code stringlengths 17 6.64M |
|---|
class AffinePermutationGroupGeneric(UniqueRepresentation, Parent):
'\n The generic affine permutation group class, in which we define all type-free\n methods for the specific affine permutation groups.\n '
def __init__(self, cartan_type):
"\n TESTS::\n\n sage: AffinePermutationGroup(['A',7,1])\n The group of affine permutations of type ['A', 7, 1]\n "
Parent.__init__(self, category=AffineWeylGroups())
ct = CartanType(cartan_type)
self.k = ct.n
self.n = ct.rank()
if (ct.letter == 'A'):
self.N = (self.k + 1)
elif ((ct.letter == 'B') or (ct.letter == 'C') or (ct.letter == 'D')):
self.N = ((2 * self.k) + 1)
elif (ct.letter == 'G'):
self.N = 6
self._cartan_type = ct
def _element_constructor_(self, *args, **keywords):
"\n TESTS::\n\n sage: AffinePermutationGroup(['A',7,1])([3, -1, 0, 6, 5, 4, 10, 9])\n Type A affine permutation with window [3, -1, 0, 6, 5, 4, 10, 9]\n "
return self.element_class(self, *args, **keywords)
def _repr_(self):
"\n TESTS::\n\n sage: AffinePermutationGroup(['A',7,1])\n The group of affine permutations of type ['A', 7, 1]\n "
return ('The group of affine permutations of type ' + str(self.cartan_type()))
def _test_enumeration(self, n=4, **options):
"\n Test that ``self`` has same number of elements of length ``n`` as the\n Weyl Group implementation.\n\n Combined with ``self._test_coxeter_relations`` this shows isomorphism\n up to length ``n``.\n\n TESTS::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: A._test_enumeration(3)\n "
tester = self._tester(**options)
n1 = len(list(self.elements_of_length(n)))
W = self.weyl_group()
I = W.weak_order_ideal(ConstantFunction(True), side='right')
n2 = len(list(I.elements_of_depth_iterator(n)))
tester.assertEqual(n1, n2, 'number of (ranked) elements of affine permutation group disagrees with Weyl group')
def weyl_group(self):
"\n Returns the Weyl Group of the same type as ``self``.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: A.weyl_group()\n Weyl Group of type ['A', 7, 1] (as a matrix group acting on the root space)\n "
return WeylGroup(self._cartan_type)
def classical(self):
"\n Returns the finite permutation group.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: A.classical()\n Symmetric group of order 8! as a permutation group\n "
if (self._cartan_type.letter == 'A'):
return SymmetricGroup((self.k + 1))
return WeylGroup(self._cartan_type.classical())
def cartan_type(self):
"\n Returns the Cartan type of ``self``.\n\n EXAMPLES::\n\n sage: AffinePermutationGroup(['A',7,1]).cartan_type()\n ['A', 7, 1]\n "
return self._cartan_type
def cartan_matrix(self):
"\n Returns the Cartan matrix of ``self``.\n\n EXAMPLES::\n\n sage: AffinePermutationGroup(['A',7,1]).cartan_matrix()\n [ 2 -1 0 0 0 0 0 -1]\n [-1 2 -1 0 0 0 0 0]\n [ 0 -1 2 -1 0 0 0 0]\n [ 0 0 -1 2 -1 0 0 0]\n [ 0 0 0 -1 2 -1 0 0]\n [ 0 0 0 0 -1 2 -1 0]\n [ 0 0 0 0 0 -1 2 -1]\n [-1 0 0 0 0 0 -1 2]\n "
return self.cartan_type().cartan_matrix()
def is_crystallographic(self):
"\n Tells whether the affine permutation group is crystallographic.\n\n EXAMPLES::\n\n sage: AffinePermutationGroup(['A',7,1]).is_crystallographic()\n True\n "
return self.cartan_type().is_crystallographic()
def index_set(self):
"\n EXAMPLES::\n\n sage: AffinePermutationGroup(['A',7,1]).index_set()\n (0, 1, 2, 3, 4, 5, 6, 7)\n "
return self.cartan_type().index_set()
_index_set = index_set
def reflection_index_set(self):
"\n EXAMPLES::\n\n sage: AffinePermutationGroup(['A',7,1]).reflection_index_set()\n (0, 1, 2, 3, 4, 5, 6, 7)\n "
return self.cartan_type().index_set()
def rank(self):
"\n Rank of the affine permutation group, equal to `k+1`.\n\n EXAMPLES::\n\n sage: AffinePermutationGroup(['A',7,1]).rank()\n 8\n "
return (self.k + 1)
def random_element(self, n=None):
"\n Return a random affine permutation of length ``n``.\n\n If ``n`` is not specified, then ``n`` is chosen as a random\n non-negative integer in `[0, 1000]`.\n\n Starts at the identity, then chooses an upper cover at random.\n Not very uniform: actually constructs a uniformly random reduced word\n of length `n`. Thus we most likely get elements with lots of reduced\n words!\n\n For the actual code, see\n :meth:`sage.categories.coxeter_group.random_element_of_length`.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: A.random_element() # random\n Type A affine permutation with window [-12, 16, 19, -1, -2, 10, -3, 9]\n sage: p = A.random_element(10)\n sage: p.length() == 10\n True\n "
if (n is None):
n = randint(0, 1000)
return self.random_element_of_length(n)
def from_word(self, w):
"\n Builds an affine permutation from a given word.\n Note: Already in category as ``from_reduced_word``, but this is less\n typing!\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: A.from_word([0, 7, 4, 1, 0, 7, 5, 4, 2, 1])\n Type A affine permutation with window [3, -1, 0, 6, 5, 4, 10, 9]\n "
return self.from_reduced_word(w)
@cached_method
def _an_element_(self):
"\n Returns a Coxeter element.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: A.from_word([0, 7, 4, 1, 0, 7, 5, 4, 2, 1])\n Type A affine permutation with window [3, -1, 0, 6, 5, 4, 10, 9]\n "
return self.from_reduced_word(self.index_set())
|
class AffinePermutationGroupTypeA(AffinePermutationGroupGeneric):
@cached_method
def one(self):
"\n Return the identity element.\n\n EXAMPLES::\n\n sage: AffinePermutationGroup(['A',7,1]).one()\n Type A affine permutation with window [1, 2, 3, 4, 5, 6, 7, 8]\n\n TESTS::\n\n sage: A = AffinePermutationGroup(['A',5,1])\n sage: A==loads(dumps(A))\n True\n sage: TestSuite(A).run()\n "
return self([i for i in range(1, (self.k + 2))])
def from_lehmer_code(self, C, typ='decreasing', side='right'):
"\n Return the affine permutation with the supplied Lehmer code (a weak\n composition with `k+1` parts, at least one of which is 0).\n\n INPUT:\n\n - ``typ`` -- ``'increasing'`` or ``'decreasing'``\n (default: ``'decreasing'``); type of product\n - ``side`` -- ``'right'`` or ``'left'`` (default: ``'right'``);\n whether the decomposition is from the right or left\n\n EXAMPLES::\n\n sage: import itertools\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p = A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.to_lehmer_code()\n [0, 3, 3, 0, 1, 2, 0, 1]\n sage: A.from_lehmer_code(p.to_lehmer_code()) == p\n True\n sage: orders = ('increasing','decreasing')\n sage: sides = ('left','right')\n sage: all(A.from_lehmer_code(p.to_lehmer_code(o,s),o,s) == p\n ....: for o,s in itertools.product(orders,sides))\n True\n "
if ((len(C) - 1) != self.k):
raise ValueError('composition must have {} entries'.format((self.k + 1)))
if (0 not in C):
raise ValueError('composition must contain a zero entry')
k = self.k
for r in range((self.k + 1)):
if (C[r] == 0):
break
D = list(C)
if ((typ[0], side[0]) == ('d', 'r')):
(t0, s0) = ((- 1), 1)
if ((typ[0], side[0]) == ('i', 'r')):
(t0, s0) = (1, 1)
if ((typ[0], side[0]) == ('d', 'l')):
(t0, s0) = ((- 1), (- 1))
if ((typ[0], side[0]) == ('i', 'l')):
(t0, s0) = (1, (- 1))
row = 0
listy = []
while (sum(D) > 0):
l = (['x'] * (self.k + 1))
ll = []
for j in range((self.k + 1)):
pos = ((r + ((s0 * t0) * j)) % (k + 1))
residue = ((r + ((s0 * t0) * (row + j))) % (k + 1))
if (D[pos] != 0):
ll.append(residue)
l[pos] = [residue]
D[pos] -= 1
if (side[0] == 'l'):
ll.reverse()
listy.append(ll)
row += 1
if (side[0] == 'r'):
listy.reverse()
x = self.one()
for ll in listy:
for i in ll:
x = x.apply_simple_reflection_right(i)
return x
Element = AffinePermutationTypeA
|
class AffinePermutationGroupTypeC(AffinePermutationGroupGeneric):
@cached_method
def one(self):
"\n Return the identity element.\n\n EXAMPLES::\n\n sage: ct=CartanType(['C',4,1])\n sage: C = AffinePermutationGroup(ct)\n sage: C.one()\n Type C affine permutation with window [1, 2, 3, 4]\n sage: C.one()*C.one()==C.one()\n True\n\n TESTS::\n\n sage: C = AffinePermutationGroup(['C',4,1])\n sage: C==loads(dumps(C))\n True\n sage: TestSuite(C).run()\n "
return self(list(range(1, (self.k + 1))))
Element = AffinePermutationTypeC
|
class AffinePermutationGroupTypeB(AffinePermutationGroupTypeC):
Element = AffinePermutationTypeB
|
class AffinePermutationGroupTypeD(AffinePermutationGroupTypeC):
Element = AffinePermutationTypeD
|
class AffinePermutationGroupTypeG(AffinePermutationGroupGeneric):
@cached_method
def one(self):
"\n Return the identity element.\n\n EXAMPLES::\n\n sage: AffinePermutationGroup(['G',2,1]).one()\n Type G affine permutation with window [1, 2, 3, 4, 5, 6]\n\n TESTS::\n\n sage: G = AffinePermutationGroup(['G',2,1])\n sage: G==loads(dumps(G))\n True\n sage: TestSuite(G).run()\n "
return self([1, 2, 3, 4, 5, 6])
Element = AffinePermutationTypeG
|
class GenericBacktracker():
'\n A generic backtrack tool for exploring a search space organized as a tree,\n with branch pruning, etc.\n\n See also :class:`RecursivelyEnumeratedSet_forest` for\n handling simple special cases.\n '
def __init__(self, initial_data, initial_state):
'\n EXAMPLES::\n\n sage: from sage.combinat.backtrack import GenericBacktracker\n sage: p = GenericBacktracker([], 1)\n sage: loads(dumps(p))\n <sage.combinat.backtrack.GenericBacktracker object at 0x...>\n '
self._initial_data = initial_data
self._initial_state = initial_state
def __iter__(self):
'\n EXAMPLES::\n\n sage: from sage.combinat.permutation import PatternAvoider\n sage: p = PatternAvoider(Permutations(4), [[1,3,2]])\n sage: len(list(p)) # needs sage.combinat\n 14\n '
stack = []
stack.append(self._rec(self._initial_data, self._initial_state))
done = False
while (not done):
try:
(obj, state, yld) = next(stack[(- 1)])
except StopIteration:
stack.pop()
done = (len(stack) == 0)
continue
if (yld is True):
(yield obj)
if (state is not None):
stack.append(self._rec(obj, state))
|
class PositiveIntegerSemigroup(UniqueRepresentation, RecursivelyEnumeratedSet_forest):
"\n The commutative additive semigroup of positive integers.\n\n This class provides an example of algebraic structure which\n inherits from :class:`RecursivelyEnumeratedSet_forest`. It builds the positive\n integers a la Peano, and endows it with its natural commutative\n additive semigroup structure.\n\n EXAMPLES::\n\n sage: from sage.combinat.backtrack import PositiveIntegerSemigroup\n sage: PP = PositiveIntegerSemigroup()\n sage: PP.category()\n Join of Category of monoids and Category of commutative additive semigroups and Category of infinite enumerated sets and Category of facade sets\n sage: PP.cardinality()\n +Infinity\n sage: PP.one()\n 1\n sage: PP.an_element()\n 1\n sage: some_elements = list(PP.some_elements()); some_elements\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]\n\n TESTS::\n\n sage: from sage.combinat.backtrack import PositiveIntegerSemigroup\n sage: PP = PositiveIntegerSemigroup()\n\n We factor out the long test from the ``TestSuite``::\n\n sage: TestSuite(PP).run(skip='_test_enumerated_set_contains')\n sage: PP._test_enumerated_set_contains() # long time\n "
def __init__(self):
'\n TESTS::\n\n sage: from sage.combinat.backtrack import PositiveIntegerSemigroup\n sage: PP = PositiveIntegerSemigroup()\n '
RecursivelyEnumeratedSet_forest.__init__(self, facade=ZZ, category=(InfiniteEnumeratedSets(), CommutativeAdditiveSemigroups(), Monoids()))
def roots(self):
'\n Return the single root of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.backtrack import PositiveIntegerSemigroup\n sage: PP = PositiveIntegerSemigroup()\n sage: list(PP.roots())\n [1]\n '
return [ZZ(1)]
def children(self, x):
'\n Return the single child ``x+1`` of the integer ``x``\n\n EXAMPLES::\n\n sage: from sage.combinat.backtrack import PositiveIntegerSemigroup\n sage: PP = PositiveIntegerSemigroup()\n sage: list(PP.children(1))\n [2]\n sage: list(PP.children(42))\n [43]\n '
return [ZZ((x + 1))]
def one(self):
'\n Return the unit of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.backtrack import PositiveIntegerSemigroup\n sage: PP = PositiveIntegerSemigroup()\n sage: PP.one()\n 1\n '
return self.first()
|
class BaxterPermutations(UniqueRepresentation, Parent):
'\n The combinatorial class of Baxter permutations.\n\n A Baxter permutation is a permutation avoiding the generalized\n permutation patterns `2-41-3` and `3-14-2`. In other words, a\n permutation `\\sigma` is a Baxter permutation if for any subword `u\n := u_1u_2u_3u_4` of `\\sigma` such that the letters `u_2` and `u_3`\n are adjacent in `\\sigma`, the standardized version of `u` is\n neither `2413` nor `3142`.\n\n See [Gir2012]_ for a study of Baxter permutations.\n\n INPUT:\n\n - ``n`` -- (default: ``None``) a nonnegative integer, the size of\n the permutations.\n\n OUTPUT:\n\n Return the combinatorial class of the Baxter permutations of size ``n``\n if ``n`` is not ``None``. Otherwise, return the combinatorial class\n of all Baxter permutations.\n\n EXAMPLES::\n\n sage: BaxterPermutations(5)\n Baxter permutations of size 5\n sage: BaxterPermutations()\n Baxter permutations\n '
@staticmethod
def __classcall_private__(classe, n=None):
'\n EXAMPLES::\n\n sage: BaxterPermutations(5)\n Baxter permutations of size 5\n sage: BaxterPermutations()\n Baxter permutations\n '
if (n is None):
return BaxterPermutations_all()
return BaxterPermutations_size(n)
|
class BaxterPermutations_size(BaxterPermutations):
'\n The enumerated set of Baxter permutations of a given size.\n\n See :class:`BaxterPermutations` for the definition of Baxter\n permutations.\n\n EXAMPLES::\n\n sage: from sage.combinat.baxter_permutations import BaxterPermutations_size\n sage: BaxterPermutations_size(5)\n Baxter permutations of size 5\n '
def __init__(self, n):
'\n EXAMPLES::\n\n sage: from sage.combinat.baxter_permutations import BaxterPermutations_size\n sage: BaxterPermutations_size(5)\n Baxter permutations of size 5\n '
self.element_class = Permutations(n).element_class
self._n = ZZ(n)
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
super().__init__(category=FiniteEnumeratedSets())
def _repr_(self):
'\n Return a string representation of ``self``\n\n EXAMPLES::\n\n sage: from sage.combinat.baxter_permutations import BaxterPermutations_size\n sage: BaxterPermutations_size(5)\n Baxter permutations of size 5\n '
return ('Baxter permutations of size %s' % self._n)
def __contains__(self, x):
'\n Return ``True`` if and only if ``x`` is a Baxter permutation of\n size ``self._n``.\n\n INPUT:\n\n - ``x`` -- a permutation.\n\n EXAMPLES::\n\n sage: Permutation([2, 1, 4, 3]) in BaxterPermutations(4)\n True\n sage: Permutation([2, 1, 4, 3]) in BaxterPermutations(5)\n False\n sage: Permutation([3, 1, 4, 2]) in BaxterPermutations(4)\n False\n sage: [len([p for p in Permutations(n) if p in BaxterPermutations(n)]) for n in range(7)]\n [1, 1, 2, 6, 22, 92, 422]\n sage: sorted([p for p in Permutations(6) if p in BaxterPermutations(6)]) == sorted(BaxterPermutations(6).list())\n True\n '
if (x not in Permutations(self._n)):
return False
for i in range(1, (len(x) - 1)):
a = x[i]
b = x[(i + 1)]
if (a < b):
max_l = 0
for x_j in x[:i]:
if ((x_j > a) and (x_j < b) and (x_j > max_l)):
max_l = x_j
min_r = (len(x) + 1)
for x_j in x[(i + 2):]:
if ((x_j > a) and (x_j < b) and (x_j < min_r)):
min_r = x_j
if (max_l > min_r):
return False
else:
min_l = (len(x) + 1)
for x_j in x[:i]:
if ((x_j < a) and (x_j > b) and (x_j < min_l)):
min_l = x_j
max_r = 0
for x_j in x[(i + 2):]:
if ((x_j < a) and (x_j > b) and (x_j > max_r)):
max_r = x_j
if (min_l < max_r):
return False
return True
def __iter__(self):
'\n Efficient generation of Baxter permutations.\n\n OUTPUT:\n\n An iterator over the Baxter permutations of size ``self._n``.\n\n EXAMPLES::\n\n sage: BaxterPermutations(4).list()\n [[4, 3, 2, 1], [3, 4, 2, 1], [3, 2, 4, 1], [3, 2, 1, 4], [2, 4, 3, 1],\n [4, 2, 3, 1], [2, 3, 4, 1], [2, 3, 1, 4], [2, 1, 4, 3], [4, 2, 1, 3],\n [2, 1, 3, 4], [1, 4, 3, 2], [4, 1, 3, 2], [1, 3, 4, 2], [1, 3, 2, 4],\n [4, 3, 1, 2], [3, 4, 1, 2], [3, 1, 2, 4], [1, 2, 4, 3], [1, 4, 2, 3],\n [4, 1, 2, 3], [1, 2, 3, 4]]\n sage: [len(BaxterPermutations(n)) for n in range(9)]\n [1, 1, 2, 6, 22, 92, 422, 2074, 10754]\n\n TESTS::\n\n sage: all(a in BaxterPermutations(n) for n in range(7)\n ....: for a in BaxterPermutations(n))\n True\n\n ALGORITHM:\n\n The algorithm using generating trees described in [BBMF2008]_ is used.\n The idea is that all Baxter permutations of size `n + 1` can be\n obtained by inserting the letter `n + 1` either just before a left\n to right maximum or just after a right to left maximum of a Baxter\n permutation of size `n`.\n '
if (self._n == 0):
(yield Permutations(0)([]))
elif (self._n == 1):
(yield Permutations(1)([1]))
else:
for b in BaxterPermutations((self._n - 1)):
for j in b.reverse().saliances():
i = ((self._n - 2) - j)
(yield Permutations(self._n)(((b[:i] + [self._n]) + b[i:])))
for i in b.saliances():
(yield Permutations(self._n)(((b[:(i + 1)] + [self._n]) + b[(i + 1):])))
def _an_element_(self):
'\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: BaxterPermutations(4)._an_element_()\n [4, 3, 2, 1]\n '
return self.first()
def cardinality(self):
'\n Return the number of Baxter permutations of size ``self._n``.\n\n For any positive integer `n`, the number of Baxter\n permutations of size `n` equals\n\n .. MATH::\n\n \\sum_{k=1}^n \\dfrac\n {\\binom{n+1}{k-1} \\binom{n+1}{k} \\binom{n+1}{k+1}}\n {\\binom{n+1}{1} \\binom{n+1}{2}} .\n\n This is :oeis:`A001181`.\n\n EXAMPLES::\n\n sage: [BaxterPermutations(n).cardinality() for n in range(13)]\n [1, 1, 2, 6, 22, 92, 422, 2074, 10754, 58202, 326240, 1882960, 11140560]\n\n sage: BaxterPermutations(3r).cardinality()\n 6\n sage: parent(_)\n Integer Ring\n '
if (self._n == 0):
return 1
from sage.arith.misc import binomial
return sum(((((binomial((self._n + 1), k) * binomial((self._n + 1), (k + 1))) * binomial((self._n + 1), (k + 2))) // ((self._n + 1) * binomial((self._n + 1), 2))) for k in range(self._n)))
|
class BaxterPermutations_all(DisjointUnionEnumeratedSets, BaxterPermutations):
'\n The enumerated set of all Baxter permutations.\n\n See :class:`BaxterPermutations` for the definition of Baxter\n permutations.\n\n EXAMPLES::\n\n sage: from sage.combinat.baxter_permutations import BaxterPermutations_all\n sage: BaxterPermutations_all()\n Baxter permutations\n '
def __init__(self, n=None):
'\n EXAMPLES::\n\n sage: from sage.combinat.baxter_permutations import BaxterPermutations_all\n sage: BaxterPermutations_all()\n Baxter permutations\n '
self.element_class = Permutations().element_class
from sage.sets.non_negative_integers import NonNegativeIntegers
from sage.sets.family import Family
DisjointUnionEnumeratedSets.__init__(self, Family(NonNegativeIntegers(), BaxterPermutations_size), facade=False, keepkey=False)
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.baxter_permutations import BaxterPermutations_all\n sage: BaxterPermutations_all()\n Baxter permutations\n '
return 'Baxter permutations'
def __contains__(self, x):
'\n Return ``True`` if and only if ``x`` is a Baxter permutation.\n\n INPUT:\n\n - ``x`` -- any object.\n\n EXAMPLES::\n\n sage: Permutation([4, 2, 1, 7, 3, 8, 5, 6]) in BaxterPermutations()\n False\n sage: Permutation([4, 3, 6, 9, 7, 5, 1, 2, 8]) in BaxterPermutations()\n True\n\n TESTS::\n\n sage: 42 in BaxterPermutations()\n False\n '
if (x not in Permutations()):
return False
return (x in BaxterPermutations(len(x)))
def to_pair_of_twin_binary_trees(self, p):
'\n Apply a bijection between Baxter permutations of size ``self._n``\n and the set of pairs of twin binary trees with ``self._n`` nodes.\n\n INPUT:\n\n - ``p`` -- a Baxter permutation.\n\n OUTPUT:\n\n The pair of twin binary trees `(T_L, T_R)` where `T_L`\n (resp. `T_R`) is obtained by inserting the letters of ``p`` from\n left to right (resp. right to left) following the binary search\n tree insertion algorithm. This is called the *Baxter P-symbol*\n in [Gir2012]_ Definition 4.1.\n\n .. NOTE::\n\n This method only works when ``p`` is a permutation. For words\n with repeated letters, it would return two "right binary\n search trees" (in the terminology of [Gir2012]_), which conflicts\n with the definition in [Gir2012]_.\n\n EXAMPLES::\n\n sage: BP = BaxterPermutations()\n sage: BP.to_pair_of_twin_binary_trees(Permutation([])) # needs sage.graphs\n (., .)\n sage: BP.to_pair_of_twin_binary_trees(Permutation([1, 2, 3])) # needs sage.graphs\n (1[., 2[., 3[., .]]], 3[2[1[., .], .], .])\n sage: BP.to_pair_of_twin_binary_trees(Permutation([3, 4, 1, 2])) # needs sage.graphs\n (3[1[., 2[., .]], 4[., .]], 2[1[., .], 4[3[., .], .]])\n '
from sage.combinat.binary_tree import LabelledBinaryTree
left = LabelledBinaryTree(None)
right = LabelledBinaryTree(None)
for a in p:
left = left.binary_search_insert(a)
for a in reversed(p):
right = right.binary_search_insert(a)
return (left, right)
|
class Bijectionist(SageObject):
'\n A toolbox to list all possible bijections between two finite sets\n under various constraints.\n\n INPUT:\n\n - ``A``, ``B`` -- sets of equal size, given as a list\n\n - ``tau`` -- (optional) a function from ``B`` to ``Z``, in case of\n ``None``, the identity map ``lambda x: x`` is used\n\n - ``alpha_beta`` -- (optional) a list of pairs of statistics ``alpha`` from\n ``A`` to ``W`` and ``beta`` from ``B`` to ``W``\n\n - ``P`` -- (optional) a partition of ``A``\n\n - ``pi_rho`` -- (optional) a list of triples ``(k, pi, rho)``, where\n\n * ``pi`` -- a ``k``-ary operation composing objects in ``A`` and\n * ``rho`` -- a ``k``-ary function composing statistic values in ``Z``\n\n - ``elements_distributions`` -- (optional) a list of pairs ``(tA, tZ)``,\n specifying the distributions of ``tA``\n\n - ``value_restrictions`` -- (optional) a list of pairs ``(a, tZ)``,\n restricting the possible values of ``a``\n\n - ``solver`` -- (optional) the backend used to solve the mixed integer\n linear programs\n\n ``W`` and ``Z`` can be arbitrary sets. As a natural example we may think\n of the natural numbers or tuples of integers.\n\n We are looking for a statistic `s: A\\to Z` and a bijection `S: A\\to B` such\n that\n\n - `s = \\tau \\circ S`: the statistics `s` and `\\tau` are equidistributed and\n `S` is an intertwining bijection.\n\n - `\\alpha = \\beta \\circ S`: the statistics `\\alpha` and `\\beta` are\n equidistributed and `S` is an intertwining bijection.\n\n - `s` is constant on the blocks of `P`.\n\n - `s(\\pi(a_1,\\dots, a_k)) = \\rho(s(a_1),\\dots, s(a_k))`.\n\n Additionally, we may require that\n\n - `s(a)\\in Z_a` for specified sets `Z_a\\subseteq Z`, and\n\n - `s|_{\\tilde A}` has a specified distribution for specified sets `\\tilde A\n \\subset A`.\n\n If `\\tau` is the identity, the two unknown functions `s` and `S` coincide.\n Although we do not exclude other bijective choices for `\\tau`, they\n probably do not make sense.\n\n If we want that `S` is graded, i.e. if elements of `A` and `B` have a\n notion of size and `S` should preserve this size, we can add grading\n statistics as `\\alpha` and `\\beta`. Since `\\alpha` and `\\beta` will be\n equidistributed with `S` as an intertwining bijection, `S` will then also\n be graded.\n\n In summary, we have the following two commutative diagrams, where `s` and\n `S` are unknown functions.\n\n .. MATH::\n\n \\begin{array}{rrl}\n & A \\\\\n {\\scriptstyle\\alpha}\\swarrow & {\\scriptstyle S}\\downarrow & \\searrow{\\scriptstyle s}\\\\\n W \\overset{\\beta}{\\leftarrow} & B & \\overset{\\tau}{\\rightarrow} Z\n \\end{array}\n \\qquad\n \\begin{array}{lcl}\n A^k &\\overset{\\pi}{\\rightarrow} & A\\\\\n \\downarrow{\\scriptstyle s^k} & & \\downarrow{\\scriptstyle s}\\\\\n Z^k &\\overset{\\rho}{\\rightarrow} & Z\\\\\n \\end{array}\n\n .. NOTE::\n\n If `\\tau` is the identity map, the partition `P` of `A` necessarily\n consists only of singletons.\n\n .. NOTE::\n\n The order of invocation of the methods with prefix ``set``, i.e.,\n :meth:`set_statistics`, :meth:`set_intertwining_relations`,\n :meth:`set_constant_blocks`, etc., is irrelevant. Calling any of these\n methods a second time overrides the previous specification.\n\n '
def __init__(self, A, B, tau=None, alpha_beta=tuple(), P=None, pi_rho=tuple(), phi_psi=tuple(), Q=None, elements_distributions=tuple(), value_restrictions=tuple(), solver=None, key=None):
'\n Initialize the bijectionist.\n\n TESTS:\n\n Check that large input sets are handled well::\n\n sage: A = B = range(20000)\n sage: bij = Bijectionist(A, B) # long time\n '
self._A = list(A)
self._B = list(B)
assert (len(self._A) == len(set(self._A))), 'A must have distinct items'
assert (len(self._B) == len(set(self._B))), 'B must have distinct items'
self._bmilp = None
self._sorter = {}
self._sorter['A'] = (lambda x: sorted(x, key=self._A.index))
self._sorter['B'] = (lambda x: sorted(x, key=self._B.index))
if (tau is None):
self._tau = {b: b for b in self._B}
else:
self._tau = {b: tau(b) for b in self._B}
self._Z = set(self._tau.values())
if ((key is not None) and ('Z' in key)):
self._sorter['Z'] = (lambda x: sorted(x, key=key['Z']))
self._Z = self._sorter['Z'](self._Z)
else:
try:
self._Z = sorted(self._Z)
self._sorter['Z'] = (lambda x: sorted(x))
except TypeError:
self._Z = list(self._Z)
self._sorter['Z'] = (lambda x: list(x))
if (P is None):
P = []
self.set_statistics(*alpha_beta)
self.set_value_restrictions(*value_restrictions)
self.set_distributions(*elements_distributions)
self.set_quadratic_relation(*phi_psi)
self.set_homomesic(Q)
self.set_intertwining_relations(*pi_rho)
self.set_constant_blocks(P)
self._solver = solver
def set_constant_blocks(self, P):
"\n Declare that `s: A\\to Z` is constant on each block of `P`.\n\n .. WARNING::\n\n Any restriction imposed by a previous invocation of\n :meth:`set_constant_blocks` will be overwritten,\n including restrictions discovered by\n :meth:`set_intertwining_relations` and\n :meth:`solutions_iterator`!\n\n A common example is to use the orbits of a bijection acting\n on `A`. This can be achieved using the function\n :meth:`~sage.combinat.cyclic_sieving_phenomenon.orbit_decomposition`.\n\n INPUT:\n\n - ``P`` -- a set partition of `A`, singletons may be omitted\n\n EXAMPLES:\n\n Initially the partitions are set to singleton blocks. The\n current partition can be reviewed using\n :meth:`constant_blocks`::\n\n sage: A = B = 'abcd'\n sage: bij = Bijectionist(A, B, lambda x: B.index(x) % 2)\n sage: bij.constant_blocks()\n {}\n\n sage: bij.set_constant_blocks([['a', 'c']])\n sage: bij.constant_blocks()\n {{'a', 'c'}}\n\n We now add a map that combines some blocks::\n\n sage: def pi(p1, p2): return 'abcdefgh'[A.index(p1) + A.index(p2)]\n sage: def rho(s1, s2): return (s1 + s2) % 2\n sage: bij.set_intertwining_relations((2, pi, rho))\n sage: list(bij.solutions_iterator())\n [{'a': 0, 'b': 1, 'c': 0, 'd': 1}]\n sage: bij.constant_blocks()\n {{'a', 'c'}, {'b', 'd'}}\n\n Setting constant blocks overrides any previous assignment::\n\n sage: bij.set_constant_blocks([['a', 'b']])\n sage: bij.constant_blocks()\n {{'a', 'b'}}\n\n If there is no solution, and the coarsest partition is\n requested, an error is raised::\n\n sage: bij.constant_blocks(optimal=True)\n Traceback (most recent call last):\n ...\n StopIteration\n\n "
self._bmilp = None
self._P = DisjointSet(self._A)
P = sorted((self._sorter['A'](p) for p in P))
for p in P:
for a in p:
self._P.union(p[0], a)
self._compute_possible_block_values()
def constant_blocks(self, singletons=False, optimal=False):
'\n Return the set partition `P` of `A` such that `s: A\\to Z` is\n known to be constant on the blocks of `P`.\n\n INPUT:\n\n - ``singletons`` -- (optional, default: ``False``) whether or not to\n include singleton blocks in the output\n\n - ``optimal`` -- (optional, default: ``False``) whether or not to\n compute the coarsest possible partition\n\n .. NOTE::\n\n computing the coarsest possible partition may be\n computationally expensive, but may speed up generating\n solutions.\n\n EXAMPLES::\n\n sage: A = B = ["a", "b", "c"]\n sage: bij = Bijectionist(A, B, lambda x: 0)\n sage: bij.set_constant_blocks([["a", "b"]])\n sage: bij.constant_blocks()\n {{\'a\', \'b\'}}\n\n sage: bij.constant_blocks(singletons=True)\n {{\'a\', \'b\'}, {\'c\'}}\n\n '
if optimal:
self._forced_constant_blocks()
if singletons:
return SetPartition(self._P)
return SetPartition((p for p in self._P if (len(p) > 1)))
def set_statistics(self, *alpha_beta):
'\n Set constraints of the form `\\alpha = \\beta\\circ S`.\n\n .. WARNING::\n\n Any restriction imposed by a previous invocation of\n :meth:`set_statistics` will be overwritten!\n\n INPUT:\n\n - ``alpha_beta`` -- one or more pairs `(\\alpha: A\\to W,\n \\beta: B\\to W)`\n\n If the statistics `\\alpha` and `\\beta` are not\n equidistributed, an error is raised.\n\n ALGORITHM:\n\n We add\n\n .. MATH::\n\n \\sum_{a\\in A, z\\in Z} x_{p(a), z} s^z t^{\\alpha(a)}\n = \\sum_{b\\in B} s^{\\tau(b)} t(\\beta(b))\n\n as a matrix equation to the MILP.\n\n EXAMPLES:\n\n We look for bijections `S` on permutations such that the\n number of weak exceedences of `S(\\pi)` equals the number of\n descents of `\\pi`, and statistics `s`, such that the number\n of fixed points of `S(\\pi)` equals `s(\\pi)`::\n\n sage: N = 4; A = B = [permutation for n in range(N) for permutation in Permutations(n)]\n sage: def wex(p): return len(p.weak_excedences())\n sage: def fix(p): return len(p.fixed_points())\n sage: def des(p): return len(p.descents(final_descent=True)) if p else 0\n sage: def adj(p): return len([e for (e, f) in zip(p, p[1:]+[0]) if e == f+1])\n sage: bij = Bijectionist(A, B, fix)\n sage: bij.set_statistics((wex, des), (len, len))\n sage: for solution in sorted(list(bij.solutions_iterator()), key=lambda d: tuple(sorted(d.items()))):\n ....: print(solution)\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 0, [2, 1, 3]: 0, [2, 3, 1]: 1, [3, 1, 2]: 3, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 0, [2, 1, 3]: 1, [2, 3, 1]: 0, [3, 1, 2]: 3, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 0, [2, 1, 3]: 1, [2, 3, 1]: 1, [3, 1, 2]: 3, [3, 2, 1]: 0}\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 1, [2, 1, 3]: 0, [2, 3, 1]: 0, [3, 1, 2]: 3, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 1, [2, 1, 3]: 0, [2, 3, 1]: 1, [3, 1, 2]: 3, [3, 2, 1]: 0}\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 1, [2, 1, 3]: 1, [2, 3, 1]: 0, [3, 1, 2]: 3, [3, 2, 1]: 0}\n\n sage: bij = Bijectionist(A, B, fix)\n sage: bij.set_statistics((wex, des), (fix, adj), (len, len))\n sage: for solution in sorted(list(bij.solutions_iterator()), key=lambda d: tuple(sorted(d.items()))):\n ....: print(solution)\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 0, [2, 1, 3]: 1, [2, 3, 1]: 0, [3, 1, 2]: 3, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 1, [2, 1, 3]: 0, [2, 3, 1]: 0, [3, 1, 2]: 3, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 1, [2, 1, 3]: 1, [2, 3, 1]: 0, [3, 1, 2]: 3, [3, 2, 1]: 0}\n\n Calling this with non-equidistributed statistics yields an error::\n\n sage: bij = Bijectionist(A, B, fix)\n sage: bij.set_statistics((wex, fix))\n Traceback (most recent call last):\n ...\n ValueError: statistics alpha and beta are not equidistributed\n\n TESTS:\n\n Calling ``set_statistics`` without arguments should restore the previous state::\n\n sage: N = 3; A = B = [permutation for n in range(N) for permutation in Permutations(n)]\n sage: def wex(p): return len(p.weak_excedences())\n sage: def fix(p): return len(p.fixed_points())\n sage: def des(p): return len(p.descents(final_descent=True)) if p else 0\n sage: bij = Bijectionist(A, B, fix)\n sage: bij.set_statistics((wex, des), (len, len))\n sage: for solution in bij.solutions_iterator():\n ....: print(solution)\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2}\n sage: bij.set_statistics()\n sage: for solution in sorted(list(bij.solutions_iterator()), key=lambda d: tuple(sorted(d.items()))):\n ....: print(solution)\n {[]: 0, [1]: 0, [1, 2]: 1, [2, 1]: 2}\n {[]: 0, [1]: 0, [1, 2]: 2, [2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0}\n {[]: 0, [1]: 2, [1, 2]: 0, [2, 1]: 1}\n {[]: 0, [1]: 2, [1, 2]: 1, [2, 1]: 0}\n {[]: 1, [1]: 0, [1, 2]: 0, [2, 1]: 2}\n {[]: 1, [1]: 0, [1, 2]: 2, [2, 1]: 0}\n {[]: 1, [1]: 2, [1, 2]: 0, [2, 1]: 0}\n {[]: 2, [1]: 0, [1, 2]: 0, [2, 1]: 1}\n {[]: 2, [1]: 0, [1, 2]: 1, [2, 1]: 0}\n {[]: 2, [1]: 1, [1, 2]: 0, [2, 1]: 0}\n\n '
self._bmilp = None
self._n_statistics = len(alpha_beta)
self._alpha = (lambda p: tuple((arg[0](p) for arg in alpha_beta)))
self._beta = (lambda p: tuple((arg[1](p) for arg in alpha_beta)))
self._statistics_fibers = {}
for a in self._A:
v = self._alpha(a)
if (v not in self._statistics_fibers):
self._statistics_fibers[v] = ([], [])
self._statistics_fibers[v][0].append(a)
for b in self._B:
v = self._beta(b)
if (v not in self._statistics_fibers):
raise ValueError(f'statistics alpha and beta do not have the same image, {v} is not a value of alpha, but of beta')
self._statistics_fibers[v][1].append(b)
if (not all(((len(fiber[0]) == len(fiber[1])) for fiber in self._statistics_fibers.values()))):
raise ValueError('statistics alpha and beta are not equidistributed')
self._W = list(self._statistics_fibers)
tau_beta_inverse = {}
self._statistics_possible_values = {}
for a in self._A:
v = self._alpha(a)
if (v not in tau_beta_inverse):
tau_beta_inverse[v] = set((self._tau[b] for b in self._statistics_fibers[v][1]))
self._statistics_possible_values[a] = tau_beta_inverse[v]
def statistics_fibers(self):
'\n Return a dictionary mapping statistic values in `W` to their\n preimages in `A` and `B`.\n\n This is a (computationally) fast way to obtain a first\n impression which objects in `A` should be mapped to which\n objects in `B`.\n\n EXAMPLES::\n\n sage: A = B = [permutation for n in range(4) for permutation in Permutations(n)]\n sage: tau = Permutation.longest_increasing_subsequence_length\n sage: def wex(p): return len(p.weak_excedences())\n sage: def fix(p): return len(p.fixed_points())\n sage: def des(p): return len(p.descents(final_descent=True)) if p else 0\n sage: def adj(p): return len([e for (e, f) in zip(p, p[1:]+[0]) if e == f+1])\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_statistics((len, len), (wex, des), (fix, adj))\n sage: table([[key, AB[0], AB[1]] for key, AB in bij.statistics_fibers().items()])\n (0, 0, 0) [[]] [[]]\n (1, 1, 1) [[1]] [[1]]\n (2, 2, 2) [[1, 2]] [[2, 1]]\n (2, 1, 0) [[2, 1]] [[1, 2]]\n (3, 3, 3) [[1, 2, 3]] [[3, 2, 1]]\n (3, 2, 1) [[1, 3, 2], [2, 1, 3], [3, 2, 1]] [[1, 3, 2], [2, 1, 3], [2, 3, 1]]\n (3, 2, 0) [[2, 3, 1]] [[3, 1, 2]]\n (3, 1, 0) [[3, 1, 2]] [[1, 2, 3]]\n\n '
return self._statistics_fibers
def statistics_table(self, header=True):
"\n Provide information about all elements of `A` with corresponding\n `\\alpha` values and all elements of `B` with corresponding\n `\\beta` and `\\tau` values.\n\n INPUT:\n\n - ``header`` -- (default: ``True``) whether to include a\n header with the standard Greek letters\n\n OUTPUT:\n\n A pair of lists suitable for :class:`~sage.misc.table.table`,\n where\n\n - the first contains the elements of `A` together with the\n values of `\\alpha`\n\n - the second contains the elements of `B` together with the\n values of `\\tau` and `\\beta`\n\n EXAMPLES::\n\n sage: A = B = [permutation for n in range(4) for permutation in Permutations(n)]\n sage: tau = Permutation.longest_increasing_subsequence_length\n sage: def wex(p): return len(p.weak_excedences())\n sage: def fix(p): return len(p.fixed_points())\n sage: def des(p): return len(p.descents(final_descent=True)) if p else 0\n sage: def adj(p): return len([e for (e, f) in zip(p, p[1:]+[0]) if e == f+1])\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_statistics((wex, des), (fix, adj))\n sage: a, b = bij.statistics_table()\n sage: table(a, header_row=True, frame=True)\n +-----------+--------+--------+\n | a | α_1(a) | α_2(a) |\n +===========+========+========+\n | [] | 0 | 0 |\n +-----------+--------+--------+\n | [1] | 1 | 1 |\n +-----------+--------+--------+\n | [1, 2] | 2 | 2 |\n +-----------+--------+--------+\n | [2, 1] | 1 | 0 |\n +-----------+--------+--------+\n | [1, 2, 3] | 3 | 3 |\n +-----------+--------+--------+\n | [1, 3, 2] | 2 | 1 |\n +-----------+--------+--------+\n | [2, 1, 3] | 2 | 1 |\n +-----------+--------+--------+\n | [2, 3, 1] | 2 | 0 |\n +-----------+--------+--------+\n | [3, 1, 2] | 1 | 0 |\n +-----------+--------+--------+\n | [3, 2, 1] | 2 | 1 |\n +-----------+--------+--------+\n sage: table(b, header_row=True, frame=True)\n +-----------+---+--------+--------+\n | b | τ | β_1(b) | β_2(b) |\n +===========+===+========+========+\n | [] | 0 | 0 | 0 |\n +-----------+---+--------+--------+\n | [1] | 1 | 1 | 1 |\n +-----------+---+--------+--------+\n | [1, 2] | 2 | 1 | 0 |\n +-----------+---+--------+--------+\n | [2, 1] | 1 | 2 | 2 |\n +-----------+---+--------+--------+\n | [1, 2, 3] | 3 | 1 | 0 |\n +-----------+---+--------+--------+\n | [1, 3, 2] | 2 | 2 | 1 |\n +-----------+---+--------+--------+\n | [2, 1, 3] | 2 | 2 | 1 |\n +-----------+---+--------+--------+\n | [2, 3, 1] | 2 | 2 | 1 |\n +-----------+---+--------+--------+\n | [3, 1, 2] | 2 | 2 | 0 |\n +-----------+---+--------+--------+\n | [3, 2, 1] | 1 | 3 | 3 |\n +-----------+---+--------+--------+\n\n TESTS:\n\n If no statistics are given, the table should still be able to be generated::\n\n sage: A = B = [permutation for n in range(3) for permutation in Permutations(n)]\n sage: tau = Permutation.longest_increasing_subsequence_length\n sage: bij = Bijectionist(A, B, tau)\n sage: a, b = bij.statistics_table()\n sage: table(a, header_row=True, frame=True)\n +--------+\n | a |\n +========+\n | [] |\n +--------+\n | [1] |\n +--------+\n | [1, 2] |\n +--------+\n | [2, 1] |\n +--------+\n sage: table(b, header_row=True, frame=True)\n +--------+---+\n | b | τ |\n +========+===+\n | [] | 0 |\n +--------+---+\n | [1] | 1 |\n +--------+---+\n | [1, 2] | 2 |\n +--------+---+\n | [2, 1] | 1 |\n +--------+---+\n\n We can omit the header::\n\n sage: bij.statistics_table(header=True)[1]\n [['b', 'τ'], [[], 0], [[1], 1], [[1, 2], 2], [[2, 1], 1]]\n sage: bij.statistics_table(header=False)[1]\n [[[], 0], [[1], 1], [[1, 2], 2], [[2, 1], 1]]\n\n "
n_statistics = self._n_statistics
if header:
output_alphas = [(['a'] + [(('α_' + str(i)) + '(a)') for i in range(1, (n_statistics + 1))])]
else:
output_alphas = []
for a in self._A:
if (n_statistics > 0):
output_alphas.append(([a] + list(self._alpha(a))))
else:
output_alphas.append([a])
if header:
output_tau_betas = [(['b', 'τ'] + [(('β_' + str(i)) + '(b)') for i in range(1, (n_statistics + 1))])]
else:
output_tau_betas = []
for b in self._B:
if (n_statistics > 0):
output_tau_betas.append(([b, self._tau[b]] + list(self._beta(b))))
else:
output_tau_betas.append([b, self._tau[b]])
return (output_alphas, output_tau_betas)
def set_value_restrictions(self, *value_restrictions):
'\n Restrict the set of possible values `s(a)` for a given element\n `a`.\n\n .. WARNING::\n\n Any restriction imposed by a previous invocation of\n :meth:`set_value_restrictions` will be overwritten!\n\n INPUT:\n\n - ``value_restrictions`` -- one or more pairs `(a\\in A, \\tilde\n Z\\subseteq Z)`\n\n EXAMPLES:\n\n We may want to restrict the value of a given element to a\n single or multiple values. We do not require that the\n specified values are in the image of `\\tau`. In some\n cases, the restriction may not be able to provide a better\n solution, as for size 3 in the following example. ::\n\n sage: A = B = [permutation for n in range(4) for permutation in Permutations(n)]\n sage: tau = Permutation.longest_increasing_subsequence_length\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_statistics((len, len))\n sage: bij.set_value_restrictions((Permutation([1, 2]), [1]),\n ....: (Permutation([3, 2, 1]), [2, 3, 4]))\n sage: for sol in sorted(bij.solutions_iterator(), key=lambda d: sorted(d.items())):\n ....: print(sol)\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 3}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 3, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 3, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 2, [2, 1, 3]: 3, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 3, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 1, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 3}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 1, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 3, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 1, [2, 1, 3]: 2, [2, 3, 1]: 3, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 1, [2, 1, 3]: 3, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 2, [2, 1, 3]: 1, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 3}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 2, [2, 1, 3]: 1, [2, 3, 1]: 2, [3, 1, 2]: 3, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 2, [2, 1, 3]: 1, [2, 3, 1]: 3, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 1, [3, 1, 2]: 2, [3, 2, 1]: 3}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 1, [3, 1, 2]: 3, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 1, [3, 2, 1]: 3}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 3, [3, 1, 2]: 1, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 2, [2, 1, 3]: 3, [2, 3, 1]: 1, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 2, [2, 1, 3]: 3, [2, 3, 1]: 2, [3, 1, 2]: 1, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 3, [2, 1, 3]: 1, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 3, [2, 1, 3]: 2, [2, 3, 1]: 1, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 3, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 1, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 1, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 1, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 1, [3, 2, 1]: 2}\n\n However, an error occurs if the set of possible values is\n empty. In this example, the image of `\\tau` under any\n legal bijection is disjoint to the specified values.\n\n TESTS::\n\n sage: A = B = [permutation for n in range(4) for permutation in Permutations(n)]\n sage: tau = Permutation.longest_increasing_subsequence_length\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_value_restrictions((Permutation([1, 2]), [4, 5]))\n sage: bij._compute_possible_block_values()\n Traceback (most recent call last):\n ...\n ValueError: no possible values found for singleton block [[1, 2]]\n\n sage: A = B = [permutation for n in range(4) for permutation in Permutations(n)]\n sage: tau = Permutation.longest_increasing_subsequence_length\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_constant_blocks([[permutation for permutation in Permutations(n)] for n in range(4)])\n sage: bij.set_value_restrictions((Permutation([1, 2]), [4, 5]))\n sage: bij._compute_possible_block_values()\n Traceback (most recent call last):\n ...\n ValueError: no possible values found for block [[1, 2], [2, 1]]\n\n sage: A = B = [permutation for n in range(4) for permutation in Permutations(n)]\n sage: tau = Permutation.longest_increasing_subsequence_length\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_value_restrictions(((1, 2), [4, 5, 6]))\n Traceback (most recent call last):\n ...\n AssertionError: element (1, 2) was not found in A\n\n '
self._bmilp = None
set_Z = set(self._Z)
self._restrictions_possible_values = {a: set_Z for a in self._A}
for (a, values) in value_restrictions:
assert (a in self._A), f'element {a} was not found in A'
self._restrictions_possible_values[a] = self._restrictions_possible_values[a].intersection(values)
def _compute_possible_block_values(self):
'\n Update the dictionary of possible values of each block.\n\n This has to be called whenever ``self._P`` was modified.\n\n It raises a :class:`ValueError`, if the restrictions on a\n block are contradictory.\n\n TESTS::\n\n sage: A = B = [permutation for n in range(4) for permutation in Permutations(n)]\n sage: tau = Permutation.longest_increasing_subsequence_length\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_value_restrictions((Permutation([1, 2]), [4, 5]))\n sage: bij._compute_possible_block_values()\n Traceback (most recent call last):\n ...\n ValueError: no possible values found for singleton block [[1, 2]]\n\n '
self._possible_block_values = {}
for (p, block) in self._P.root_to_elements_dict().items():
sets = ([self._restrictions_possible_values[a] for a in block] + [self._statistics_possible_values[a] for a in block])
self._possible_block_values[p] = _non_copying_intersection(sets)
if (not self._possible_block_values[p]):
if (len(block) == 1):
raise ValueError(f'no possible values found for singleton block {block}')
else:
raise ValueError(f'no possible values found for block {block}')
def set_distributions(self, *elements_distributions):
'\n Specify the distribution of `s` for a subset of elements.\n\n .. WARNING::\n\n Any restriction imposed by a previous invocation of\n :meth:`set_distributions` will be overwritten!\n\n INPUT:\n\n - one or more pairs of `(\\tilde A, \\tilde Z)`, where `\\tilde\n A\\subseteq A` and `\\tilde Z` is a list of values in `Z` of\n the same size as `\\tilde A`\n\n This method specifies that `\\{s(a) | a\\in\\tilde A\\}` equals\n `\\tilde Z` as a multiset for each of the pairs.\n\n When specifying several distributions, the subsets of `A` do\n not have to be disjoint.\n\n ALGORITHM:\n\n We add\n\n .. MATH::\n\n \\sum_{a\\in\\tilde A} x_{p(a), z}t^z = \\sum_{z\\in\\tilde Z} t^z,\n\n where `p(a)` is the block containing `a`, for each given\n distribution as a vector equation to the MILP.\n\n EXAMPLES::\n\n sage: A = B = [permutation for n in range(4) for permutation in Permutations(n)]\n sage: tau = Permutation.longest_increasing_subsequence_length\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_statistics((len, len))\n sage: bij.set_distributions(([Permutation([1, 2, 3]), Permutation([1, 3, 2])], [1, 3]))\n sage: for sol in sorted(list(bij.solutions_iterator()), key=lambda d: tuple(sorted(d.items()))):\n ....: print(sol)\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 3, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 1, [1, 3, 2]: 3, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n\n sage: bij.constant_blocks(optimal=True)\n {{[2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]}}\n sage: sorted(bij.minimal_subdistributions_blocks_iterator(), key=lambda d: (len(d[0]), d[0]))\n [([[]], [0]),\n ([[1]], [1]),\n ([[2, 1, 3]], [2]),\n ([[1, 2], [2, 1]], [1, 2]),\n ([[1, 2, 3], [1, 3, 2]], [1, 3])]\n\n We may also specify multiple, possibly overlapping distributions::\n\n sage: bij.set_distributions(([Permutation([1, 2, 3]), Permutation([1, 3, 2])], [1, 3]),\n ....: ([Permutation([1, 3, 2]), Permutation([3, 2, 1]),\n ....: Permutation([2, 1, 3])], [1, 2, 2]))\n sage: for sol in sorted(list(bij.solutions_iterator()), key=lambda d: tuple(sorted(d.items()))):\n ....: print(sol)\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n\n sage: bij.constant_blocks(optimal=True)\n {{[1], [1, 3, 2]}, {[2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]}}\n sage: sorted(bij.minimal_subdistributions_blocks_iterator(), key=lambda d: (len(d[0]), d[0]))\n [([[]], [0]),\n ([[1]], [1]),\n ([[1, 2, 3]], [3]),\n ([[2, 3, 1]], [2]),\n ([[1, 2], [2, 1]], [1, 2])]\n\n TESTS:\n\n Because of the current implementation of the output calculation, we do\n not improve our solution if we do not gain any unique solutions::\n\n sage: A = B = [permutation for n in range(4) for permutation in Permutations(n)]\n sage: tau = Permutation.longest_increasing_subsequence_length\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_statistics((len, len))\n sage: bij.set_distributions(([Permutation([1, 2, 3]), Permutation([1, 3, 2])], [2, 3]))\n sage: for sol in sorted(list(bij.solutions_iterator()), key=lambda d: tuple(sorted(d.items()))):\n ....: print(sol)\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 3, [2, 1, 3]: 1, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 3, [2, 1, 3]: 2, [2, 3, 1]: 1, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 3, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 1, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 2, [1, 3, 2]: 3, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 1, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 1, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 1, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 1, [2, 1]: 2, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 2, [1, 3, 2]: 3, [2, 1, 3]: 1, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 2, [1, 3, 2]: 3, [2, 1, 3]: 2, [2, 3, 1]: 1, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 2, [1, 3, 2]: 3, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 1, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 2, [1, 3, 2]: 3, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 1, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 1, [3, 1, 2]: 2, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 1, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 1}\n\n Another example with statistics::\n\n sage: bij = Bijectionist(A, B, tau)\n sage: def alpha(p): return p(1) if len(p) > 0 else 0\n sage: def beta(p): return p(1) if len(p) > 0 else 0\n sage: bij.set_statistics((alpha, beta), (len, len))\n sage: for sol in sorted(list(bij.solutions_iterator()), key=lambda d: tuple(sorted(d.items()))):\n ....: print(sol)\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 2, [1, 3, 2]: 3, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 1, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 2, [1, 3, 2]: 3, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 1, [3, 2, 1]: 2}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 1}\n\n The solution above is not unique. We can add a feasible distribution to force uniqueness::\n\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_statistics((alpha, beta), (len, len))\n sage: bij.set_distributions(([Permutation([1, 2, 3]), Permutation([3, 2, 1])], [1, 3]))\n sage: for sol in bij.solutions_iterator():\n ....: print(sol)\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 1, [1, 2, 3]: 3, [1, 3, 2]: 2, [2, 1, 3]: 2, [2, 3, 1]: 2, [3, 1, 2]: 2, [3, 2, 1]: 1}\n\n Let us try to add a distribution that cannot be satisfied,\n because there is no solution where a permutation that starts\n with 1 is mapped onto 1::\n\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_statistics((alpha, beta), (len, len))\n sage: bij.set_distributions(([Permutation([1, 2, 3]), Permutation([1, 3, 2])], [1, 3]))\n sage: list(bij.solutions_iterator())\n []\n\n The specified elements have to be in `A` and have to be of the same size::\n\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_statistics((len, len))\n sage: bij.set_distributions(([Permutation([1, 2, 3, 4])], [1]))\n Traceback (most recent call last):\n ...\n ValueError: element [1, 2, 3, 4] was not found in A\n sage: bij.set_distributions(([Permutation([1, 2, 3])], [-1]))\n Traceback (most recent call last):\n ...\n ValueError: value -1 was not found in tau(A)\n\n Note that the same error occurs when an element that is not the first element of the list is\n not in `A`.\n\n '
self._bmilp = None
for (tA, tZ) in elements_distributions:
assert (len(tA) == len(tZ)), f'{tA} and {tZ} are not of the same size!'
for (a, z) in zip(tA, tZ):
if (a not in self._A):
raise ValueError(f'element {a} was not found in A')
if (z not in self._Z):
raise ValueError(f'value {z} was not found in tau(A)')
self._elements_distributions = tuple(elements_distributions)
def set_intertwining_relations(self, *pi_rho):
'\n Add restrictions of the form `s(\\pi(a_1,\\dots, a_k)) =\n \\rho(s(a_1),\\dots, s(a_k))`.\n\n .. WARNING::\n\n Any restriction imposed by a previous invocation of\n :meth:`set_intertwining_relations` will be overwritten!\n\n INPUT:\n\n - ``pi_rho`` -- one or more tuples `(k, \\pi: A^k\\to A, \\rho:\n Z^k\\to Z, \\tilde A)` where `\\tilde A` (optional) is a\n `k`-ary function that returns true if and only if a\n `k`-tuple of objects in `A` is in the domain of `\\pi`\n\n ALGORITHM:\n\n The relation\n\n .. MATH::\n\n s(\\pi(a_1,\\dots, a_k)) = \\rho(s(a_1),\\dots, s(a_k))\n\n for each pair `(\\pi, \\rho)` implies immediately that\n `s(\\pi(a_1,\\dots, a_k))` only depends on the blocks of\n `a_1,\\dots, a_k`.\n\n The MILP formulation is as follows. Let `a_1,\\dots,a_k \\in\n A` and let `a = \\pi(a_1,\\dots,a_k)`. Let `z_1,\\dots,z_k \\in\n Z` and let `z = \\rho(z_1,\\dots,z_k)`. Suppose that `a_i\\in\n p_i` for all `i` and that `a\\in p`.\n\n We then want to model the implication\n\n .. MATH::\n\n x_{p_1, z_1} = 1,\\dots, x_{p_k, z_k} = 1 \\Rightarrow x_{p, z} = 1.\n\n We achieve this by requiring\n\n .. MATH::\n\n x_{p, z}\\geq 1 - k + \\sum_{i=1}^k x_{p_i, z_i}.\n\n Note that `z` must be a possible value of `p` and each `z_i`\n must be a possible value of `p_i`.\n\n EXAMPLES:\n\n We can concatenate two permutations by increasing the values\n of the second permutation by the length of the first\n permutation::\n\n sage: def concat(p1, p2): return Permutation(p1 + [i + len(p1) for i in p2])\n\n We may be interested in statistics on permutations which are\n equidistributed with the number of fixed points, such that\n concatenating permutations corresponds to adding statistic\n values::\n\n sage: A = B = [permutation for n in range(4) for permutation in Permutations(n)]\n sage: bij = Bijectionist(A, B, Permutation.number_of_fixed_points)\n sage: bij.set_statistics((len, len))\n sage: for solution in sorted(list(bij.solutions_iterator()), key=lambda d: tuple(sorted(d.items()))):\n ....: print(solution)\n ...\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 0, [2, 1, 3]: 0, [2, 3, 1]: 1, [3, 1, 2]: 1, [3, 2, 1]: 3}\n ...\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 1, [2, 1, 3]: 3, [2, 3, 1]: 0, [3, 1, 2]: 0, [3, 2, 1]: 1}\n ...\n\n sage: bij.set_intertwining_relations((2, concat, lambda x, y: x + y))\n sage: for solution in sorted(list(bij.solutions_iterator()), key=lambda d: tuple(sorted(d.items()))):\n ....: print(solution)\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 1, [2, 3, 1]: 0, [3, 1, 2]: 0, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 1, [2, 3, 1]: 0, [3, 1, 2]: 1, [3, 2, 1]: 0}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 1, [2, 3, 1]: 1, [3, 1, 2]: 0, [3, 2, 1]: 0}\n\n The domain of the composition may be restricted. E.g., if we\n concatenate only permutations starting with a 1, we obtain\n fewer forced elements::\n\n sage: in_domain = lambda p1, p2: (not p1 or p1(1) == 1) and (not p2 or p2(1) == 1)\n sage: bij.set_intertwining_relations((2, concat, lambda x, y: x + y, in_domain))\n sage: for solution in sorted(list(bij.solutions_iterator()), key=lambda d: tuple(sorted(d.items()))):\n ....: print(solution)\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0, [1, 2, 3]: 3, [1, 3, 2]: 0, [2, 1, 3]: 0, [2, 3, 1]: 1, [3, 1, 2]: 1, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0, [1, 2, 3]: 3, [1, 3, 2]: 0, [2, 1, 3]: 1, [2, 3, 1]: 0, [3, 1, 2]: 1, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0, [1, 2, 3]: 3, [1, 3, 2]: 0, [2, 1, 3]: 1, [2, 3, 1]: 1, [3, 1, 2]: 0, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0, [1, 2, 3]: 3, [1, 3, 2]: 0, [2, 1, 3]: 1, [2, 3, 1]: 1, [3, 1, 2]: 1, [3, 2, 1]: 0}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 0, [2, 3, 1]: 0, [3, 1, 2]: 1, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 0, [2, 3, 1]: 1, [3, 1, 2]: 0, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 0, [2, 3, 1]: 1, [3, 1, 2]: 1, [3, 2, 1]: 0}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 1, [2, 3, 1]: 0, [3, 1, 2]: 0, [3, 2, 1]: 1}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 1, [2, 3, 1]: 0, [3, 1, 2]: 1, [3, 2, 1]: 0}\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 0, [1, 2, 3]: 3, [1, 3, 2]: 1, [2, 1, 3]: 1, [2, 3, 1]: 1, [3, 1, 2]: 0, [3, 2, 1]: 0}\n\n We can also restrict according to several composition\n functions. For example, we may additionally concatenate\n permutations by incrementing the elements of the first::\n\n sage: skew_concat = lambda p1, p2: Permutation([i + len(p2) for i in p1] + list(p2))\n sage: bij.set_intertwining_relations((2, skew_concat, lambda x, y: x + y))\n sage: for solution in sorted(list(bij.solutions_iterator()), key=lambda d: tuple(sorted(d.items()))):\n ....: print(solution)\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 0, [1, 3, 2]: 0, [2, 1, 3]: 1, [2, 3, 1]: 1, [3, 1, 2]: 1, [3, 2, 1]: 3}\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 0, [1, 3, 2]: 1, [2, 1, 3]: 0, [2, 3, 1]: 1, [3, 1, 2]: 1, [3, 2, 1]: 3}\n {[]: 0, [1]: 1, [1, 2]: 0, [2, 1]: 2, [1, 2, 3]: 1, [1, 3, 2]: 0, [2, 1, 3]: 0, [2, 3, 1]: 1, [3, 1, 2]: 1, [3, 2, 1]: 3}\n\n However, this yields no solution::\n\n sage: bij.set_intertwining_relations((2, concat, lambda x, y: x + y), (2, skew_concat, lambda x, y: x + y))\n sage: list(bij.solutions_iterator())\n []\n\n '
self._bmilp = None
Pi_Rho = namedtuple('Pi_Rho', 'numargs pi rho domain')
self._pi_rho = []
for pi_rho_tuple in pi_rho:
if (len(pi_rho_tuple) == 3):
(k, pi, rho) = pi_rho_tuple
domain = None
else:
(k, pi, rho, domain) = pi_rho_tuple
self._pi_rho.append(Pi_Rho(numargs=k, pi=pi, rho=rho, domain=domain))
set_semi_conjugacy = set_intertwining_relations
def set_quadratic_relation(self, *phi_psi):
'\n Add restrictions of the form `s\\circ\\psi\\circ s = \\phi`.\n\n INPUT:\n\n - ``phi_psi`` -- (optional) a list of pairs `(\\phi, \\rho)` where `\\phi:\n A\\to Z` and `\\psi: Z\\to A`\n\n ALGORITHM:\n\n We add\n\n .. MATH::\n\n x_{p(a), z} = x_{p(\\psi(z)), \\phi(a)}\n\n for `a\\in A` and `z\\in Z` to the MILP, where `\\phi:A\\to Z`\n and `\\psi:Z\\to A`. Note that, in particular, `\\phi` must be\n constant on blocks.\n\n\n EXAMPLES::\n\n sage: A = B = DyckWords(3)\n sage: bij = Bijectionist(A, B)\n sage: bij.set_statistics((lambda D: D.number_of_touch_points(), lambda D: D.number_of_initial_rises()))\n sage: ascii_art(sorted(bij.minimal_subdistributions_iterator()))\n [ ( [ /\\ ] )\n [ ( [ / \\ ] ) ( [ /\\ /\\ ] [ /\\ /\\/\\ ] )\n [ ( [ /\\/\\/\\ ], [ / \\ ] ), ( [ /\\/ \\, / \\/\\ ], [ / \\/\\, / \\ ] ),\n <BLANKLINE>\n ( [ /\\ ] ) ]\n ( [ /\\/\\ / \\ ] [ /\\ ] ) ]\n ( [ / \\, / \\ ], [ /\\/\\/\\, /\\/ \\ ] ) ]\n sage: bij.set_quadratic_relation((lambda D: D, lambda D: D))\n sage: ascii_art(sorted(bij.minimal_subdistributions_iterator()))\n [ ( [ /\\ ] )\n [ ( [ / \\ ] ) ( [ /\\ ] [ /\\/\\ ] )\n [ ( [ /\\/\\/\\ ], [ / \\ ] ), ( [ /\\/ \\ ], [ / \\ ] ),\n <BLANKLINE>\n <BLANKLINE>\n ( [ /\\ ] [ /\\ ] ) ( [ /\\/\\ ] [ /\\ ] )\n ( [ / \\/\\ ], [ / \\/\\ ] ), ( [ / \\ ], [ /\\/ \\ ] ),\n <BLANKLINE>\n ( [ /\\ ] ) ]\n ( [ / \\ ] ) ]\n ( [ / \\ ], [ /\\/\\/\\ ] ) ]\n\n '
self._bmilp = None
self._phi_psi = phi_psi
def set_homomesic(self, Q):
'\n Assert that the average of `s` on each block of `Q` is\n constant.\n\n INPUT:\n\n - ``Q`` -- a set partition of ``A``\n\n EXAMPLES::\n\n sage: A = B = [1,2,3]\n sage: bij = Bijectionist(A, B, lambda b: b % 3)\n sage: bij.set_homomesic([[1,2], [3]])\n sage: list(bij.solutions_iterator())\n [{1: 2, 2: 0, 3: 1}, {1: 0, 2: 2, 3: 1}]\n\n '
self._bmilp = None
if (Q is None):
self._Q = None
else:
self._Q = SetPartition(Q)
assert (self._Q in SetPartitions(self._A)), f'{Q} must be a set partition of A'
def _forced_constant_blocks(self):
'\n Modify current partition into blocks to the coarsest possible\n one, meaning that after calling this function for every two\n distinct blocks `p_1`, `p_2` there exists a solution `s` with\n `s(p_1)\\neq s(p_2)`.\n\n ALGORITHM:\n\n First we generate an initial solution. For all blocks i, j\n that have the same value under this initial solution, we add\n the constraint `x[i, z] + x[j, z] <= 1` for all possible\n values `z\\in Z`. This constraint ensures that the `s` differs\n on the two blocks. If this modified problem does not have a\n solution, we know that the two blocks always have the same\n value and join them. Then we save all values of this new\n solution and continue looking at pairs of blocks that had the\n same value under all calculated solutions, until no blocks\n can be joined anymore.\n\n EXAMPLES:\n\n The easiest example is given by a constant `tau`, so everything\n is forced to be the same value:\n\n sage: A = B = [permutation for n in range(3) for permutation in Permutations(n)]\n sage: bij = Bijectionist(A, B, lambda x: 0)\n sage: bij.constant_blocks()\n {}\n sage: bij.constant_blocks(optimal=True) # indirect doctest\n {{[], [1], [1, 2], [2, 1]}}\n\n In this other example we look at permutations with length 2 and 3::\n\n sage: N = 4\n sage: A = B = [permutation for n in range(2, N) for permutation in Permutations(n)]\n sage: def tau(p): return p[0] if len(p) else 0\n sage: add_n = lambda p1: Permutation(p1 + [1 + len(p1)])\n sage: add_1 = lambda p1: Permutation([1] + [1 + i for i in p1])\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_intertwining_relations((1, add_n, lambda x: x + 1), (1, add_1, lambda x: x + 1))\n sage: bij.set_statistics((len, len))\n\n sage: bij.constant_blocks()\n {}\n sage: bij.constant_blocks(optimal=True)\n {{[1, 3, 2], [2, 1, 3]}}\n\n Indeed, ``[1,3,2]`` and ``[2,1,3]`` have the same value in\n all solutions, but different values are possible::\n\n sage: pi1 = Permutation([1,3,2]); pi2 = Permutation([2,1,3]);\n sage: set([(solution[pi1], solution[pi2]) for solution in bij.solutions_iterator()])\n {(2, 2), (3, 3)}\n\n Another example involving the cycle type of permutations::\n\n sage: A = B = [permutation for n in range(4) for permutation in Permutations(n)]\n sage: bij = Bijectionist(A, B, lambda x: x.cycle_type())\n\n Let us require that each permutation has the same value as its inverse::\n\n sage: from sage.combinat.cyclic_sieving_phenomenon import orbit_decomposition\n sage: P = orbit_decomposition([permutation for n in range(4) for permutation in Permutations(n)], Permutation.inverse)\n sage: bij.set_constant_blocks(P)\n sage: bij.constant_blocks()\n {{[2, 3, 1], [3, 1, 2]}}\n\n sage: def concat(p1, p2): return Permutation(p1 + [i + len(p1) for i in p2])\n sage: def union(p1, p2): return Partition(sorted(list(p1) + list(p2), reverse=True))\n sage: bij.set_intertwining_relations((2, concat, union))\n\n In this case we do not discover constant blocks by looking at the intertwining_relations only::\n\n sage: next(bij.solutions_iterator())\n ...\n sage: bij.constant_blocks()\n {{[2, 3, 1], [3, 1, 2]}}\n\n sage: bij.constant_blocks(optimal=True)\n {{[1, 3, 2], [2, 1, 3], [3, 2, 1]}, {[2, 3, 1], [3, 1, 2]}}\n\n TESTS::\n\n sage: N = 4\n sage: A = B = [permutation for n in range(N + 1) for permutation in Permutations(n)]\n sage: def alpha1(p): return len(p.weak_excedences())\n sage: def alpha2(p): return len(p.fixed_points())\n sage: def beta1(p): return len(p.descents(final_descent=True)) if p else 0\n sage: def beta2(p): return len([e for (e, f) in zip(p, p[1:] + [0]) if e == f + 1])\n sage: tau = Permutation.longest_increasing_subsequence_length\n sage: def rotate_permutation(p):\n ....: cycle = Permutation(tuple(range(1, len(p) + 1)))\n ....: return Permutation([cycle.inverse()(p(cycle(i))) for i in range(1, len(p) + 1)])\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_statistics((alpha1, beta1), (alpha2, beta2))\n sage: from sage.combinat.cyclic_sieving_phenomenon import orbit_decomposition\n sage: bij.set_constant_blocks(orbit_decomposition(A, rotate_permutation))\n sage: P = bij.constant_blocks()\n sage: P = [sorted(p, key=lambda p: (len(p), p)) for p in P]\n sage: P = sorted(P, key=lambda p: (len(next(iter(p))), len(p)))\n sage: for p in P:\n ....: print(p)\n [[1, 3, 2], [2, 1, 3], [3, 2, 1]]\n [[1, 4, 3, 2], [3, 2, 1, 4]]\n [[2, 1, 4, 3], [4, 3, 2, 1]]\n [[1, 2, 4, 3], [1, 3, 2, 4], [2, 1, 3, 4], [4, 2, 3, 1]]\n [[1, 3, 4, 2], [2, 3, 1, 4], [2, 4, 3, 1], [3, 2, 4, 1]]\n [[1, 4, 2, 3], [3, 1, 2, 4], [4, 1, 3, 2], [4, 2, 1, 3]]\n [[2, 4, 1, 3], [3, 1, 4, 2], [3, 4, 2, 1], [4, 3, 1, 2]]\n\n sage: P = bij.constant_blocks(optimal=True)\n sage: P = [sorted(p, key=lambda p: (len(p), p)) for p in P]\n sage: P = sorted(P, key=lambda p: (len(next(iter(p))), len(p)))\n sage: for p in P:\n ....: print(p)\n [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]\n [[1, 3, 2], [2, 1, 3], [3, 2, 1],\n [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 3, 2],\n [2, 1, 3, 4], [2, 1, 4, 3], [2, 3, 1, 4], [2, 3, 4, 1],\n [2, 4, 3, 1], [3, 2, 1, 4], [3, 2, 4, 1], [4, 2, 3, 1],\n [4, 3, 2, 1]]\n [[1, 4, 2, 3], [2, 4, 1, 3], [3, 1, 2, 4], [3, 1, 4, 2],\n [3, 4, 2, 1], [4, 1, 3, 2], [4, 2, 1, 3], [4, 3, 1, 2]]\n\n The permutation `[2, 1]` is in none of these blocks::\n\n sage: bij.set_constant_blocks(orbit_decomposition(A, rotate_permutation))\n sage: all(s[Permutation([2, 1])] == s[Permutation([1])] for s in bij.solutions_iterator())\n False\n\n sage: all(s[Permutation([2, 1])] == s[Permutation([1, 3, 2])] for s in bij.solutions_iterator())\n False\n\n sage: all(s[Permutation([2, 1])] == s[Permutation([1, 4, 2, 3])] for s in bij.solutions_iterator())\n False\n\n sage: A = B = ["a", "b", "c", "d", "e", "f"]\n sage: tau = {"a": 1, "b": 1, "c": 3, "d": 4, "e": 5, "f": 6}.get\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_distributions((["a", "b"], [1, 1]), (["c", "d", "e"], [3, 4, 5]))\n sage: bij.constant_blocks()\n {}\n sage: bij.constant_blocks(optimal=True)\n {{\'a\', \'b\'}}\n\n sage: A = B = ["a", "b", "c", "d", "e", "f"]\n sage: tau = {"a": 1, "b": 1, "c": 5, "d": 4, "e": 4, "f": 6}.get\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_distributions((["a", "b"], [1, 1]), (["d", "e"], [4, 4]))\n sage: bij.constant_blocks(optimal=True)\n {{\'a\', \'b\'}, {\'d\', \'e\'}}\n\n sage: A = B = ["a", "b", "c", "d"]\n sage: tau = {"a": 1, "b": 1, "c": 2, "d": 2}.get\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.constant_blocks(optimal=True)\n {}\n sage: bij.set_constant_blocks([["a", "b"]])\n sage: bij.constant_blocks()\n {{\'a\', \'b\'}}\n sage: bij.constant_blocks(optimal=True)\n {{\'a\', \'b\'}, {\'c\', \'d\'}}\n\n '
if (self._bmilp is None):
self._bmilp = _BijectionistMILP(self)
solution = next(self._bmilp.solutions_iterator(True, []))
multiple_preimages = {(z,): tP for (z, tP) in _invert_dict(solution).items() if (len(tP) > 1)}
tmp_P = copy(self._P)
def different_values(p1, p2):
tmp_constraints = [((self._bmilp._x[(p1, z)] + self._bmilp._x[(p2, z)]) <= 1) for z in self._possible_block_values[p1] if (z in self._possible_block_values[p2])]
return next(self._bmilp.solutions_iterator(True, tmp_constraints))
def merge_until_split():
for tZ in list(multiple_preimages):
tP = multiple_preimages[tZ]
for i2 in range((len(tP) - 1), (- 1), (- 1)):
for i1 in range(i2):
try:
solution = different_values(tP[i1], tP[i2])
except StopIteration:
tmp_P.union(tP[i1], tP[i2])
if (len(multiple_preimages[tZ]) == 2):
del multiple_preimages[tZ]
else:
tP.remove(tP[i2])
break
return solution
while True:
solution = merge_until_split()
if (solution is None):
self._P = tmp_P
self._bmilp = _BijectionistMILP(self, self._bmilp._solution_cache)
return
updated_multiple_preimages = defaultdict(list)
for (tZ, tP) in multiple_preimages.items():
for p in tP:
updated_multiple_preimages[(tZ + (solution[p],))].append(p)
multiple_preimages = updated_multiple_preimages
def possible_values(self, p=None, optimal=False):
'\n Return for each block the values of `s` compatible with the\n imposed restrictions.\n\n INPUT:\n\n - ``p`` -- (optional) a block of `P`, or an element of a\n block of `P`, or a list of these\n\n - ``optimal`` -- (default: ``False``) whether or not to\n compute the minimal possible set of statistic values\n\n .. NOTE::\n\n Computing the minimal possible set of statistic values\n may be computationally expensive.\n\n .. TODO::\n\n currently, calling this method with ``optimal=True`` does\n not update the internal dictionary, because this would\n interfere with the variables of the MILP.\n\n EXAMPLES::\n\n sage: A = B = ["a", "b", "c", "d"]\n sage: tau = {"a": 1, "b": 1, "c": 1, "d": 2}.get\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_constant_blocks([["a", "b"]])\n sage: bij.possible_values(A)\n {\'a\': {1, 2}, \'b\': {1, 2}, \'c\': {1, 2}, \'d\': {1, 2}}\n sage: bij.possible_values(A, optimal=True)\n {\'a\': {1}, \'b\': {1}, \'c\': {1, 2}, \'d\': {1, 2}}\n\n The internal dictionary is not updated::\n\n sage: bij.possible_values(A)\n {\'a\': {1, 2}, \'b\': {1, 2}, \'c\': {1, 2}, \'d\': {1, 2}}\n\n TESTS::\n\n sage: A = B = ["a", "b", "c", "d"]\n sage: tau = {"a": 1, "b": 1, "c": 2, "d": 2}.get\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_constant_blocks([["a", "b"]])\n\n Test if all formats are really possible::\n\n sage: bij.possible_values(p="a")\n {\'a\': {1, 2}, \'b\': {1, 2}}\n sage: bij.possible_values(p=["a", "b"])\n {\'a\': {1, 2}, \'b\': {1, 2}}\n sage: bij.possible_values(p=[["a", "b"]])\n {\'a\': {1, 2}, \'b\': {1, 2}}\n sage: bij.possible_values(p=[["a", "b"], ["c"]])\n {\'a\': {1, 2}, \'b\': {1, 2}, \'c\': {1, 2}}\n\n Test an unfeasible problem::\n\n sage: A = B = \'ab\'\n sage: bij = Bijectionist(A, B, lambda x: B.index(x) % 2)\n sage: bij.set_constant_blocks([[\'a\', \'b\']])\n sage: bij.possible_values(p="a")\n {\'a\': {0, 1}, \'b\': {0, 1}}\n sage: bij.possible_values(p="a", optimal=True)\n {\'a\': set(), \'b\': set()}\n '
blocks = set()
if (p in self._A):
blocks.add(self._P.find(p))
elif isinstance(p, list):
for p1 in p:
if (p1 in self._A):
blocks.add(self._P.find(p1))
elif isinstance(p1, list):
for p2 in p1:
blocks.add(self._P.find(p2))
if optimal:
if (self._bmilp is None):
self._bmilp = _BijectionistMILP(self)
bmilp = self._bmilp
solutions = defaultdict(set)
try:
solution = next(bmilp.solutions_iterator(True, []))
except StopIteration:
pass
else:
for (p, z) in solution.items():
solutions[p].add(z)
for p in blocks:
tmp_constraints = [(bmilp._x[(p, z)] == 0) for z in solutions[p]]
while True:
try:
solution = next(bmilp.solutions_iterator(True, tmp_constraints))
except StopIteration:
break
for (p0, z) in solution.items():
solutions[p0].add(z)
tmp_constraints.append((bmilp._x[(p, solution[p])] == 0))
possible_values = {}
for p in blocks:
for a in self._P.root_to_elements_dict()[p]:
if optimal:
possible_values[a] = solutions[p]
else:
possible_values[a] = self._possible_block_values[p]
return possible_values
def minimal_subdistributions_iterator(self):
'\n Return all minimal subsets `\\tilde A` of `A`\n together with submultisets `\\tilde Z` with `s(\\tilde A) =\n \\tilde Z` as multisets.\n\n EXAMPLES::\n\n sage: A = B = [permutation for n in range(3) for permutation in Permutations(n)]\n sage: bij = Bijectionist(A, B, len)\n sage: bij.set_statistics((len, len))\n sage: for sol in bij.solutions_iterator():\n ....: print(sol)\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 2}\n sage: sorted(bij.minimal_subdistributions_iterator())\n [([[]], [0]), ([[1]], [1]), ([[1, 2]], [2]), ([[2, 1]], [2])]\n\n Another example::\n\n sage: N = 2; A = B = [dyck_word for n in range(N+1) for dyck_word in DyckWords(n)]\n sage: def tau(D): return D.number_of_touch_points()\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_statistics((lambda d: d.semilength(), lambda d: d.semilength()))\n sage: for solution in sorted(list(bij.solutions_iterator()), key=lambda d: tuple(sorted(d.items()))):\n ....: print(solution)\n {[]: 0, [1, 0]: 1, [1, 0, 1, 0]: 1, [1, 1, 0, 0]: 2}\n {[]: 0, [1, 0]: 1, [1, 0, 1, 0]: 2, [1, 1, 0, 0]: 1}\n sage: for subdistribution in bij.minimal_subdistributions_iterator():\n ....: print(subdistribution)\n ([[]], [0])\n ([[1, 0]], [1])\n ([[1, 0, 1, 0], [1, 1, 0, 0]], [1, 2])\n\n An example with two elements of the same block in a subdistribution::\n\n sage: A = B = ["a", "b", "c", "d", "e"]\n sage: tau = {"a": 1, "b": 1, "c": 2, "d": 2, "e": 3}.get\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_constant_blocks([["a", "b"]])\n sage: bij.set_value_restrictions(("a", [1, 2]))\n sage: bij.constant_blocks(optimal=True)\n {{\'a\', \'b\'}}\n sage: list(bij.minimal_subdistributions_iterator())\n [([\'a\', \'b\', \'c\', \'d\', \'e\'], [1, 1, 2, 2, 3])]\n '
minimal_subdistribution = MixedIntegerLinearProgram(maximization=False, solver=self._solver)
D = minimal_subdistribution.new_variable(binary=True)
V = minimal_subdistribution.new_variable(integer=True)
minimal_subdistribution.set_objective(sum((D[a] for a in self._A)))
minimal_subdistribution.add_constraint((sum((D[a] for a in self._A)) >= 1))
if (self._bmilp is None):
self._bmilp = _BijectionistMILP(self)
s = next(self._bmilp.solutions_iterator(False, []))
while True:
for v in self._Z:
minimal_subdistribution.add_constraint((sum((D[a] for a in self._A if (s[a] == v))) == V[v]))
try:
minimal_subdistribution.solve()
except MIPSolverException:
return
d = minimal_subdistribution.get_values(D, convert=bool, tolerance=0.1)
new_s = self._find_counterexample(self._A, s, d, False)
if (new_s is None):
values = self._sorter['Z']((s[a] for a in self._A if d[a]))
(yield ([a for a in self._A if d[a]], values))
active_vars = [D[a] for a in self._A if minimal_subdistribution.get_values(D[a], convert=bool, tolerance=0.1)]
minimal_subdistribution.add_constraint((sum(active_vars) <= (len(active_vars) - 1)), name='veto')
else:
s = new_s
def _find_counterexample(self, P, s0, d, on_blocks):
'\n Return a solution `s` such that ``d`` is not a subdistribution of\n `s0`.\n\n INPUT:\n\n - ``P`` -- the representatives of the blocks, or `A` if\n ``on_blocks`` is ``False``\n\n - ``s0`` -- a solution\n\n - ``d`` -- a subset of `A`, in the form of a dict from `A` to\n `\\{0, 1\\}`\n\n - ``on_blocks`` -- whether to return the counterexample on\n blocks or on elements\n\n EXAMPLES::\n\n sage: A = B = ["a", "b", "c", "d", "e"]\n sage: tau = {"a": 1, "b": 1, "c": 2, "d": 2, "e": 3}.get\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_constant_blocks([["a", "b"]])\n sage: bij.set_value_restrictions(("a", [1, 2]))\n sage: next(bij.solutions_iterator())\n {\'a\': 1, \'b\': 1, \'c\': 2, \'d\': 3, \'e\': 2}\n\n sage: s0 = {\'a\': 1, \'b\': 1, \'c\': 2, \'d\': 3, \'e\': 2}\n sage: d = {\'a\': 1, \'b\': 0, \'c\': 0, \'d\': 0, \'e\': 0}\n sage: bij._find_counterexample(bij._A, s0, d, False)\n {\'a\': 2, \'b\': 2, \'c\': 1, \'d\': 3, \'e\': 1}\n\n '
bmilp = self._bmilp
for z in self._Z:
z_in_d_count = sum((d[p] for p in P if (s0[p] == z)))
if (not z_in_d_count):
continue
z_in_d = sum(((d[p] * bmilp._x[(self._P.find(p), z)]) for p in P if (z in self._possible_block_values[self._P.find(p)])))
tmp_constraints = [(z_in_d <= (z_in_d_count - 1))]
try:
solution = next(bmilp.solutions_iterator(on_blocks, tmp_constraints))
return solution
except StopIteration:
pass
def minimal_subdistributions_blocks_iterator(self):
'\n Return all representatives of minimal subsets `\\tilde P`\n of `P` together with submultisets `\\tilde Z`\n with `s(\\tilde P) = \\tilde Z` as multisets.\n\n .. WARNING::\n\n If there are several solutions with the same support\n (i.e., the sets of block representatives are the same),\n only one of these will be found, even if the\n distributions are different, see the doctest below. To\n find all solutions, use\n :meth:`minimal_subdistributions_iterator`, which is,\n however, computationally more expensive.\n\n EXAMPLES::\n\n sage: A = B = [permutation for n in range(3) for permutation in Permutations(n)]\n sage: bij = Bijectionist(A, B, len)\n sage: bij.set_statistics((len, len))\n sage: for sol in bij.solutions_iterator():\n ....: print(sol)\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 2}\n sage: sorted(bij.minimal_subdistributions_blocks_iterator())\n [([[]], [0]), ([[1]], [1]), ([[1, 2]], [2]), ([[2, 1]], [2])]\n\n Another example::\n\n sage: N = 2; A = B = [dyck_word for n in range(N+1) for dyck_word in DyckWords(n)]\n sage: def tau(D): return D.number_of_touch_points()\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_statistics((lambda d: d.semilength(), lambda d: d.semilength()))\n sage: for solution in sorted(list(bij.solutions_iterator()), key=lambda d: tuple(sorted(d.items()))):\n ....: print(solution)\n {[]: 0, [1, 0]: 1, [1, 0, 1, 0]: 1, [1, 1, 0, 0]: 2}\n {[]: 0, [1, 0]: 1, [1, 0, 1, 0]: 2, [1, 1, 0, 0]: 1}\n sage: for subdistribution in bij.minimal_subdistributions_blocks_iterator():\n ....: print(subdistribution)\n ([[]], [0])\n ([[1, 0]], [1])\n ([[1, 0, 1, 0], [1, 1, 0, 0]], [1, 2])\n\n An example with two elements of the same block in a subdistribution::\n\n sage: A = B = ["a", "b", "c", "d", "e"]\n sage: tau = {"a": 1, "b": 1, "c": 2, "d": 2, "e": 3}.get\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_constant_blocks([["a", "b"]])\n sage: bij.set_value_restrictions(("a", [1, 2]))\n sage: bij.constant_blocks(optimal=True)\n {{\'a\', \'b\'}}\n sage: list(bij.minimal_subdistributions_blocks_iterator())\n [([\'b\', \'b\', \'c\', \'d\', \'e\'], [1, 1, 2, 2, 3])]\n\n An example with overlapping minimal subdistributions::\n\n sage: A = B = ["a", "b", "c", "d", "e"]\n sage: tau = {"a": 1, "b": 1, "c": 2, "d": 2, "e": 3}.get\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_distributions((["a", "b"], [1, 2]), (["a", "c", "d"], [1, 2, 3]))\n sage: sorted(bij.solutions_iterator(), key=lambda d: tuple(sorted(d.items())))\n [{\'a\': 1, \'b\': 2, \'c\': 2, \'d\': 3, \'e\': 1},\n {\'a\': 1, \'b\': 2, \'c\': 3, \'d\': 2, \'e\': 1},\n {\'a\': 2, \'b\': 1, \'c\': 1, \'d\': 3, \'e\': 2},\n {\'a\': 2, \'b\': 1, \'c\': 3, \'d\': 1, \'e\': 2}]\n sage: bij.constant_blocks(optimal=True)\n {{\'a\', \'e\'}}\n sage: list(bij.minimal_subdistributions_blocks_iterator())\n [([\'a\', \'b\'], [1, 2]), ([\'a\', \'c\', \'d\'], [1, 2, 3])]\n\n Fedor Petrov\'s example from https://mathoverflow.net/q/424187::\n\n sage: A = B = ["a"+str(i) for i in range(1, 9)] + ["b"+str(i) for i in range(3, 9)] + ["d"]\n sage: tau = {b: 0 if i < 10 else 1 for i, b in enumerate(B)}.get\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_constant_blocks([["a"+str(i), "b"+str(i)] for i in range(1, 9) if "b"+str(i) in A])\n sage: d = [0]*8+[1]*4\n sage: bij.set_distributions((A[:8] + A[8+2:-1], d), (A[:8] + A[8:-3], d))\n sage: sorted([s[a] for a in A] for s in bij.solutions_iterator())\n [[0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1],\n [0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0],\n [0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0],\n [0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0],\n [0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0],\n [1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0],\n [1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0],\n [1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0],\n [1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0],\n [1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1],\n [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1]]\n\n sage: sorted(bij.minimal_subdistributions_blocks_iterator()) # random\n [([\'a1\', \'a2\', \'a3\', \'a4\', \'a5\', \'a5\', \'a6\', \'a6\', \'a7\', \'a7\', \'a8\', \'a8\'],\n [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]),\n ([\'a3\', \'a4\', \'d\'], [0, 0, 1]),\n ([\'a7\', \'a8\', \'d\'], [0, 0, 1])]\n\n The following solution is not found, because it happens to\n have the same support as the other::\n\n sage: D = set(A).difference([\'b7\', \'b8\', \'d\'])\n sage: sorted(a.replace("b", "a") for a in D)\n [\'a1\', \'a2\', \'a3\', \'a3\', \'a4\', \'a4\', \'a5\', \'a5\', \'a6\', \'a6\', \'a7\', \'a8\']\n sage: set(tuple(sorted(s[a] for a in D)) for s in bij.solutions_iterator())\n {(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1)}\n\n But it is, by design, included here::\n\n sage: sorted(D) in [d for d, _ in bij.minimal_subdistributions_iterator()]\n True\n\n '
minimal_subdistribution = MixedIntegerLinearProgram(maximization=False, solver=self._solver)
D = minimal_subdistribution.new_variable(integer=True, nonnegative=True)
X = minimal_subdistribution.new_variable(binary=True)
V = minimal_subdistribution.new_variable(integer=True, nonnegative=True)
P = _disjoint_set_roots(self._P)
minimal_subdistribution.set_objective(sum((D[p] for p in P)))
minimal_subdistribution.add_constraint((sum((D[p] for p in P)) >= 1))
for p in P:
minimal_subdistribution.add_constraint((D[p] <= len(self._P.root_to_elements_dict()[p])))
minimal_subdistribution.add_constraint(((X[p] * len(self._P.root_to_elements_dict()[p])) >= D[p] >= X[p]))
def add_counter_example_constraint(s):
for v in self._Z:
minimal_subdistribution.add_constraint((sum((D[p] for p in P if (s[p] == v))) == V[v]))
if (self._bmilp is None):
self._bmilp = _BijectionistMILP(self)
s = next(self._bmilp.solutions_iterator(True, []))
add_counter_example_constraint(s)
while True:
try:
minimal_subdistribution.solve()
except MIPSolverException:
return
d = minimal_subdistribution.get_values(D, convert=ZZ, tolerance=0.1)
new_s = self._find_counterexample(P, s, d, True)
if (new_s is None):
(yield ([p for p in P for _ in range(ZZ(d[p]))], self._sorter['Z']((s[p] for p in P for _ in range(ZZ(d[p]))))))
support = [X[p] for p in P if d[p]]
minimal_subdistribution.add_constraint((sum(support) <= (len(support) - 1)), name='veto')
else:
s = new_s
add_counter_example_constraint(s)
def _preprocess_intertwining_relations(self):
"\n Make ``self._P`` be the finest set partition coarser\n than ``self._P`` such that composing elements preserves\n blocks.\n\n Suppose that `p_1`, `p_2` are blocks of `P`, and `a_1, a'_1\n \\in p_1` and `a_2, a'_2\\in p_2`. Then,\n\n .. MATH:\n\n s(\\pi(a_1, a_2))\n = \\rho(s(a_1), s(a_2))\n = \\rho(s(a'_1), s(a'_2))\n = s(\\pi(a'_1, a'_2)).\n\n Therefore, `\\pi(a_1, a_2)` and `\\pi(a'_1, a'_2)` are in the\n same block.\n\n In other words, `s(\\pi(a_1,\\dots,a_k))` only depends on the\n blocks of `a_1,\\dots,a_k`.\n\n In particular, if `P` consists only if singletons, this\n method has no effect.\n\n .. TODO::\n\n create one test with one and one test with two\n intertwining relations\n\n .. TODO::\n\n it is not clear whether this method makes sense\n\n EXAMPLES::\n\n sage: A = B = 'abcd'\n sage: bij = Bijectionist(A, B, lambda x: B.index(x) % 2)\n sage: def pi(p1, p2): return 'abcdefgh'[A.index(p1) + A.index(p2)]\n sage: def rho(s1, s2): return (s1 + s2) % 2\n sage: bij.set_intertwining_relations((2, pi, rho))\n sage: bij._preprocess_intertwining_relations()\n sage: bij._P\n {{'a'}, {'b'}, {'c'}, {'d'}}\n\n Let a group act on permutations::\n\n sage: A = B = Permutations(3)\n sage: bij = Bijectionist(A, B, lambda x: x[0])\n sage: bij.set_intertwining_relations((1, lambda pi: pi.reverse(), lambda z: z))\n sage: bij._preprocess_intertwining_relations()\n sage: bij._P\n {{[1, 2, 3]}, {[1, 3, 2]}, {[2, 1, 3]}, {[2, 3, 1]}, {[3, 1, 2]}, {[3, 2, 1]}}\n\n "
A = self._A
P = self._P
images = defaultdict(set)
for pi_rho in self._pi_rho:
for a_tuple in itertools.product(*([A] * pi_rho.numargs)):
if ((pi_rho.domain is not None) and (not pi_rho.domain(*a_tuple))):
continue
a = pi_rho.pi(*a_tuple)
if (a in A):
images[a_tuple].add(a)
something_changed = True
while something_changed:
something_changed = False
updated_images = defaultdict(set)
for (a_tuple, image_set) in images.items():
representatives = tuple((P.find(a) for a in a_tuple))
updated_images[representatives].update(image_set)
for (a_tuple, image_set) in updated_images.items():
image = image_set.pop()
while image_set:
P.union(image, image_set.pop())
something_changed = True
image_set.add(image)
images = updated_images
def solutions_iterator(self):
'\n An iterator over all solutions of the problem.\n\n OUTPUT: An iterator over all possible mappings `s: A\\to Z`\n\n ALGORITHM:\n\n We solve an integer linear program with a binary variable\n `x_{p, z}` for each partition block `p\\in P` and each\n statistic value `z\\in Z`:\n\n - `x_{p, z} = 1` if and only if `s(a) = z` for all `a\\in p`.\n\n Then we add the constraint `\\sum_{x\\in V} x<|V|`, where `V`\n is the set containing all `x` with `x = 1`, that is, those\n indicator variables representing the current solution.\n Therefore, a solution of this new program must be different\n from all those previously obtained.\n\n INTEGER LINEAR PROGRAM:\n\n * Let `m_w(p)`, for a block `p` of `P`, be the multiplicity\n of the value `w` in `W` under `\\alpha`, that is, the number\n of elements `a \\in p` with `\\alpha(a)=w`.\n\n * Let `n_w(z)` be the number of elements `b \\in B` with\n `\\beta(b)=w` and `\\tau(b)=z` for `w \\in W`, `z \\in Z`.\n\n * Let `k` be the arity of a pair `(\\pi, \\rho)` in an\n intertwining relation.\n\n and the following constraints:\n\n * because every block is assigned precisely one value, for\n all `p\\in P`,\n\n .. MATH::\n\n \\sum_z x_{p, z} = 1.\n\n * because the statistics `s` and `\\tau` and also `\\alpha` and\n `\\beta` are equidistributed, for all `w\\in W` and `z\\in Z`,\n\n .. MATH::\n\n \\sum_p m_w(p) x_{p, z} = n_w(z).\n\n * for each intertwining relation `s(\\pi(a_1,\\dots, a_k)) =\n \\rho(s(a_1),\\dots, s(a_r))`, and for all `k`-combinations\n of blocks `p_i\\in P` such that there exist `(a_1,\\dots,\n a_k)\\in p_1\\times\\dots\\times p_k` with `\\pi(a_1,\\dots,\n a_k)\\in W` and `z = \\rho(z_1,\\dots, z_k)`,\n\n .. MATH::\n\n x_{p, z} \\geq 1-k + \\sum_{i=1}^k x_{p_i, z_i}.\n\n * for each distribution restriction, i.e. a set of elements\n `\\tilde A` and a distribution of values given by integers\n `d_z` representing the multiplicity of each `z \\in Z`, and\n `r_p = |p \\cap\\tilde A|` indicating the relative size of\n block `p` in the set of elements of the distribution,\n\n .. MATH::\n\n \\sum_p r_p x_{p, z} = d_z.\n\n EXAMPLES::\n\n sage: A = B = \'abc\'\n sage: bij = Bijectionist(A, B, lambda x: B.index(x) % 2, solver="GLPK")\n sage: next(bij.solutions_iterator())\n {\'a\': 0, \'b\': 1, \'c\': 0}\n\n sage: list(bij.solutions_iterator())\n [{\'a\': 0, \'b\': 1, \'c\': 0},\n {\'a\': 1, \'b\': 0, \'c\': 0},\n {\'a\': 0, \'b\': 0, \'c\': 1}]\n\n sage: N = 4\n sage: A = B = [permutation for n in range(N) for permutation in Permutations(n)]\n\n Let `\\tau` be the number of non-left-to-right-maxima of a\n permutation::\n\n sage: def tau(pi):\n ....: pi = list(pi)\n ....: i = count = 0\n ....: for j in range(len(pi)):\n ....: if pi[j] > i:\n ....: i = pi[j]\n ....: else:\n ....: count += 1\n ....: return count\n\n We look for a statistic which is constant on conjugacy classes::\n\n sage: P = [list(a) for n in range(N) for a in Permutations(n).conjugacy_classes()]\n\n sage: bij = Bijectionist(A, B, tau, solver="GLPK")\n sage: bij.set_statistics((len, len))\n sage: bij.set_constant_blocks(P)\n sage: for solution in bij.solutions_iterator():\n ....: print(solution)\n {[]: 0, [1]: 0, [1, 2]: 1, [2, 1]: 0, [1, 2, 3]: 0, [1, 3, 2]: 1, [2, 1, 3]: 1, [3, 2, 1]: 1, [2, 3, 1]: 2, [3, 1, 2]: 2}\n {[]: 0, [1]: 0, [1, 2]: 0, [2, 1]: 1, [1, 2, 3]: 0, [1, 3, 2]: 1, [2, 1, 3]: 1, [3, 2, 1]: 1, [2, 3, 1]: 2, [3, 1, 2]: 2}\n\n Changing or re-setting problem parameters clears the internal\n cache. Setting the verbosity prints the MILP which is solved.::\n\n sage: set_verbose(2)\n sage: bij.set_constant_blocks(P)\n sage: _ = list(bij.solutions_iterator())\n Constraints are:\n block []: 1 <= x_0 <= 1\n block [1]: 1 <= x_1 <= 1\n block [1, 2]: 1 <= x_2 + x_3 <= 1\n block [2, 1]: 1 <= x_4 + x_5 <= 1\n block [1, 2, 3]: 1 <= x_6 + x_7 + x_8 <= 1\n block [1, 3, 2]: 1 <= x_9 + x_10 + x_11 <= 1\n block [2, 3, 1]: 1 <= x_12 + x_13 + x_14 <= 1\n statistics: 1 <= x_0 <= 1\n statistics: 0 <= <= 0\n statistics: 0 <= <= 0\n statistics: 1 <= x_1 <= 1\n statistics: 0 <= <= 0\n statistics: 0 <= <= 0\n statistics: 1 <= x_2 + x_4 <= 1\n statistics: 1 <= x_3 + x_5 <= 1\n statistics: 0 <= <= 0\n statistics: 1 <= x_6 + 3 x_9 + 2 x_12 <= 1\n statistics: 3 <= x_7 + 3 x_10 + 2 x_13 <= 3\n statistics: 2 <= x_8 + 3 x_11 + 2 x_14 <= 2\n Variables are:\n x_0: s([]) = 0\n x_1: s([1]) = 0\n x_2: s([1, 2]) = 0\n x_3: s([1, 2]) = 1\n x_4: s([2, 1]) = 0\n x_5: s([2, 1]) = 1\n x_6: s([1, 2, 3]) = 0\n x_7: s([1, 2, 3]) = 1\n x_8: s([1, 2, 3]) = 2\n x_9: s([1, 3, 2]) = s([2, 1, 3]) = s([3, 2, 1]) = 0\n x_10: s([1, 3, 2]) = s([2, 1, 3]) = s([3, 2, 1]) = 1\n x_11: s([1, 3, 2]) = s([2, 1, 3]) = s([3, 2, 1]) = 2\n x_12: s([2, 3, 1]) = s([3, 1, 2]) = 0\n x_13: s([2, 3, 1]) = s([3, 1, 2]) = 1\n x_14: s([2, 3, 1]) = s([3, 1, 2]) = 2\n after vetoing\n Constraints are:\n block []: 1 <= x_0 <= 1\n block [1]: 1 <= x_1 <= 1\n block [1, 2]: 1 <= x_2 + x_3 <= 1\n block [2, 1]: 1 <= x_4 + x_5 <= 1\n block [1, 2, 3]: 1 <= x_6 + x_7 + x_8 <= 1\n block [1, 3, 2]: 1 <= x_9 + x_10 + x_11 <= 1\n block [2, 3, 1]: 1 <= x_12 + x_13 + x_14 <= 1\n statistics: 1 <= x_0 <= 1\n statistics: 0 <= <= 0\n statistics: 0 <= <= 0\n statistics: 1 <= x_1 <= 1\n statistics: 0 <= <= 0\n statistics: 0 <= <= 0\n statistics: 1 <= x_2 + x_4 <= 1\n statistics: 1 <= x_3 + x_5 <= 1\n statistics: 0 <= <= 0\n statistics: 1 <= x_6 + 3 x_9 + 2 x_12 <= 1\n statistics: 3 <= x_7 + 3 x_10 + 2 x_13 <= 3\n statistics: 2 <= x_8 + 3 x_11 + 2 x_14 <= 2\n veto: x_0 + x_1 + x_3 + x_4 + x_6 + x_10 + x_14 <= 6\n after vetoing\n Constraints are:\n block []: 1 <= x_0 <= 1\n block [1]: 1 <= x_1 <= 1\n block [1, 2]: 1 <= x_2 + x_3 <= 1\n block [2, 1]: 1 <= x_4 + x_5 <= 1\n block [1, 2, 3]: 1 <= x_6 + x_7 + x_8 <= 1\n block [1, 3, 2]: 1 <= x_9 + x_10 + x_11 <= 1\n block [2, 3, 1]: 1 <= x_12 + x_13 + x_14 <= 1\n statistics: 1 <= x_0 <= 1\n statistics: 0 <= <= 0\n statistics: 0 <= <= 0\n statistics: 1 <= x_1 <= 1\n statistics: 0 <= <= 0\n statistics: 0 <= <= 0\n statistics: 1 <= x_2 + x_4 <= 1\n statistics: 1 <= x_3 + x_5 <= 1\n statistics: 0 <= <= 0\n statistics: 1 <= x_6 + 3 x_9 + 2 x_12 <= 1\n statistics: 3 <= x_7 + 3 x_10 + 2 x_13 <= 3\n statistics: 2 <= x_8 + 3 x_11 + 2 x_14 <= 2\n veto: x_0 + x_1 + x_3 + x_4 + x_6 + x_10 + x_14 <= 6\n veto: x_0 + x_1 + x_2 + x_5 + x_6 + x_10 + x_14 <= 6\n\n sage: set_verbose(0)\n\n TESTS:\n\n An unfeasible problem::\n\n sage: A = ["a", "b", "c", "d"]; B = [1, 2, 3, 4]\n sage: bij = Bijectionist(A, B)\n sage: bij.set_value_restrictions(("a", [1, 2]), ("b", [1, 2]), ("c", [1, 3]), ("d", [2, 3]))\n sage: list(bij.solutions_iterator())\n []\n\n Testing interactions between multiple instances using Fedor Petrov\'s example from https://mathoverflow.net/q/424187::\n\n sage: A = B = ["a"+str(i) for i in range(1, 9)] + ["b"+str(i) for i in range(3, 9)] + ["d"]\n sage: tau = {b: 0 if i < 10 else 1 for i, b in enumerate(B)}.get\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_constant_blocks([["a"+str(i), "b"+str(i)] for i in range(1, 9) if "b"+str(i) in A])\n sage: d = [0]*8+[1]*4\n sage: bij.set_distributions((A[:8] + A[8+2:-1], d), (A[:8] + A[8:-3], d))\n sage: iterator1 = bij.solutions_iterator()\n sage: iterator2 = bij.solutions_iterator()\n\n Generate a solution in iterator1, iterator2 should generate the same solution and vice versa::\n\n sage: s1_1 = next(iterator1)\n sage: s2_1 = next(iterator2)\n sage: s1_1 == s2_1\n True\n sage: s2_2 = next(iterator2)\n sage: s1_2 = next(iterator1)\n sage: s1_2 == s2_2\n True\n\n Re-setting the distribution resets the cache, so a new\n iterator will generate the first solutions again, but the old\n iterator continues::\n\n sage: bij.set_distributions((A[:8] + A[8+2:-1], d), (A[:8] + A[8:-3], d))\n sage: iterator3 = bij.solutions_iterator()\n\n sage: s3_1 = next(iterator3)\n sage: s1_1 == s3_1\n True\n\n sage: s1_3 = next(iterator1)\n sage: len(set([tuple(sorted(s.items())) for s in [s1_1, s1_2, s1_3]]))\n 3\n\n '
if (self._bmilp is None):
self._bmilp = _BijectionistMILP(self)
(yield from self._bmilp.solutions_iterator(False, []))
|
class _BijectionistMILP():
'\n Wrapper class for the MixedIntegerLinearProgram (MILP).\n\n This class is used to manage the MILP, add constraints, solve the\n problem and check for uniqueness of solution values.\n '
def __init__(self, bijectionist: Bijectionist, solutions=None):
'\n Initialize the mixed integer linear program.\n\n INPUT:\n\n - ``bijectionist`` -- an instance of :class:`Bijectionist`.\n\n - ``solutions`` -- (optional) a list of solutions of the\n problem, each provided as a dictionary mapping `(a, z)` to\n a boolean, such that at least one element from each block\n of `P` appears as `a`.\n\n .. TODO::\n\n it might be cleaner not to pass the full bijectionist\n instance, but only those attributes we actually use\n\n TESTS::\n\n sage: A = B = ["a", "b", "c", "d"]\n sage: bij = Bijectionist(A, B)\n sage: from sage.combinat.bijectionist import _BijectionistMILP\n sage: _BijectionistMILP(bij)\n <sage.combinat.bijectionist._BijectionistMILP object at ...>\n\n '
self._bijectionist = bijectionist
bijectionist._preprocess_intertwining_relations()
bijectionist._compute_possible_block_values()
self.milp = MixedIntegerLinearProgram(solver=bijectionist._solver)
self.milp.set_objective(None)
indices = [(p, z) for (p, tZ) in bijectionist._possible_block_values.items() for z in tZ]
self._x = self.milp.new_variable(binary=True, indices=indices)
tZ = bijectionist._possible_block_values
P = bijectionist._P
for p in _disjoint_set_roots(P):
self.milp.add_constraint((sum((self._x[(p, z)] for z in tZ[p])) == 1), name=f'block {p}'[:50])
self.add_alpha_beta_constraints()
self.add_distribution_constraints()
self.add_quadratic_relation_constraints()
self.add_homomesic_constraints()
self.add_intertwining_relation_constraints()
if (get_verbose() >= 2):
self.show()
self._solution_cache = []
if (solutions is not None):
for solution in solutions:
self._add_solution({(P.find(a), z): value for ((a, z), value) in solution.items()})
def show(self, variables=True):
'\n Print the constraints and variables of the MILP together\n with some explanations.\n\n EXAMPLES::\n\n sage: A = B = ["a", "b", "c"]\n sage: bij = Bijectionist(A, B, lambda x: A.index(x) % 2, solver="GLPK")\n sage: bij.set_constant_blocks([["a", "b"]])\n sage: next(bij.solutions_iterator())\n {\'a\': 0, \'b\': 0, \'c\': 1}\n sage: bij._bmilp.show()\n Constraints are:\n block a: 1 <= x_0 + x_1 <= 1\n block c: 1 <= x_2 + x_3 <= 1\n statistics: 2 <= 2 x_0 + x_2 <= 2\n statistics: 1 <= 2 x_1 + x_3 <= 1\n veto: x_0 + x_3 <= 1\n Variables are:\n x_0: s(a) = s(b) = 0\n x_1: s(a) = s(b) = 1\n x_2: s(c) = 0\n x_3: s(c) = 1\n\n '
print('Constraints are:')
b = self.milp.get_backend()
varid_name = {}
for i in range(b.ncols()):
s = b.col_name(i)
default_name = str(self.milp.linear_functions_parent()({i: 1}))
if (s and (s != default_name)):
varid_name[i] = s
else:
varid_name[i] = default_name
for (i, (lb, (indices, values), ub)) in enumerate(self.milp.constraints()):
if b.row_name(i):
print(((' ' + b.row_name(i)) + ':'), end=' ')
if (lb is not None):
print((str(ZZ(lb)) + ' <='), end=' ')
first = True
for (j, c) in sorted(zip(indices, values)):
c = ZZ(c)
if (c == 0):
continue
print(((('+ ' if ((not first) and (c > 0)) else '') + ('' if (c == 1) else ('- ' if (c == (- 1)) else ((str(c) + ' ') if (first and (c < 0)) else ((('- ' + str(abs(c))) + ' ') if (c < 0) else (str(c) + ' ')))))) + varid_name[j]), end=' ')
first = False
print((('<= ' + str(ZZ(ub))) if (ub is not None) else ''))
if variables:
print('Variables are:')
P = self._bijectionist._P.root_to_elements_dict()
for ((p, z), v) in self._x.items():
print(((f' {v}: ' + ''.join([f's({a}) = ' for a in P[p]])) + f'{z}'))
def _prepare_solution(self, on_blocks, solution):
'\n Return the solution as a dictionary from `A` (or `P`) to\n `Z`.\n\n INPUT:\n\n - ``on_blocks`` -- whether to return the solution on blocks\n or on all elements\n\n TESTS::\n\n sage: A = B = ["a", "b", "c"]\n sage: bij = Bijectionist(A, B, lambda x: 0)\n sage: bij.set_constant_blocks([["a", "b"]])\n sage: next(bij.solutions_iterator())\n {\'a\': 0, \'b\': 0, \'c\': 0}\n sage: bmilp = bij._bmilp\n sage: bmilp._prepare_solution(True, bmilp._solution_cache[0])\n {\'a\': 0, \'c\': 0}\n\n '
P = self._bijectionist._P
tZ = self._bijectionist._possible_block_values
mapping = {}
for (p, block) in P.root_to_elements_dict().items():
for z in tZ[p]:
if (solution[(p, z)] == 1):
if on_blocks:
mapping[p] = z
else:
for a in block:
mapping[a] = z
break
return mapping
def solutions_iterator(self, on_blocks, additional_constraints):
'\n Iterate over all solutions satisfying the additional constraints.\n\n INPUT:\n\n - ``additional_constraints`` -- a list of constraints for the\n underlying MILP\n\n - ``on_blocks``, whether to return the solution on blocks or\n on all elements\n\n TESTS::\n\n sage: A = B = \'abc\'\n sage: bij = Bijectionist(A, B, lambda x: B.index(x) % 2, solver="GLPK")\n sage: from sage.combinat.bijectionist import _BijectionistMILP\n sage: bmilp = _BijectionistMILP(bij)\n sage: it = bmilp.solutions_iterator(False, [])\n sage: it2 = bmilp.solutions_iterator(False, [bmilp._x[(\'c\', 1)] == 1])\n sage: next(it)\n {\'a\': 0, \'b\': 1, \'c\': 0}\n sage: next(it2)\n {\'a\': 0, \'b\': 0, \'c\': 1}\n sage: next(it)\n {\'a\': 0, \'b\': 0, \'c\': 1}\n sage: next(it)\n {\'a\': 1, \'b\': 0, \'c\': 0}\n\n '
i = 0
while True:
while (i < len(self._solution_cache)):
solution = self._solution_cache[i]
i += 1
if all((self._is_solution(constraint, solution) for constraint in additional_constraints)):
(yield self._prepare_solution(on_blocks, solution))
break
else:
new_indices = []
for constraint in additional_constraints:
new_indices.extend(self.milp.add_constraint(constraint, return_indices=True))
try:
self.milp.solve()
solution = self.milp.get_values(self._x, convert=bool, tolerance=0.1)
except MIPSolverException:
return
finally:
b = self.milp.get_backend()
if hasattr(b, '_get_model'):
m = b._get_model()
if (m.getStatus() != 'unknown'):
m.freeTransform()
self.milp.remove_constraints(new_indices)
self._add_solution(solution)
i += 1
assert (i == len(self._solution_cache))
(yield self._prepare_solution(on_blocks, solution))
if (get_verbose() >= 2):
print('after vetoing')
self.show(variables=False)
def _add_solution(self, solution):
'\n Add the ``solution`` to the cache and an appropriate\n veto constraint to the MILP.\n\n INPUT:\n\n - ``solution`` -- a dictionary from the indices of the MILP to\n a boolean\n\n EXAMPLES::\n\n sage: A = B = ["a", "b"]\n sage: bij = Bijectionist(A, B)\n sage: from sage.combinat.bijectionist import _BijectionistMILP\n sage: bmilp = _BijectionistMILP(bij)\n sage: bmilp._add_solution({(a, b): a == b for a in A for b in B})\n sage: bmilp.show() # random\n Constraints are:\n block a: 1 <= x_0 + x_1 <= 1\n block b: 1 <= x_2 + x_3 <= 1\n statistics: 1 <= x_1 + x_3 <= 1\n statistics: 1 <= x_0 + x_2 <= 1\n veto: x_1 + x_2 <= 1\n Variables are:\n x_0: s(a) = b\n x_1: s(a) = a\n x_2: s(b) = b\n x_3: s(b) = a\n\n '
active_vars = [self._x[(p, z)] for p in _disjoint_set_roots(self._bijectionist._P) for z in self._bijectionist._possible_block_values[p] if solution[(p, z)]]
self.milp.add_constraint((sum(active_vars) <= (len(active_vars) - 1)), name='veto')
self._solution_cache.append(solution)
def _is_solution(self, constraint, values):
'\n Evaluate the given function at the given values.\n\n INPUT:\n\n - ``constraint`` -- a\n :class:`sage.numerical.linear_functions.LinearConstraint`.\n\n - ``values`` -- a candidate for a solution of the MILP as a\n dictionary from pairs `(a, z)\\in A\\times Z` to `0` or `1`,\n specifying whether `a` is mapped to `z`.\n\n EXAMPLES::\n\n sage: A = B = ["a", "b"]\n sage: bij = Bijectionist(A, B)\n sage: from sage.combinat.bijectionist import _BijectionistMILP\n sage: bmilp = _BijectionistMILP(bij)\n sage: f = bmilp._x["a", "a"] + bmilp._x["b", "a"] >= bmilp._x["b", "b"] + 1\n sage: v = {(\'a\', \'a\'): 1, (\'a\', \'b\'): 0, (\'b\', \'a\'): 1, (\'b\', \'b\'): 1}\n sage: bmilp._is_solution(f, v)\n True\n sage: v = {(\'a\', \'a\'): 0, (\'a\', \'b\'): 0, (\'b\', \'a\'): 1, (\'b\', \'b\'): 1}\n sage: bmilp._is_solution(f, v)\n False\n '
index_block_value_dict = {}
for ((p, z), v) in self._x.items():
variable_index = next(iter(v.dict()))
index_block_value_dict[variable_index] = (p, z)
def evaluate(f):
return sum(((coeff if (index == (- 1)) else (coeff * values[index_block_value_dict[index]])) for (index, coeff) in f.dict().items()))
for (lhs, rhs) in constraint.equations():
if evaluate((lhs - rhs)):
return False
for (lhs, rhs) in constraint.inequalities():
if (evaluate((lhs - rhs)) > 0):
return False
return True
def add_alpha_beta_constraints(self):
'\n Add constraints enforcing that `(alpha, s)` is equidistributed\n with `(beta, tau)` and `S` is the intertwining bijection.\n\n We do this by adding\n\n .. MATH::\n\n \\sum_{a\\in A, z\\in Z} x_{p(a), z} s^z t^{\\alpha(a)}\n = \\sum_{b\\in B} s^{\\tau(b)} t(\\beta(b))\n\n as a matrix equation.\n\n EXAMPLES::\n\n sage: A = B = [permutation for n in range(3) for permutation in Permutations(n)]\n sage: bij = Bijectionist(A, B, len)\n sage: bij.set_statistics((len, len))\n sage: from sage.combinat.bijectionist import _BijectionistMILP\n sage: bmilp = _BijectionistMILP(bij) # indirect doctest\n sage: next(bmilp.solutions_iterator(False, []))\n {[]: 0, [1]: 1, [1, 2]: 2, [2, 1]: 2}\n '
W = self._bijectionist._W
Z = self._bijectionist._Z
zero = self.milp.linear_functions_parent().zero()
AZ_matrix = [([zero] * len(W)) for _ in range(len(Z))]
B_matrix = [([zero] * len(W)) for _ in range(len(Z))]
W_dict = {w: i for (i, w) in enumerate(W)}
Z_dict = {z: i for (i, z) in enumerate(Z)}
for a in self._bijectionist._A:
p = self._bijectionist._P.find(a)
for z in self._bijectionist._possible_block_values[p]:
w_index = W_dict[self._bijectionist._alpha(a)]
z_index = Z_dict[z]
AZ_matrix[z_index][w_index] += self._x[(p, z)]
for b in self._bijectionist._B:
w_index = W_dict[self._bijectionist._beta(b)]
z_index = Z_dict[self._bijectionist._tau[b]]
B_matrix[z_index][w_index] += 1
for w in range(len(W)):
for z in range(len(Z)):
self.milp.add_constraint((AZ_matrix[z][w] == B_matrix[z][w]), name='statistics')
def add_distribution_constraints(self):
'\n Add constraints so the distributions given by\n :meth:`set_distributions` are fulfilled.\n\n To accomplish this we add\n\n .. MATH::\n\n \\sum_{a\\in\\tilde A} x_{p(a), z}t^z = \\sum_{z\\in\\tilde Z} t^z,\n\n where `p(a)` is the block containing `a`, for each given\n distribution as a vector equation.\n\n EXAMPLES::\n\n sage: A = B = Permutations(3)\n sage: tau = Permutation.longest_increasing_subsequence_length\n sage: bij = Bijectionist(A, B, tau)\n sage: bij.set_distributions(([Permutation([1, 2, 3]), Permutation([1, 3, 2])], [1, 3]))\n sage: from sage.combinat.bijectionist import _BijectionistMILP\n sage: bmilp = _BijectionistMILP(bij) # indirect doctest\n sage: next(bmilp.solutions_iterator(False, []))\n {[1, 2, 3]: 3,\n [1, 3, 2]: 1,\n [2, 1, 3]: 2,\n [2, 3, 1]: 2,\n [3, 1, 2]: 2,\n [3, 2, 1]: 2}\n\n '
Z = self._bijectionist._Z
Z_dict = {z: i for (i, z) in enumerate(Z)}
zero = self.milp.linear_functions_parent().zero()
for (tA, tZ) in self._bijectionist._elements_distributions:
tA_sum = ([zero] * len(Z_dict))
tZ_sum = ([zero] * len(Z_dict))
for a in tA:
p = self._bijectionist._P.find(a)
for z in self._bijectionist._possible_block_values[p]:
tA_sum[Z_dict[z]] += self._x[(p, z)]
for z in tZ:
tZ_sum[Z_dict[z]] += 1
for (a, z) in zip(tA_sum, tZ_sum):
self.milp.add_constraint((a == z), name=f'd: {a} == {z}')
def add_intertwining_relation_constraints(self):
"\n Add constraints corresponding to the given intertwining\n relations.\n\n INPUT:\n\n - origins, a list of triples `((\\pi/\\rho, p,\n (p_1,\\dots,p_k))`, where `p` is the block of\n `\\rho(s(a_1),\\dots, s(a_k))`, for any `a_i\\in p_i`.\n\n This adds the constraints imposed by\n :meth:`set_intertwining_relations`,\n\n .. MATH::\n\n s(\\pi(a_1,\\dots, a_k)) = \\rho(s(a_1),\\dots, s(a_k))\n\n for each pair `(\\pi, \\rho)`. The relation implies\n immediately that `s(\\pi(a_1,\\dots, a_k))` only depends on the\n blocks of `a_1,\\dots, a_k`.\n\n The MILP formulation is as follows. Let `a_1,\\dots,a_k \\in\n A` and let `a = \\pi(a_1,\\dots,a_k)`. Let `z_1,\\dots,z_k \\in\n Z` and let `z = \\rho(z_1,\\dots,z_k)`. Suppose that `a_i\\in\n p_i` for all `i` and that `a\\in p`.\n\n We then want to model the implication\n\n .. MATH::\n\n x_{p_1, z_1} = 1,\\dots, x_{p_k, z_k} = 1 \\Rightarrow x_{p, z} = 1.\n\n We achieve this by requiring\n\n .. MATH::\n\n x_{p, z}\\geq 1 - k + \\sum_{i=1}^k x_{p_i, z_i}.\n\n Note that `z` must be a possible value of `p` and each `z_i`\n must be a possible value of `p_i`.\n\n EXAMPLES::\n\n sage: A = B = 'abcd'\n sage: bij = Bijectionist(A, B, lambda x: B.index(x) % 2)\n sage: def pi(p1, p2): return 'abcdefgh'[A.index(p1) + A.index(p2)]\n sage: def rho(s1, s2): return (s1 + s2) % 2\n sage: bij.set_intertwining_relations((2, pi, rho))\n sage: from sage.combinat.bijectionist import _BijectionistMILP\n sage: bmilp = _BijectionistMILP(bij) # indirect doctest\n sage: next(bmilp.solutions_iterator(False, []))\n {'a': 0, 'b': 1, 'c': 0, 'd': 1}\n "
A = self._bijectionist._A
tZ = self._bijectionist._possible_block_values
P = self._bijectionist._P
for (composition_index, pi_rho) in enumerate(self._bijectionist._pi_rho):
pi_blocks = set()
for a_tuple in itertools.product(A, repeat=pi_rho.numargs):
if ((pi_rho.domain is not None) and (not pi_rho.domain(*a_tuple))):
continue
a = pi_rho.pi(*a_tuple)
if (a in A):
p_tuple = tuple((P.find(a) for a in a_tuple))
p = P.find(a)
if ((p_tuple, p) not in pi_blocks):
pi_blocks.add((p_tuple, p))
for z_tuple in itertools.product(*[tZ[p] for p in p_tuple]):
rhs = ((1 - pi_rho.numargs) + sum((self._x[(p_i, z_i)] for (p_i, z_i) in zip(p_tuple, z_tuple))))
z = pi_rho.rho(*z_tuple)
if (z in tZ[p]):
c = (self._x[(p, z)] - rhs)
if c.is_zero():
continue
self.milp.add_constraint((c >= 0), name=f'pi/rho({composition_index})')
else:
self.milp.add_constraint((rhs <= 0), name=f'pi/rho({composition_index})')
def add_quadratic_relation_constraints(self):
'\n Add constraints enforcing that `s\\circ\\phi\\circ s =\n \\psi`.\n\n We do this by adding\n\n .. MATH::\n\n x_{p(a), z} = x_{p(\\psi(z)), \\phi(a)}\n\n for `a\\in A` and `z\\in Z`, where `\\phi:A\\to Z` and `\\psi:Z\\to\n A`. Note that, in particular, `\\phi` must be constant on\n blocks.\n\n EXAMPLES::\n\n sage: A = B = DyckWords(3)\n sage: bij = Bijectionist(A, B)\n sage: bij.set_statistics((lambda D: D.number_of_touch_points(), lambda D: D.number_of_initial_rises()))\n sage: ascii_art(sorted(bij.minimal_subdistributions_iterator()))\n [ ( [ /\\ ] )\n [ ( [ / \\ ] ) ( [ /\\ /\\ ] [ /\\ /\\/\\ ] )\n [ ( [ /\\/\\/\\ ], [ / \\ ] ), ( [ /\\/ \\, / \\/\\ ], [ / \\/\\, / \\ ] ),\n <BLANKLINE>\n ( [ /\\ ] ) ]\n ( [ /\\/\\ / \\ ] [ /\\ ] ) ]\n ( [ / \\, / \\ ], [ /\\/\\/\\, /\\/ \\ ] ) ]\n sage: bij.set_quadratic_relation((lambda D: D, lambda D: D)) # indirect doctest\n sage: ascii_art(sorted(bij.minimal_subdistributions_iterator()))\n [ ( [ /\\ ] )\n [ ( [ / \\ ] ) ( [ /\\ ] [ /\\/\\ ] )\n [ ( [ /\\/\\/\\ ], [ / \\ ] ), ( [ /\\/ \\ ], [ / \\ ] ),\n <BLANKLINE>\n <BLANKLINE>\n ( [ /\\ ] [ /\\ ] ) ( [ /\\/\\ ] [ /\\ ] )\n ( [ / \\/\\ ], [ / \\/\\ ] ), ( [ / \\ ], [ /\\/ \\ ] ),\n <BLANKLINE>\n ( [ /\\ ] ) ]\n ( [ / \\ ] ) ]\n ( [ / \\ ], [ /\\/\\/\\ ] ) ]\n\n '
P = self._bijectionist._P
for (phi, psi) in self._bijectionist._phi_psi:
for (p, block) in P.root_to_elements_dict().items():
z0 = phi(p)
assert all(((phi(a) == z0) for a in block)), ('phi must be constant on the block %s' % block)
for z in self._bijectionist._possible_block_values[p]:
p0 = P.find(psi(z))
if (z0 in self._bijectionist._possible_block_values[p0]):
c = (self._x[(p, z)] - self._x[(p0, z0)])
if c.is_zero():
continue
self.milp.add_constraint((c == 0), name=f'i: s({p})={z}<->s(psi({z})=phi({p})')
else:
self.milp.add_constraint((self._x[(p, z)] == 0), name=f'i: s({p})!={z}')
def add_homomesic_constraints(self):
'\n Add constraints enforcing that `s` has constant average\n on the blocks of `Q`.\n\n We do this by adding\n\n .. MATH::\n\n \\frac{1}{|q|}\\sum_{a\\in q} \\sum_z z x_{p(a), z} =\n \\frac{1}{|q_0|}\\sum_{a\\in q_0} \\sum_z z x_{p(a), z},\n\n for `q\\in Q`, where `q_0` is some fixed block of `Q`.\n\n EXAMPLES::\n\n sage: A = B = [1,2,3]\n sage: bij = Bijectionist(A, B, lambda b: b % 3)\n sage: bij.set_homomesic([[1,2], [3]]) # indirect doctest\n sage: list(bij.solutions_iterator())\n [{1: 2, 2: 0, 3: 1}, {1: 0, 2: 2, 3: 1}]\n '
Q = self._bijectionist._Q
if (Q is None):
return
P = self._bijectionist._P
tZ = self._bijectionist._possible_block_values
def sum_q(q):
return sum((sum(((z * self._x[(P.find(a), z)]) for z in tZ[P.find(a)])) for a in q))
q0 = Q[0]
v0 = sum_q(q0)
for q in Q[1:]:
self.milp.add_constraint(((len(q0) * sum_q(q)) == (len(q) * v0)), name=f'h: ({q})~({q0})')
|
def _invert_dict(d):
'\n Return the dictionary whose keys are the values of the input and\n whose values are the lists of preimages.\n\n INPUT:\n\n - ``d`` -- a dict\n\n EXAMPLES::\n\n sage: from sage.combinat.bijectionist import _invert_dict\n sage: _invert_dict({1: "a", 2: "a", 3:"b"})\n {\'a\': [1, 2], \'b\': [3]}\n\n sage: _invert_dict({})\n {}\n '
preimages = {}
for (k, v) in d.items():
preimages[v] = (preimages.get(v, []) + [k])
return preimages
|
def _disjoint_set_roots(d):
'\n Return the representatives of the blocks of the disjoint set.\n\n INPUT:\n\n - ``d`` -- a :class:`sage.sets.disjoint_set.DisjointSet_of_hashables`\n\n EXAMPLES::\n\n sage: from sage.combinat.bijectionist import _disjoint_set_roots\n sage: d = DisjointSet(\'abcde\')\n sage: d.union("a", "b")\n sage: d.union("a", "c")\n sage: d.union("e", "d")\n sage: _disjoint_set_roots(d)\n dict_keys([\'a\', \'e\'])\n '
return d.root_to_elements_dict().keys()
|
def _non_copying_intersection(sets):
'\n Return the intersection of the sets.\n\n If the intersection is equal to one of the sets, return this\n set.\n\n EXAMPLES::\n\n sage: from sage.combinat.bijectionist import _non_copying_intersection\n sage: A = set(range(7000)); B = set(range(8000));\n sage: _non_copying_intersection([A, B]) is A\n True\n\n sage: A = set([1,2]); B = set([2,3])\n sage: _non_copying_intersection([A, B])\n {2}\n\n '
sets = sorted(sets, key=len)
result = set.intersection(*sets)
n = len(result)
for s in sets:
N = len(s)
if (n < N):
return result
if (s == result):
return s
|
class BinaryRecurrenceSequence(SageObject):
'\n Create a linear binary recurrence sequence defined by initial conditions\n `u_0` and `u_1` and recurrence relation `u_{n+2} = b*u_{n+1}+c*u_n`.\n\n INPUT:\n\n - ``b`` -- an integer (partially determining the recurrence relation)\n\n - ``c`` -- an integer (partially determining the recurrence relation)\n\n - ``u0`` -- an integer (the 0th term of the binary recurrence sequence)\n\n - ``u1`` -- an integer (the 1st term of the binary recurrence sequence)\n\n\n OUTPUT:\n\n - An integral linear binary recurrence sequence defined by ``u0``, ``u1``, and `u_{n+2} = b*u_{n+1}+c*u_n`\n\n .. SEEALSO::\n\n :func:`fibonacci`, :func:`lucas_number1`, :func:`lucas_number2`\n\n EXAMPLES::\n\n sage: R = BinaryRecurrenceSequence(3,3,2,1)\n sage: R\n Binary recurrence sequence defined by: u_n = 3 * u_{n-1} + 3 * u_{n-2};\n With initial conditions: u_0 = 2, and u_1 = 1\n\n '
def __init__(self, b, c, u0=0, u1=1):
'\n See :class:`BinaryRecurrenceSequence` for full documentation.\n\n EXAMPLES::\n\n sage: R = BinaryRecurrenceSequence(3,3,2,1)\n sage: R\n Binary recurrence sequence defined by: u_n = 3 * u_{n-1} + 3 * u_{n-2};\n With initial conditions: u_0 = 2, and u_1 = 1\n\n sage: R = BinaryRecurrenceSequence(1,1)\n sage: loads(R.dumps()) == R\n True\n\n '
self.b = b
self.c = c
self.u0 = u0
self.u1 = u1
self._period_dict = {}
self._PGoodness = {}
self._ell = 1
def __repr__(self):
'\n Give string representation of the class.\n\n EXAMPLES::\n\n sage: R = BinaryRecurrenceSequence(3,3,2,1)\n sage: R\n Binary recurrence sequence defined by: u_n = 3 * u_{n-1} + 3 * u_{n-2};\n With initial conditions: u_0 = 2, and u_1 = 1\n\n '
return ((((((('Binary recurrence sequence defined by: u_n = ' + str(self.b)) + ' * u_{n-1} + ') + str(self.c)) + ' * u_{n-2};\nWith initial conditions: u_0 = ') + str(self.u0)) + ', and u_1 = ') + str(self.u1))
def __eq__(self, other):
'\n Compare two binary recurrence sequences.\n\n EXAMPLES::\n\n sage: R = BinaryRecurrenceSequence(3,3,2,1)\n sage: S = BinaryRecurrenceSequence(3,3,2,1)\n sage: R == S\n True\n\n sage: T = BinaryRecurrenceSequence(3,3,2,2)\n sage: R == T\n False\n '
return ((self.u0 == other.u0) and (self.u1 == other.u1) and (self.b == other.b) and (self.c == other.c))
def __call__(self, n, modulus=0):
'\n Give the nth term of a binary recurrence sequence, possibly mod some modulus.\n\n INPUT:\n\n - ``n`` -- an integer (the index of the term in the binary recurrence sequence)\n\n - ``modulus`` -- a natural number (optional -- default value is 0)\n\n OUTPUT:\n\n - An integer (the nth term of the binary recurrence sequence modulo ``modulus``)\n\n EXAMPLES::\n\n sage: R = BinaryRecurrenceSequence(3,3,2,1)\n sage: R(2)\n 9\n sage: R(101)\n 16158686318788579168659644539538474790082623100896663971001\n sage: R(101,12)\n 9\n sage: R(101)%12\n 9\n '
R = Integers(modulus)
F = matrix(R, [[0, 1], [self.c, self.b]])
v = vector(R, [self.u0, self.u1])
return list(((F ** n) * v))[0]
def is_degenerate(self):
'\n Decide whether the binary recurrence sequence is degenerate.\n\n Let `\\alpha` and `\\beta` denote the roots of the characteristic polynomial\n `p(x) = x^2-bx -c`. Let `a = u_1-u_0\\beta/(\\beta - \\alpha)` and\n `b = u_1-u_0\\alpha/(\\beta - \\alpha)`. The sequence is, thus, given by\n `u_n = a \\alpha^n - b\\beta^n`. Then we say that the sequence is nondegenerate\n if and only if `a*b*\\alpha*\\beta \\neq 0` and `\\alpha/\\beta` is not a\n root of unity.\n\n More concretely, there are 4 classes of degeneracy, that can all be formulated\n in terms of the matrix `F = [[0,1], [c, b]]`.\n\n - `F` is singular -- this corresponds to ``c`` = 0, and thus `\\alpha*\\beta = 0`. This sequence is geometric after term ``u0`` and so we call it ``quasigeometric``.\n\n - `v = [[u_0], [u_1]]` is an eigenvector of `F` -- this corresponds to a ``geometric`` sequence with `a*b = 0`.\n\n - `F` is nondiagonalizable -- this corresponds to `\\alpha = \\beta`. This sequence will be the point-wise product of an arithmetic and geometric sequence.\n\n - `F^k` is scaler, for some `k>1` -- this corresponds to `\\alpha/\\beta` a `k` th root of unity. This sequence is a union of several geometric sequences, and so we again call it ``quasigeometric``.\n\n EXAMPLES::\n\n sage: S = BinaryRecurrenceSequence(0,1)\n sage: S.is_degenerate()\n True\n sage: S.is_geometric()\n False\n sage: S.is_quasigeometric()\n True\n\n sage: R = BinaryRecurrenceSequence(3,-2)\n sage: R.is_degenerate()\n False\n\n sage: T = BinaryRecurrenceSequence(2,-1)\n sage: T.is_degenerate()\n True\n sage: T.is_arithmetic()\n True\n '
D = ((self.b ** 2) + (4 * self.c))
if (D != 0):
if D.is_square():
A = sqrt(D)
else:
K = QuadraticField(D, 'x')
A = K.gen()
aa = ((self.u1 - ((self.u0 * (self.b + A)) / 2)) / A)
bb = ((self.u1 - ((self.u0 * (self.b - A)) / 2)) / A)
if (self.b != A):
if ((((self.b + A) / (self.b - A)) ** 6) == 1):
return True
else:
return True
return ((((aa * bb) * (self.b + A)) * (self.b - A)) == 0)
return True
def is_geometric(self):
'\n Decide whether the binary recurrence sequence is geometric - ie a geometric sequence.\n\n This is a subcase of a degenerate binary recurrence sequence, for which `ab=0`, i.e.\n `u_{n}/u_{n-1}=r` for some value of `r`.\n\n See :meth:`is_degenerate` for a description of\n degeneracy and definitions of `a` and `b`.\n\n EXAMPLES::\n\n sage: S = BinaryRecurrenceSequence(2,0,1,2)\n sage: [S(i) for i in range(10)]\n [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]\n sage: S.is_geometric()\n True\n '
return ((self.u1 ** 2) == (((self.b * self.u1) + (self.c * self.u0)) * self.u0))
def is_quasigeometric(self):
'\n Decide whether the binary recurrence sequence is degenerate and similar to a geometric sequence,\n i.e. the union of multiple geometric sequences, or geometric after term ``u0``.\n\n If `\\alpha/\\beta` is a `k` th root of unity, where `k>1`, then necessarily `k = 2, 3, 4, 6`.\n Then `F = [[0,1],[c,b]` is diagonalizable, and `F^k = [[\\alpha^k, 0], [0,\\beta^k]]` is scaler\n matrix. Thus for all values of `j` mod `k`, the `j` mod `k` terms of `u_n` form a geometric\n series.\n\n If `\\alpha` or `\\beta` is zero, this implies that `c=0`. This is the case when `F` is\n singular. In this case, `u_1, u_2, u_3, ...` is geometric.\n\n EXAMPLES::\n\n sage: S = BinaryRecurrenceSequence(0,1)\n sage: [S(i) for i in range(10)]\n [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]\n sage: S.is_quasigeometric()\n True\n\n sage: R = BinaryRecurrenceSequence(3,0)\n sage: [R(i) for i in range(10)]\n [0, 1, 3, 9, 27, 81, 243, 729, 2187, 6561]\n sage: R.is_quasigeometric()\n True\n '
if (self.c == 0):
return True
D = ((self.b ** 2) + (4 * self.c))
if (D != 0):
if D.is_square():
A = sqrt(D)
else:
K = QuadraticField(D, 'x')
A = K.gen()
if ((((self.b + A) / (self.b - A)) ** 6) == 1):
return True
return False
def is_arithmetic(self):
'\n Decide whether the sequence is degenerate and an arithmetic sequence.\n\n The sequence is arithmetic if and only if `u_1 - u_0 = u_2 - u_1 = u_3 - u_2`.\n\n This corresponds to the matrix `F = [[0,1],[c,b]]` being nondiagonalizable\n and `\\alpha/\\beta = 1`.\n\n EXAMPLES::\n\n sage: S = BinaryRecurrenceSequence(2,-1)\n sage: [S(i) for i in range(10)]\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n sage: S.is_arithmetic()\n True\n '
return ((self(1) - self(0)) == (self(2) - self(1)) == (self(3) - self(2)))
def period(self, m):
'\n Return the period of the binary recurrence sequence modulo\n an integer ``m``.\n\n If `n_1` is congruent to `n_2` modulo ``period(m)``, then `u_{n_1}` is\n is congruent to `u_{n_2}` modulo ``m``.\n\n INPUT:\n\n - ``m`` -- an integer (modulo which the period of the recurrence relation is calculated).\n\n OUTPUT:\n\n - The integer (the period of the sequence modulo m)\n\n EXAMPLES:\n\n If `p = \\pm 1 \\mod 5`, then the period of the Fibonacci sequence\n mod `p` is `p-1` (c.f. Lemma 3.3 of [BMS2006]_).\n\n ::\n\n sage: R = BinaryRecurrenceSequence(1,1)\n sage: R.period(31)\n 30\n\n sage: [R(i) % 4 for i in range(12)]\n [0, 1, 1, 2, 3, 1, 0, 1, 1, 2, 3, 1]\n sage: R.period(4)\n 6\n\n This function works for degenerate sequences as well.\n\n ::\n\n sage: S = BinaryRecurrenceSequence(2,0,1,2)\n sage: S.is_degenerate()\n True\n sage: S.is_geometric()\n True\n sage: [S(i) % 17 for i in range(16)]\n [1, 2, 4, 8, 16, 15, 13, 9, 1, 2, 4, 8, 16, 15, 13, 9]\n sage: S.period(17)\n 8\n\n .. NOTE:: The answer is cached.\n '
if (m in self._period_dict):
return self._period_dict[m]
else:
R = Integers(m)
A = matrix(R, [[0, 1], [self.c, self.b]])
w = vector(R, [self.u0, self.u1])
Fac = list(m.factor())
Periods = {}
for (p, e) in Fac:
if (p in self._period_dict):
perp = self._period_dict[p]
else:
F = A.change_ring(GF(p))
v = w.change_ring(GF(p))
FF = (F ** (p - 1))
p1fac = list((p - 1).factor())
if ((FF * v) == v):
M = (p - 1)
Mfac = p1fac
elif (FF.trace() == 2):
M = (p - 1)
Mfac = p1fac
F = (F ** p)
else:
M = ((p + 1) * (p - 1))
p2fac = list((p + 1).factor())
Mfac_dic = {}
for (i0, i1) in list((p1fac + p2fac)):
if (i0 not in Mfac_dic):
Mfac_dic[i0] = i1
else:
Mfac_dic[i0] += i1
Mfac = list(Mfac_dic.items())
Mfac = list(Mfac)
C = []
for (i0, i1) in Mfac:
for _ in range(i1):
C.append(i0)
Mfac = C
n = M
for ii in Mfac:
b = (n // ii)
if (((F ** b) * v) == v):
n = b
perp = n
F = A.change_ring(Integers((p ** e)))
v = w.change_ring(Integers((p ** e)))
FF = (F ** perp)
if ((FF * v) == v):
perpe = perp
else:
tries = 0
while True:
tries += 1
FF = (FF ** p)
if ((FF * v) == v):
perpe = (perp * (p ** tries))
break
Periods[p] = perpe
period = 1
for p in Periods:
period = lcm(Periods[p], period)
self._period_dict[m] = period
return period
def pthpowers(self, p, Bound):
'\n Find the indices of proveably all pth powers in the recurrence sequence bounded by Bound.\n\n Let `u_n` be a binary recurrence sequence. A ``p`` th power in `u_n` is a solution\n to `u_n = y^p` for some integer `y`. There are only finitely many ``p`` th powers in\n any recurrence sequence [SS1983]_.\n\n INPUT:\n\n - ``p`` - a rational prime integer (the fixed p in `u_n = y^p`)\n\n - ``Bound`` - a natural number (the maximum index `n` in `u_n = y^p` that is checked).\n\n OUTPUT:\n\n - A list of the indices of all ``p`` th powers less bounded by\n ``Bound``. If the sequence is degenerate and there are many\n ``p`` th powers, raises :class:`ValueError`.\n\n EXAMPLES::\n\n sage: R = BinaryRecurrenceSequence(1,1) #the Fibonacci sequence\n sage: R.pthpowers(2, 10**10) # long time (7 seconds) -- in fact these are all squares, c.f. [BMS2006]_\n [0, 1, 2, 12]\n\n sage: S = BinaryRecurrenceSequence(8,1) #a Lucas sequence\n sage: S.pthpowers(3,10**10) # long time (3 seconds) -- provably finds the indices of all 3rd powers less than 10^10\n [0, 1, 2]\n\n sage: Q = BinaryRecurrenceSequence(3,3,2,1)\n sage: Q.pthpowers(11,10**10) # long time (7.5 seconds)\n [1]\n\n If the sequence is degenerate, and there are no ``p`` th powers, returns `[]`. Otherwise, if\n there are many ``p`` th powers, raises :class:`ValueError`.\n\n ::\n\n sage: T = BinaryRecurrenceSequence(2,0,1,2)\n sage: T.is_degenerate()\n True\n sage: T.is_geometric()\n True\n sage: T.pthpowers(7, 10**30) # needs sage.symbolic\n Traceback (most recent call last):\n ...\n ValueError: the degenerate binary recurrence sequence is geometric or\n quasigeometric and has many pth powers\n\n sage: L = BinaryRecurrenceSequence(4,0,2,2)\n sage: [L(i).factor() for i in range(10)]\n [2, 2, 2^3, 2^5, 2^7, 2^9, 2^11, 2^13, 2^15, 2^17]\n sage: L.is_quasigeometric()\n True\n sage: L.pthpowers(2, 10**30) # needs sage.symbolic\n []\n\n .. NOTE::\n\n This function is primarily optimized in the range where\n ``Bound`` is much larger than ``p``.\n '
self._PGoodness = {}
self._ell = 1
if (self.is_geometric() or self.is_quasigeometric()):
no_powers = True
for i in range(1, ((6 * p) + 1)):
if _is_p_power(self(i), p):
no_powers = False
break
if no_powers:
if _is_p_power(self.u0, p):
return [0]
return []
else:
raise ValueError('the degenerate binary recurrence sequence is geometric or quasigeometric and has many pth powers')
elif (((self.b ** 2) + (4 * self.c)) == 0):
alpha = (self.b / 2)
for k in range(1, (p + 1)):
A = (((alpha ** (k - 1)) * self.u0) + (k * (((alpha ** (k - 1)) * self.u1) - (self.u0 * (alpha ** k)))))
B = (p * (((alpha ** (k - 1)) * self.u1) - (self.u0 * (alpha ** k))))
if _is_p_power_mod(A, p, B):
raise ValueError('the degenerate binary recurrence sequence has many pth powers')
return []
else:
if (Bound < (3 * p)):
powers = []
ell = (p + 1)
while (not is_prime(ell)):
ell += p
F = GF(ell)
a0 = F(self.u0)
a1 = F(self.u1)
(bf, cf) = (F(self.b), F(self.c))
for n in range(Bound):
if _is_p_power_mod(a0, p, ell):
if _is_p_power(self(n), p):
powers.append(n)
(a0, a1) = (a1, ((bf * a1) + (cf * a0)))
else:
powers = []
cong = [0]
Possible_count = {}
qqold = 1
M1 = 1
M2 = p
qq = 1
while True:
patience = (0.01 * _estimated_time(lcm(M2, (p * next_prime_power(qq))), M1, len(cong), p))
tries = 0
while True:
ell = _next_good_prime(p, self, qq, patience, qqold)
if ell:
(cong1, modu) = _find_cong1(p, self, ell)
CongNew = []
M = lcm(M1, modu)
for k in range((M // M1)):
for i in cong:
CongNew.append(((k * M1) + i))
cong = set(CongNew)
M1 = M
killed_something = False
for i in list(cong):
if ((i % modu) not in cong1):
cong.remove(i)
killed_something = True
if (M1 == M2):
if (not killed_something):
tries += 1
if (tries == 2):
cong = list(cong)
qqold = qq
qq = next_prime_power(qq)
M2 = lcm(M2, (p * qq))
break
else:
qq = next_prime_power(qq)
M2 = lcm(M2, (p * qq))
cong = list(cong)
break
for i in cong:
if (i in Possible_count):
Possible_count[i] += 1
else:
Possible_count[i] = 1
for i in Possible_count:
if (Possible_count[i] == 7):
n = Integer(i)
if (n < Bound):
if _is_p_power(self(n), p):
powers.append(n)
if (len(cong) > len(powers)):
if (cong[len(powers)] > Bound):
break
elif (M1 > Bound):
break
return powers
|
def _prime_powers(N):
'\n Find the prime powers dividing ``N``.\n\n In other words, if `N = q_1^(e_1)q_2^(e_2)...q_n^(e_n)`, it returns\n `[q_1^(e_1),q_2^(e_2),...,q_n^(e_n)]`.\n\n INPUT:\n\n - ``N`` -- an integer\n\n OUTPUT:\n\n - A list of the prime powers dividing N.\n\n EXAMPLES::\n\n sage: sage.combinat.binary_recurrence_sequences._prime_powers(124656)\n [3, 16, 49, 53]\n\n sage: sage.combinat.binary_recurrence_sequences._prime_powers(65537)\n [65537]\n '
return sorted(((i ** j) for (i, j) in N.factor()))
|
def _largest_ppower_divisor(N):
'\n Find the largest prime power divisor of N.\n\n INPUT:\n\n - ``N`` -- an integer\n\n OUTPUT:\n\n The largest prime power dividing ``N``.\n\n EXAMPLES::\n\n sage: sage.combinat.binary_recurrence_sequences._largest_ppower_divisor(124656)\n 53\n sage: sage.combinat.binary_recurrence_sequences._largest_ppower_divisor(65537)\n 65537\n '
return _prime_powers(N)[(- 1)]
|
def _goodness(n, R, p):
'\n Return the goodness of ``n`` for the sequence ``R`` and the prime ``p`` -- that is the largest\n non-``p`` prime power dividing ``period(n)``.\n\n INPUT:\n\n - ``n`` -- an integer\n\n - ``R`` -- an object in the class ``BinaryRecurrenceSequence``\n\n - ``p`` -- a rational prime\n\n OUTPUT:\n\n - An integer which is the "goodness" of ``n``, i.e. the largest non-``p`` prime power dividing ``period(n)``.\n\n EXAMPLES::\n\n sage: R = BinaryRecurrenceSequence(11,2)\n sage: sage.combinat.binary_recurrence_sequences._goodness(89,R,7)\n 11\n\n sage: R = BinaryRecurrenceSequence(1,1)\n sage: sage.combinat.binary_recurrence_sequences._goodness(13,R,7)\n 4\n sage: R.period(13) #the period of R mod 13 is divisible by 7\n 28\n '
K = R.period(n)
return _largest_ppower_divisor((K // K.gcd(p)))
|
def _next_good_prime(p, R, qq, patience, qqold):
'\n Find the next prime `\\ell` which is good by ``qq`` but not by ``qqold``, 1 mod ``p``, and for which\n ``b^2+4*c`` is a square mod `\\ell`, for the sequence ``R`` if it is possible in runtime patience.\n\n INPUT:\n\n - ``p`` -- a prime\n\n - ``R`` -- an object in the class ``BinaryRecurrenceSequence``\n\n - ``qq`` -- a perfect power\n\n - ``patience`` -- a real number\n\n - ``qqold`` -- a perfect power less than or equal to ``qq``\n\n OUTPUT:\n\n - A prime `\\ell` such that `\\ell` is 1 mod ``p``, ``b^2+4*c`` is a square mod `\\ell` and the period of `\\ell` has ``goodness`` by ``qq`` but not ``qqold``, if patience has not be surpased. Otherwise ``False``.\n\n\n EXAMPLES::\n\n sage: R = BinaryRecurrenceSequence(1,1)\n sage: sage.combinat.binary_recurrence_sequences._next_good_prime(7,R,1,100,1) #ran out of patience to search for good primes\n False\n sage: sage.combinat.binary_recurrence_sequences._next_good_prime(7,R,2,100,1)\n 29\n sage: sage.combinat.binary_recurrence_sequences._next_good_prime(7,R,2,100,2) #ran out of patience, as qqold == qq, so no primes work\n False\n\n '
Possible_Primes = []
for j in R._PGoodness:
if ((qqold < j <= qq) and len(R._PGoodness[j])):
Possible_Primes.append(R._PGoodness[j][0])
if Possible_Primes:
q = min(Possible_Primes)
n = _goodness(q, R, p)
del R._PGoodness[n][0]
return q
else:
i = 0
while (i < patience):
i += 1
R._ell = next_prime(R._ell)
if ((R._ell % p) == 1):
if (legendre_symbol(((R.b ** 2) + (4 * R.c)), R._ell) == 1):
N = _goodness(R._ell, R, p)
if (qqold < N <= qq):
return R._ell
elif (N in R._PGoodness):
R._PGoodness[N].append(R._ell)
else:
R._PGoodness[N] = [R._ell]
return False
|
def _is_p_power_mod(a, p, N):
"\n Determine if ``a`` is a ``p`` th power modulo ``N``.\n\n By the CRT, this is equivalent to the condition that ``a`` be a ``p`` th power mod all\n distinct prime powers dividing ``N``. For each of these, we use the strong statement of\n Hensel's lemma to lift ``p`` th powers mod `q` or `q^2` or `q^3` to ``p`` th powers mod `q^e`.\n\n INPUT:\n\n - ``a`` -- an integer\n\n - ``p`` -- a rational prime number\n\n - ``N`` -- a positive integer\n\n OUTPUT:\n\n - True if ``a`` is a ``p`` th power modulo ``N``; False otherwise.\n\n EXAMPLES::\n\n sage: sage.combinat.binary_recurrence_sequences._is_p_power_mod(2**3,7,29)\n False\n sage: sage.combinat.binary_recurrence_sequences._is_p_power_mod(2**3,3,29)\n True\n\n "
for (q, e) in N.factor():
v = a.valuation(q)
if (v >= e):
continue
if (v % p):
return False
aa = (a / (q ** v))
ee = (e - v)
if (q != p):
if ((q % p) == 1):
if ((GF(q)(aa) ** ((q - 1) / p)) != 1):
return False
elif (ee > 1):
if (p % 2):
if ((Integers((p ** 2))(aa) ** (p - 1)) != 1):
return False
elif (ee == 2):
if ((aa % 4) != 1):
return False
elif ((aa % 8) != 1):
return False
return True
|
def _estimated_time(M2, M1, length, p):
'\n Find the estimated time to extend congruences mod M1 to consistent congruences mod M2.\n\n INPUT:\n\n - ``M2`` -- an integer (the new modulus)\n\n - ``M1`` -- an integer (the old modulus)\n\n - ``length`` -- a list (the current length of the list of congruences mod ``M1``)\n\n - ``p`` -- a prime\n\n OUTPUT:\n\n - The estimated run time of the "CRT" step to combine consistent congruences.\n\n EXAMPLES::\n\n sage: from sage.combinat.binary_recurrence_sequences import _estimated_time\n sage: _estimated_time(2**4*3**2*5*7*11*13*17, 2**4*3**2*5*7*11*13, 20, 7) # needs sage.symbolic\n 106.211159309421\n\n '
Q = (p * log(M2))
NPrimes = (log((M2 / M1)) / log(Q))
return (length * ((Q / p) ** NPrimes)).n()
|
def _find_cong1(p, R, ell):
'\n Find the list of permissible indices `n` for which `u_n = y^p` mod ``ell``.\n\n INPUT:\n\n - ``p`` -- a prime number\n\n - ``R`` -- an object in class :class:`BinaryRecurrenceSequence`\n\n - ``ell`` -- a prime number\n\n OUTPUT:\n\n - A list of permissible values of `n` modulo ``period(ell)`` and the integer ``period(ell)``.\n\n EXAMPLES::\n\n sage: R = BinaryRecurrenceSequence(1,1)\n sage: sage.combinat.binary_recurrence_sequences._find_cong1(7, R, 29) # needs sage.rings.finite_rings\n ([0, 1, 2, 12, 13], 14)\n '
F = GF(ell)
u0 = F(R.u0)
u1 = F(R.u1)
(bf, cf) = (F(R.b), F(R.c))
a0 = u0
a1 = u1
PPowers = set(((i ** p) for i in F))
modu = R.period(ell)
cong1 = []
for n in range(modu):
if (a0 in PPowers):
cong1.append(n)
(a0, a1) = (a1, ((bf * a1) + (cf * a0)))
cong1.sort()
return (cong1, modu)
|
def _is_p_power(a, p):
'\n Determine whether ``a`` is a perfect ``p`` th power.\n\n INPUT:\n\n - ``a`` -- an integer\n\n - ``p`` -- a prime number\n\n OUTPUT:\n\n - True if ``a`` is a ``p`` th power; else False.\n\n EXAMPLES::\n\n sage: sage.combinat.binary_recurrence_sequences._is_p_power(2**7, 7) # needs sage.symbolic\n True\n sage: sage.combinat.binary_recurrence_sequences._is_p_power(2**7*3**2, 7) # needs sage.symbolic\n False\n '
return ((int((a ** (1 / p))) ** p) == a)
|
class BinaryTree(AbstractClonableTree, ClonableArray, metaclass=InheritComparisonClasscallMetaclass):
'\n Binary trees.\n\n Binary trees here mean ordered (a.k.a. plane) finite binary\n trees, where "ordered" means that the children of each node are\n ordered.\n\n Binary trees contain nodes and leaves, where each node has two\n children while each leaf has no children. The number of leaves\n of a binary tree always equals the number of nodes plus `1`.\n\n INPUT:\n\n - ``children`` -- ``None`` (default) or a list, tuple or iterable of\n length `2` of binary trees or convertible objects. This corresponds\n to the standard recursive definition of a binary tree as either a\n leaf or a pair of binary trees. Syntactic sugar allows leaving out\n all but the outermost calls of the ``BinaryTree()`` constructor, so\n that, e. g., ``BinaryTree([BinaryTree(None),BinaryTree(None)])`` can\n be shortened to ``BinaryTree([None,None])``. It is also allowed to\n abbreviate ``[None, None]`` by ``[]``.\n\n - ``check`` -- (default: ``True``) whether check for binary should be\n performed or not.\n\n EXAMPLES::\n\n sage: BinaryTree()\n .\n sage: BinaryTree(None)\n .\n sage: BinaryTree([])\n [., .]\n sage: BinaryTree([None, None])\n [., .]\n sage: BinaryTree([None, []])\n [., [., .]]\n sage: BinaryTree([[], None])\n [[., .], .]\n sage: BinaryTree("[[], .]")\n [[., .], .]\n sage: BinaryTree([None, BinaryTree([None, None])])\n [., [., .]]\n\n sage: BinaryTree([[], None, []])\n Traceback (most recent call last):\n ...\n ValueError: this is not a binary tree\n\n TESTS::\n\n sage: t1 = BinaryTree([[None, [[],[[], None]]],[[],[]]])\n sage: t2 = BinaryTree([[[],[]],[]])\n sage: with t1.clone() as t1c:\n ....: t1c[1,1,1] = t2\n sage: t1 == t1c\n False\n '
@staticmethod
def __classcall_private__(cls, *args, **opts):
"\n Ensure that binary trees created by the enumerated sets and directly\n are the same and that they are instances of :class:`BinaryTree`.\n\n TESTS::\n\n sage: from sage.combinat.binary_tree import BinaryTrees_all\n sage: issubclass(BinaryTrees_all().element_class, BinaryTree)\n True\n sage: t0 = BinaryTree([[],[[], None]])\n sage: t0.parent()\n Binary trees\n sage: type(t0)\n <class 'sage.combinat.binary_tree.BinaryTrees_all_with_category.element_class'>\n\n sage: t1 = BinaryTrees()([[],[[], None]])\n sage: t1.parent() is t0.parent()\n True\n sage: type(t1) is type(t0)\n True\n\n sage: t1 = BinaryTrees(4)([[],[[], None]])\n sage: t1.parent() is t0.parent()\n True\n sage: type(t1) is type(t0)\n True\n "
return cls._auto_parent.element_class(cls._auto_parent, *args, **opts)
@lazy_class_attribute
def _auto_parent(cls):
'\n The automatic parent of the elements of this class.\n\n When calling the constructor of an element of this class, one needs a\n parent. This class attribute specifies which parent is used.\n\n EXAMPLES::\n\n sage: BinaryTree._auto_parent\n Binary trees\n sage: BinaryTree([None, None]).parent()\n Binary trees\n '
return BinaryTrees_all()
def __init__(self, parent, children=None, check=True):
'\n TESTS::\n\n sage: BinaryTree([None, None]).parent()\n Binary trees\n sage: BinaryTree("[., [., [., .]]]")\n [., [., [., .]]]\n sage: BinaryTree("[.,.,.]")\n Traceback (most recent call last):\n ...\n ValueError: this is not a binary tree\n sage: all(BinaryTree(repr(bt)) == bt for i in range(6) for bt in BinaryTrees(i))\n True\n\n `\\QQ` (or any number field) has a ``list()`` method that\n returns itself as a `\\QQ`-vector represented as a list.\n Before :trac:`23961`, this would cause an infinite recursion\n because `\\QQ` elements give a list of length 1. For more\n details, see :trac:`23961`. We test that constructing\n binary trees from elements from `\\QQ` terminates with\n an appropriate error::\n\n sage: BinaryTree(1/2)\n Traceback (most recent call last):\n ...\n ValueError: this is not a binary tree\n '
if isinstance(children, str):
children = children.replace('.', 'None')
from ast import literal_eval
children = literal_eval(children)
if (children is None):
children = []
elif (isinstance(children, (list, tuple)) and (not children)):
E = self.__class__(parent, None, check=check)
children = [E, E]
elif ((children.__class__ is self.__class__) and (children.parent() == parent)):
children = list(children)
else:
children = list(children)
if (children and (len(children) != 2)):
raise ValueError('this is not a binary tree')
children = [(x if ((x.__class__ is self.__class__) and (x.parent() == parent)) else self.__class__(parent, x, check=check)) for x in children]
ClonableArray.__init__(self, parent, children, check=check)
def check(self):
'\n Check that ``self`` is a binary tree.\n\n EXAMPLES::\n\n sage: BinaryTree([[], []]) # indirect doctest\n [[., .], [., .]]\n sage: BinaryTree([[], [], []]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: this is not a binary tree\n sage: BinaryTree([[]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: this is not a binary tree\n '
if (not ((not self) or (len(self) == 2))):
raise ValueError('this is not a binary tree')
__hash__ = ClonableArray.__hash__
def _repr_(self):
'\n TESTS::\n\n sage: t1 = BinaryTree([[], None]); t1 # indirect doctest\n [[., .], .]\n sage: BinaryTree([[None, t1], None]) # indirect doctest\n [[., [[., .], .]], .]\n '
if (not self):
return '.'
else:
return super()._repr_()
def _ascii_art_(self):
'\n TESTS::\n\n sage: ascii_art(BinaryTree())\n <BLANKLINE>\n sage: ascii_art(BinaryTree([]))\n o\n sage: for bt in BinaryTrees(3):\n ....: print(ascii_art(bt))\n o\n \\\n o\n \\\n o\n o\n \\\n o\n /\n o\n o\n / \\\n o o\n o\n /\n o\n \\\n o\n o\n /\n o\n /\n o\n sage: ascii_art(BinaryTree([None,[]]))\n o\n \\\n o\n sage: ascii_art(BinaryTree([None,[None,[]]]))\n o\n \\\n o\n \\\n o\n sage: ascii_art(BinaryTree([None,[[],None]]))\n o\n \\\n o\n /\n o\n sage: ascii_art(BinaryTree([None,[[[],[]],[]]]))\n o\n \\\n _o_\n / \\\n o o\n / \\\n o o\n sage: ascii_art(BinaryTree([None,[[None,[[],[]]],None]]))\n o\n \\\n o\n /\n o\n \\\n o\n / \\\n o o\n sage: ascii_art(BinaryTree([[],None]))\n o\n /\n o\n sage: ascii_art(BinaryTree([[[[],None], None],None]))\n o\n /\n o\n /\n o\n /\n o\n sage: ascii_art(BinaryTree([[[],[]],None]))\n o\n /\n o\n / \\\n o o\n sage: ascii_art(BinaryTree([[[None,[]],[[[],None],None]], None]))\n o\n /\n ___o___\n / \\\n o o\n \\ /\n o o\n /\n o\n sage: ascii_art(BinaryTree([[None,[[],[]]],None]))\n o\n /\n o\n \\\n o\n / \\\n o o\n sage: ascii_art(BinaryTree([[],[]]))\n o\n / \\\n o o\n sage: ascii_art(BinaryTree([[],[[],None]]))\n _o_\n / \\\n o o\n /\n o\n sage: ascii_art(BinaryTree([[None,[]],[[[],None],None]]))\n ___o___\n / \\\n o o\n \\ /\n o o\n /\n o\n sage: ascii_art(BinaryTree([[[],[]],[[],None]]))\n __o__\n / \\\n o o\n / \\ /\n o o o\n sage: ascii_art(BinaryTree([[[],[]],[[],[]]]))\n __o__\n / \\\n o o\n / \\ / \\\n o o o o\n sage: ascii_art(BinaryTree([[[[],[]],[[],[]]],[]]))\n ___o___\n / \\\n __o__ o\n / \\\n o o\n / \\ / \\\n o o o o\n sage: ascii_art(BinaryTree([[],[[[[],[]],[[],[]]],[]]]))\n _____o______\n / \\\n o ___o___\n / \\\n __o__ o\n / \\\n o o\n / \\ / \\\n o o o o\n '
def node_to_str(bt):
return (str(bt.label()) if hasattr(bt, 'label') else 'o')
if self.is_empty():
from sage.typeset.ascii_art import empty_ascii_art
return empty_ascii_art
from sage.typeset.ascii_art import AsciiArt
if (self[0].is_empty() and self[1].is_empty()):
bt_repr = AsciiArt([node_to_str(self)])
bt_repr._root = 1
return bt_repr
if self[0].is_empty():
node = node_to_str(self)
rr_tree = self[1]._ascii_art_()
if (rr_tree._root > 2):
f_line = ((' ' * (rr_tree._root - 3)) + node)
s_line = ((' ' * ((len(node) + rr_tree._root) - 3)) + '\\')
t_repr = (AsciiArt([f_line, s_line]) * rr_tree)
t_repr._root = (rr_tree._root - 2)
else:
f_line = node
s_line = (' ' + '\\')
t_line = (' ' * (len(node) + 1))
t_repr = (AsciiArt([f_line, s_line]) * (AsciiArt([t_line]) + rr_tree))
t_repr._root = rr_tree._root
t_repr._baseline = (t_repr._h - 1)
return t_repr
if self[1].is_empty():
node = node_to_str(self)
lr_tree = self[0]._ascii_art_()
f_line = ((' ' * (lr_tree._root + 1)) + node)
s_line = ((' ' * lr_tree._root) + '/')
t_repr = (AsciiArt([f_line, s_line]) * lr_tree)
t_repr._root = (lr_tree._root + 2)
t_repr._baseline = (t_repr._h - 1)
return t_repr
node = node_to_str(self)
lr_tree = self[0]._ascii_art_()
rr_tree = self[1]._ascii_art_()
nb_ = (((lr_tree._l - lr_tree._root) + rr_tree._root) - 1)
nb_L = (nb_ // 2)
nb_R = (nb_L + (nb_ % 2))
f_line = (((' ' * (lr_tree._root + 1)) + ('_' * nb_L)) + node)
f_line += ('_' * nb_R)
s_line = ((((' ' * lr_tree._root) + '/') + (' ' * (((len(node) + rr_tree._root) - 1) + (lr_tree._l - lr_tree._root)))) + '\\')
t_repr = (AsciiArt([f_line, s_line]) * ((lr_tree + AsciiArt([(' ' * (len(node) + 2))])) + rr_tree))
t_repr._root = ((lr_tree._root + nb_L) + 2)
t_repr._baseline = (t_repr._h - 1)
return t_repr
def _unicode_art_(self):
'\n TESTS::\n\n sage: unicode_art(BinaryTree())\n <BLANKLINE>\n sage: unicode_art(BinaryTree([]))\n o\n sage: for bt in BinaryTrees(3):\n ....: print(unicode_art(bt))\n o\n ╲\n o\n ╲\n o\n o\n ╲\n o\n ╱\n o\n o\n ╱ ╲\n o o\n o\n ╱\n o\n ╲\n o\n o\n ╱\n o\n ╱\n o\n sage: unicode_art(BinaryTree([None,[]]))\n o\n ╲\n o\n sage: unicode_art(BinaryTree([None,[None,[]]]))\n o\n ╲\n o\n ╲\n o\n sage: unicode_art(BinaryTree([None,[[],None]]))\n o\n ╲\n o\n ╱\n o\n sage: unicode_art(BinaryTree([None,[[[],[]],[]]]))\n o\n ╲\n _o_\n ╱ ╲\n o o\n ╱ ╲\n o o\n sage: unicode_art(BinaryTree([None,[[None,[[],[]]],None]]))\n o\n ╲\n o\n ╱\n o\n ╲\n o\n ╱ ╲\n o o\n sage: unicode_art(BinaryTree([[],None]))\n o\n ╱\n o\n sage: unicode_art(BinaryTree([[[[],None], None],None]))\n o\n ╱\n o\n ╱\n o\n ╱\n o\n sage: unicode_art(BinaryTree([[[],[]],None]))\n o\n ╱\n o\n ╱ ╲\n o o\n sage: unicode_art(BinaryTree([[[None,[]],[[[],None],None]], None]))\n o\n ╱\n ___o___\n ╱ ╲\n o o\n ╲ ╱\n o o\n ╱\n o\n sage: unicode_art(BinaryTree([[None,[[],[]]],None]))\n o\n ╱\n o\n ╲\n o\n ╱ ╲\n o o\n sage: unicode_art(BinaryTree([[],[]]))\n o\n ╱ ╲\n o o\n sage: unicode_art(BinaryTree([[],[[],None]]))\n _o_\n ╱ ╲\n o o\n ╱\n o\n sage: unicode_art(BinaryTree([[None,[]],[[[],None],None]]))\n ___o___\n ╱ ╲\n o o\n ╲ ╱\n o o\n ╱\n o\n sage: unicode_art(BinaryTree([[[],[]],[[],None]]))\n __o__\n ╱ ╲\n o o\n ╱ ╲ ╱\n o o o\n sage: unicode_art(BinaryTree([[[],[]],[[],[]]]))\n __o__\n ╱ ╲\n o o\n ╱ ╲ ╱ ╲\n o o o o\n sage: unicode_art(BinaryTree([[[[],[]],[[],[]]],[]]))\n ___o___\n ╱ ╲\n __o__ o\n ╱ ╲\n o o\n ╱ ╲ ╱ ╲\n o o o o\n sage: unicode_art(BinaryTree([[],[[[[],[]],[[],[]]],[]]]))\n _____o______\n ╱ ╲\n o ___o___\n ╱ ╲\n __o__ o\n ╱ ╲\n o o\n ╱ ╲ ╱ ╲\n o o o o\n '
def node_to_str(bt):
return (str(bt.label()) if hasattr(bt, 'label') else 'o')
if self.is_empty():
from sage.typeset.unicode_art import empty_unicode_art
return empty_unicode_art
from sage.typeset.unicode_art import UnicodeArt
if (self[0].is_empty() and self[1].is_empty()):
bt_repr = UnicodeArt([node_to_str(self)])
bt_repr._root = 1
return bt_repr
if self[0].is_empty():
node = node_to_str(self)
rr_tree = self[1]._unicode_art_()
if (rr_tree._root > 2):
f_line = ((' ' * (rr_tree._root - 3)) + node)
s_line = ((' ' * ((len(node) + rr_tree._root) - 3)) + '╲')
t_repr = (UnicodeArt([f_line, s_line]) * rr_tree)
t_repr._root = (rr_tree._root - 2)
else:
f_line = node
s_line = ' ╲'
t_line = (' ' * (len(node) + 1))
t_repr = (UnicodeArt([f_line, s_line]) * (UnicodeArt([t_line]) + rr_tree))
t_repr._root = rr_tree._root
t_repr._baseline = (t_repr._h - 1)
return t_repr
if self[1].is_empty():
node = node_to_str(self)
lr_tree = self[0]._unicode_art_()
f_line = ((' ' * (lr_tree._root + 1)) + node)
s_line = ((' ' * lr_tree._root) + '╱')
t_repr = (UnicodeArt([f_line, s_line]) * lr_tree)
t_repr._root = (lr_tree._root + 2)
t_repr._baseline = (t_repr._h - 1)
return t_repr
node = node_to_str(self)
lr_tree = self[0]._unicode_art_()
rr_tree = self[1]._unicode_art_()
nb_ = (((lr_tree._l - lr_tree._root) + rr_tree._root) - 1)
nb_L = (nb_ // 2)
nb_R = (nb_L + (nb_ % 2))
f_line = (((' ' * (lr_tree._root + 1)) + ('_' * nb_L)) + node)
f_line += ('_' * nb_R)
s_line = ((((' ' * lr_tree._root) + '╱') + (' ' * (((len(node) + rr_tree._root) - 1) + (lr_tree._l - lr_tree._root)))) + '╲')
t_repr = (UnicodeArt([f_line, s_line]) * ((lr_tree + UnicodeArt([(' ' * (len(node) + 2))])) + rr_tree))
t_repr._root = ((lr_tree._root + nb_L) + 2)
t_repr._baseline = (t_repr._h - 1)
return t_repr
def _sort_key(self):
'\n Return a tuple of nonnegative integers encoding the binary\n tree ``self``.\n\n The first entry of the tuple is the number of children of the\n root. Then the rest of the tuple is the concatenation of the\n tuples associated to these children (we view the children of\n a tree as trees themselves) from left to right.\n\n This tuple characterizes the tree uniquely, and can be used to\n sort the binary trees.\n\n EXAMPLES::\n\n sage: x = BinaryTree([])\n sage: y = (x.under(x)).over(x)\n sage: y._sort_key()\n (2, 2, 0, 0, 2, 0, 0)\n sage: z = (x.over(x)).under(x)\n sage: z._sort_key()\n (2, 2, 0, 2, 0, 0, 0)\n '
l = len(self)
if (l == 0):
return (0,)
resu = ([l] + [u for t in self for u in t._sort_key()])
return tuple(resu)
def is_empty(self):
'\n Return whether ``self`` is empty.\n\n The notion of emptiness employed here is the one which defines\n a binary tree to be empty if its root is a leaf. There is\n precisely one empty binary tree.\n\n EXAMPLES::\n\n sage: BinaryTree().is_empty()\n True\n sage: BinaryTree([]).is_empty()\n False\n sage: BinaryTree([[], None]).is_empty()\n False\n '
return (not self)
def graph(self, with_leaves=True):
'\n Convert ``self`` to a digraph.\n\n By default, this graph contains both nodes and leaves, hence\n is never empty. To obtain a graph which contains only the\n nodes, the ``with_leaves`` optional keyword variable has to be\n set to ``False``.\n\n The resulting digraph is endowed with a combinatorial embedding,\n in order to be displayed correctly.\n\n INPUT:\n\n - ``with_leaves`` -- (default: ``True``) a Boolean, determining\n whether the resulting graph will be formed from the leaves\n and the nodes of ``self`` (if ``True``), or only from the\n nodes of ``self`` (if ``False``)\n\n EXAMPLES::\n\n sage: t1 = BinaryTree([[], None])\n sage: t1.graph()\n Digraph on 5 vertices\n sage: t1.graph(with_leaves=False)\n Digraph on 2 vertices\n\n sage: t1 = BinaryTree([[], [[], None]])\n sage: t1.graph()\n Digraph on 9 vertices\n sage: t1.graph().edges(sort=True)\n [(0, 1, None), (0, 4, None), (1, 2, None), (1, 3, None), (4, 5, None), (4, 8, None), (5, 6, None), (5, 7, None)]\n sage: t1.graph(with_leaves=False)\n Digraph on 4 vertices\n sage: t1.graph(with_leaves=False).edges(sort=True)\n [(0, 1, None), (0, 2, None), (2, 3, None)]\n\n sage: t1 = BinaryTree()\n sage: t1.graph()\n Digraph on 1 vertex\n sage: t1.graph(with_leaves=False)\n Digraph on 0 vertices\n\n sage: BinaryTree([]).graph()\n Digraph on 3 vertices\n sage: BinaryTree([]).graph(with_leaves=False)\n Digraph on 1 vertex\n\n sage: t1 = BinaryTree([[], [[], []]])\n sage: t1.graph(with_leaves=False)\n Digraph on 5 vertices\n sage: t1.graph(with_leaves=False).edges(sort=True)\n [(0, 1, None), (0, 2, None), (2, 3, None), (2, 4, None)]\n '
from sage.graphs.digraph import DiGraph
if with_leaves:
if (not self):
res = DiGraph({0: []})
res.set_embedding({0: []})
return res
res = DiGraph()
emb = {}
def rec(tr, idx):
if (not tr):
emb[idx] = []
return
else:
nbl = ((2 * tr[0].node_number()) + 1)
res.add_edges([[idx, (idx + 1)], [idx, ((idx + 1) + nbl)]])
emb[idx] = [((idx + 1) + nbl), (idx + 1)]
rec(tr[0], (idx + 1))
rec(tr[1], ((idx + nbl) + 1))
rec(self, 0)
for i in res:
if (i != 0):
emb[i].append(res.neighbors_in(i)[0])
res.set_embedding(emb)
return res
else:
if (self.node_number() == 1):
res = DiGraph({0: []})
res.set_embedding({0: []})
return res
res = DiGraph()
emb = {}
def rec(tr, idx):
if (not tr):
return
else:
nbl = tr[0].node_number()
if (nbl > 0):
res.add_edge([idx, (idx + 1)])
emb[idx] = [(idx + 1)]
rec(tr[0], (idx + 1))
else:
emb[idx] = []
if (tr[1].node_number() > 0):
res.add_edge([idx, ((idx + nbl) + 1)])
emb[idx] = ([((idx + nbl) + 1)] + emb[idx])
rec(tr[1], ((idx + nbl) + 1))
rec(self, 0)
for i in res:
if (i != 0):
emb[i].append(res.neighbors_in(i)[0])
res.set_embedding(emb)
return res
def canonical_labelling(self, shift=1):
'\n Return a labelled version of ``self``.\n\n The canonical labelling of a binary tree is a certain labelling of the\n nodes (not the leaves) of the tree.\n The actual canonical labelling is currently unspecified. However, it\n is guaranteed to have labels in `1...n` where `n` is the number of\n nodes of the tree. Moreover, two (unlabelled) trees compare as equal if\n and only if their canonical labelled trees compare as equal.\n\n EXAMPLES::\n\n sage: BinaryTree().canonical_labelling()\n .\n sage: BinaryTree([]).canonical_labelling()\n 1[., .]\n sage: BinaryTree([[[], [[], None]], [[], []]]).canonical_labelling()\n 5[2[1[., .], 4[3[., .], .]], 7[6[., .], 8[., .]]]\n '
LTR = self.parent().labelled_trees()
if self:
sz0 = self[0].node_number()
return LTR([self[0].canonical_labelling(shift), self[1].canonical_labelling(((shift + 1) + sz0))], label=(shift + sz0))
else:
return LTR(None)
def show(self, with_leaves=False):
'\n Show the binary tree ``show``, with or without leaves depending\n on the Boolean keyword variable ``with_leaves``.\n\n .. WARNING::\n\n For a labelled binary tree, the labels shown in the\n picture are not (in general) the ones given by the\n labelling!\n\n Use :meth:`_latex_`, ``view``,\n :meth:`_ascii_art_` or ``pretty_print`` for more\n faithful representations of the data of the tree.\n\n TESTS::\n\n sage: t1 = BinaryTree([[], [[], None]])\n sage: t1.show() # needs sage.plot\n '
try:
self.graph(with_leaves=with_leaves).show(layout='tree', tree_root=0, tree_orientation='down')
except RuntimeError:
self.graph(with_leaves=with_leaves).show()
def make_node(self, child_list=[None, None]):
'\n Modify ``self`` so that it becomes a node with children ``child_list``.\n\n INPUT:\n\n - ``child_list`` -- a pair of binary trees (or objects convertible to)\n\n .. NOTE:: ``self`` must be in a mutable state.\n\n .. SEEALSO::\n\n :meth:`make_leaf <sage.combinat.binary_tree.BinaryTree.make_leaf>`\n\n EXAMPLES::\n\n sage: t = BinaryTree()\n sage: t.make_node([None, None])\n Traceback (most recent call last):\n ...\n ValueError: object is immutable; please change a copy instead.\n sage: with t.clone() as t1:\n ....: t1.make_node([None, None])\n sage: t, t1\n (., [., .])\n sage: with t.clone() as t:\n ....: t.make_node([BinaryTree(), BinaryTree(), BinaryTree([])])\n Traceback (most recent call last):\n ...\n ValueError: the list must have length 2\n sage: with t1.clone() as t2:\n ....: t2.make_node([t1, t1])\n sage: with t2.clone() as t3:\n ....: t3.make_node([t1, t2])\n sage: t1, t2, t3\n ([., .], [[., .], [., .]], [[., .], [[., .], [., .]]])\n '
self._require_mutable()
child_lst = [self.__class__(self.parent(), x) for x in child_list]
if (len(child_lst) != 2):
raise ValueError('the list must have length 2')
self.__init__(self.parent(), child_lst, check=False)
def make_leaf(self):
'\n Modify ``self`` so that it becomes a leaf (i. e., an empty tree).\n\n .. NOTE:: ``self`` must be in a mutable state.\n\n .. SEEALSO::\n\n :meth:`make_node <sage.combinat.binary_tree.BinaryTree.make_node>`\n\n EXAMPLES::\n\n sage: t = BinaryTree([None, None])\n sage: t.make_leaf()\n Traceback (most recent call last):\n ...\n ValueError: object is immutable; please change a copy instead.\n sage: with t.clone() as t1:\n ....: t1.make_leaf()\n sage: t, t1\n ([., .], .)\n '
self._require_mutable()
self.__init__(self.parent(), None)
def _to_dyck_word_rec(self, usemap='1L0R'):
'\n EXAMPLES::\n\n sage: BinaryTree()._to_dyck_word_rec()\n []\n sage: BinaryTree([])._to_dyck_word_rec()\n [1, 0]\n sage: BinaryTree([[[], [[], None]], [[], []]])._to_dyck_word_rec()\n [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0]\n sage: BinaryTree([[None,[]],None])._to_dyck_word_rec("L1R0")\n [1, 1, 0, 0, 1, 0]\n sage: BinaryTree([[[], [[], None]], [[], []]])._to_dyck_word_rec("L1R0")\n [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0]\n '
if self:
w = []
for l in usemap:
if (l == 'L'):
w += self[0]._to_dyck_word_rec(usemap)
elif (l == 'R'):
w += self[1]._to_dyck_word_rec(usemap)
elif (l == '1'):
w += [1]
elif (l == '0'):
w += [0]
return w
else:
return []
@combinatorial_map(name='to the Tamari corresponding Dyck path')
def to_dyck_word_tamari(self):
'\n Return the Dyck word associated with ``self`` in consistency with\n the Tamari order on Dyck words and binary trees.\n\n The bijection is defined recursively as follows:\n\n - a leaf is associated with an empty Dyck word;\n\n - a tree with children `l,r` is associated with the Dyck word\n `T(l) 1 T(r) 0`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: BinaryTree().to_dyck_word_tamari()\n []\n sage: BinaryTree([]).to_dyck_word_tamari()\n [1, 0]\n sage: BinaryTree([[None,[]],None]).to_dyck_word_tamari()\n [1, 1, 0, 0, 1, 0]\n sage: BinaryTree([[[], [[], None]], [[], []]]).to_dyck_word_tamari()\n [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0]\n '
return self.to_dyck_word('L1R0')
def tamari_interval(self, other):
'\n Return the Tamari interval between ``self`` and ``other`` as a\n :class:`~sage.combinat.interval_posets.TamariIntervalPoset`.\n\n A "Tamari interval" is an interval in the Tamari poset.\n See :meth:`tamari_lequal` for the definition of the Tamari poset.\n\n INPUT:\n\n - ``other`` -- a binary tree greater or equal to ``self``\n in the Tamari order\n\n EXAMPLES::\n\n sage: bt = BinaryTree([[None, [[], None]], None])\n sage: ip = bt.tamari_interval(BinaryTree([None, [[None, []], None]])); ip\n The Tamari interval of size 4 induced by relations [(2, 4), (3, 4), (3, 1), (2, 1)]\n sage: ip.lower_binary_tree()\n [[., [[., .], .]], .]\n sage: ip.upper_binary_tree()\n [., [[., [., .]], .]]\n sage: ip.interval_cardinality()\n 4\n sage: ip.number_of_tamari_inversions()\n 2\n sage: list(ip.binary_trees())\n [[., [[., [., .]], .]],\n [[., [., [., .]]], .],\n [., [[[., .], .], .]],\n [[., [[., .], .]], .]]\n sage: bt.tamari_interval(BinaryTree([[None,[]],[]]))\n Traceback (most recent call last):\n ...\n ValueError: the two binary trees are not comparable on the Tamari lattice\n\n TESTS:\n\n Setting ``other`` equal to ``bt`` gives an interval consisting of\n just one element::\n\n sage: ip = bt.tamari_interval(bt)\n sage: ip\n The Tamari interval of size 4 induced by relations [(1, 4), (2, 3), (3, 4), (3, 1), (2, 1)]\n sage: list(ip.binary_trees())\n [[[., [[., .], .]], .]]\n\n Empty trees work well::\n\n sage: bt = BinaryTree()\n sage: ip = bt.tamari_interval(bt)\n sage: ip\n The Tamari interval of size 0 induced by relations []\n sage: list(ip.binary_trees())\n [.]\n '
from sage.combinat.interval_posets import TamariIntervalPosets
return TamariIntervalPosets.from_binary_trees(self, other)
def tamari_join(self, other):
'\n Return the join of the binary trees ``self`` and ``other``\n (of equal size) in the `n`-th Tamari poset (where `n` is\n the size of these trees).\n\n The `n`-th Tamari poset (defined in :meth:`tamari_lequal`)\n is known to be a lattice, and the map from the `n`-th\n symmetric group `S_n` to the `n`-th Tamari poset defined\n by sending every permutation `p \\in S_n` to the binary\n search tree of `p` (more precisely, to\n ``p.binary_search_tree_shape()``) is a lattice\n homomorphism. (See Theorem 6.2 in [Rea2004]_.)\n\n .. SEEALSO::\n\n :meth:`tamari_lequal`, :meth:`tamari_meet`.\n\n AUTHORS:\n\n Viviane Pons and Darij Grinberg, 18 June 2014;\n Frédéric Chapoton, 9 January 2018.\n\n EXAMPLES::\n\n sage: a = BinaryTree([None, [None, []]])\n sage: b = BinaryTree([None, [[], None]])\n sage: c = BinaryTree([[None, []], None])\n sage: d = BinaryTree([[[], None], None])\n sage: e = BinaryTree([[], []])\n sage: a.tamari_join(c) == a\n True\n sage: b.tamari_join(c) == b\n True\n sage: c.tamari_join(e) == a\n True\n sage: d.tamari_join(e) == e\n True\n sage: e.tamari_join(b) == a\n True\n sage: e.tamari_join(a) == a\n True\n\n ::\n\n sage: b1 = BinaryTree([None, [[[], None], None]])\n sage: b2 = BinaryTree([[[], None], []])\n sage: b1.tamari_join(b2)\n [., [[., .], [., .]]]\n sage: b3 = BinaryTree([[], [[], None]])\n sage: b1.tamari_join(b3)\n [., [., [[., .], .]]]\n sage: b2.tamari_join(b3)\n [[., .], [., [., .]]]\n\n The universal property of the meet operation is\n satisfied::\n\n sage: def test_uni_join(p, q):\n ....: j = p.tamari_join(q)\n ....: if not p.tamari_lequal(j):\n ....: return False\n ....: if not q.tamari_lequal(j):\n ....: return False\n ....: for r in p.tamari_greater():\n ....: if q.tamari_lequal(r) and not j.tamari_lequal(r):\n ....: return False\n ....: return True\n sage: all( test_uni_join(p, q) for p in BinaryTrees(3) for q in BinaryTrees(3) )\n True\n sage: p = BinaryTrees(6).random_element() # needs sage.combinat\n sage: q = BinaryTrees(6).random_element() # needs sage.combinat\n sage: test_uni_join(p, q) # needs sage.combinat\n True\n\n Border cases::\n\n sage: b = BinaryTree(None)\n sage: b.tamari_join(b)\n .\n sage: b = BinaryTree([])\n sage: b.tamari_join(b)\n [., .]\n '
a = self.to_132_avoiding_permutation()
b = other.to_132_avoiding_permutation()
return a.permutohedron_join(b).binary_search_tree_shape(left_to_right=False)
def tamari_meet(self, other, side='right'):
'\n Return the meet of the binary trees ``self`` and ``other``\n (of equal size) in the `n`-th Tamari poset (where `n` is\n the size of these trees).\n\n The `n`-th Tamari poset (defined in :meth:`tamari_lequal`)\n is known to be a lattice, and the map from the `n`-th\n symmetric group `S_n` to the `n`-th Tamari poset defined\n by sending every permutation `p \\in S_n` to the binary\n search tree of `p` (more precisely, to\n ``p.binary_search_tree_shape()``) is a lattice\n homomorphism. (See Theorem 6.2 in [Rea2004]_.)\n\n .. SEEALSO::\n\n :meth:`tamari_lequal`, :meth:`tamari_join`.\n\n AUTHORS:\n\n Viviane Pons and Darij Grinberg, 18 June 2014.\n\n EXAMPLES::\n\n sage: a = BinaryTree([None, [None, []]])\n sage: b = BinaryTree([None, [[], None]])\n sage: c = BinaryTree([[None, []], None])\n sage: d = BinaryTree([[[], None], None])\n sage: e = BinaryTree([[], []])\n sage: a.tamari_meet(c) == c\n True\n sage: b.tamari_meet(c) == c\n True\n sage: c.tamari_meet(e) == d\n True\n sage: d.tamari_meet(e) == d\n True\n sage: e.tamari_meet(b) == d\n True\n sage: e.tamari_meet(a) == e\n True\n\n ::\n\n sage: b1 = BinaryTree([None, [[[], None], None]])\n sage: b2 = BinaryTree([[[], None], []])\n sage: b1.tamari_meet(b2)\n [[[[., .], .], .], .]\n sage: b3 = BinaryTree([[], [[], None]])\n sage: b1.tamari_meet(b3)\n [[[[., .], .], .], .]\n sage: b2.tamari_meet(b3)\n [[[[., .], .], .], .]\n\n The universal property of the meet operation is\n satisfied::\n\n sage: def test_uni_meet(p, q):\n ....: m = p.tamari_meet(q)\n ....: if not m.tamari_lequal(p):\n ....: return False\n ....: if not m.tamari_lequal(q):\n ....: return False\n ....: for r in p.tamari_smaller():\n ....: if r.tamari_lequal(q) and not r.tamari_lequal(m):\n ....: return False\n ....: return True\n sage: all( test_uni_meet(p, q) for p in BinaryTrees(3) for q in BinaryTrees(3) )\n True\n sage: p = BinaryTrees(6).random_element() # needs sage.combinat\n sage: q = BinaryTrees(6).random_element() # needs sage.combinat\n sage: test_uni_meet(p, q) # needs sage.combinat\n True\n\n Border cases::\n\n sage: b = BinaryTree(None)\n sage: b.tamari_meet(b)\n .\n sage: b = BinaryTree([])\n sage: b.tamari_meet(b)\n [., .]\n '
x = self.tamari_sorting_tuple()[0]
y = other.tamari_sorting_tuple()[0]
meet = tuple((min(a, b) for (a, b) in zip(x, y)))
return from_tamari_sorting_tuple(meet)
@combinatorial_map(name='to Dyck paths: up step, left tree, down step, right tree')
def to_dyck_word(self, usemap='1L0R'):
'\n Return the Dyck word associated with ``self`` using the given map.\n\n INPUT:\n\n - ``usemap`` -- a string, either ``1L0R``, ``1R0L``, ``L1R0``, ``R1L0``\n\n The bijection is defined recursively as follows:\n\n - a leaf is associated to the empty Dyck Word\n\n - a tree with children `l,r` is associated with the Dyck word\n described by ``usemap`` where `L` and `R` are respectively the\n Dyck words associated with the trees `l` and `r`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: BinaryTree().to_dyck_word()\n []\n sage: BinaryTree([]).to_dyck_word()\n [1, 0]\n sage: BinaryTree([[[], [[], None]], [[], []]]).to_dyck_word()\n [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0]\n sage: BinaryTree([[None,[]],None]).to_dyck_word()\n [1, 1, 0, 1, 0, 0]\n sage: BinaryTree([[None,[]],None]).to_dyck_word("1R0L")\n [1, 0, 1, 1, 0, 0]\n sage: BinaryTree([[None,[]],None]).to_dyck_word("L1R0")\n [1, 1, 0, 0, 1, 0]\n sage: BinaryTree([[None,[]],None]).to_dyck_word("R1L0")\n [1, 1, 0, 1, 0, 0]\n sage: BinaryTree([[None,[]],None]).to_dyck_word("R10L")\n Traceback (most recent call last):\n ...\n ValueError: R10L is not a correct map\n\n TESTS::\n\n sage: # needs sage.combinat\n sage: bt = BinaryTree([[[], [[], None]], [[], []]])\n sage: bt == bt.to_dyck_word().to_binary_tree()\n True\n sage: bt == bt.to_dyck_word("1R0L").to_binary_tree("1R0L")\n True\n sage: bt == bt.to_dyck_word("L1R0").to_binary_tree("L1R0")\n True\n sage: bt == bt.to_dyck_word("R1L0").to_binary_tree("R1L0")\n True\n '
from sage.combinat.dyck_word import DyckWord
if (usemap not in ['1L0R', '1R0L', 'L1R0', 'R1L0']):
raise ValueError(('%s is not a correct map' % usemap))
return DyckWord(self._to_dyck_word_rec(usemap))
def _to_ordered_tree(self, bijection='left', root=None):
'\n Internal recursive method to obtain an ordered tree from a binary\n tree.\n\n EXAMPLES::\n\n sage: bt = BinaryTree([[],[]])\n sage: bt._to_ordered_tree()\n [[], [[]]]\n sage: bt._to_ordered_tree(bijection="right")\n [[[]], []]\n sage: bt._to_ordered_tree(bijection="none")\n Traceback (most recent call last):\n ...\n ValueError: the bijection argument should be either left or right\n sage: bt = BinaryTree([[[], [[], None]], [[], []]])\n sage: bt._to_ordered_tree()\n [[], [[], []], [[], [[]]]]\n sage: bt._to_ordered_tree(bijection="right")\n [[[[]], [[]]], [[]], []]\n '
close_root = False
if (root is None):
from sage.combinat.ordered_tree import OrderedTree
root = OrderedTree().clone()
close_root = True
if self:
(left, right) = (self[0], self[1])
if (bijection == 'left'):
root = left._to_ordered_tree(bijection=bijection, root=root)
root.append(right._to_ordered_tree(bijection=bijection, root=None))
elif (bijection == 'right'):
root.append(left._to_ordered_tree(bijection=bijection, root=None))
root = right._to_ordered_tree(bijection=bijection, root=root)
else:
raise ValueError('the bijection argument should be either left or right')
if close_root:
root.set_immutable()
return root
@combinatorial_map(name='To ordered tree, left child = left brother')
def to_ordered_tree_left_branch(self):
'\n Return an ordered tree of size `n+1` by the following recursive rule:\n\n - if `x` is the left child of `y`, `x` becomes the left brother\n of `y`\n - if `x` is the right child of `y`, `x` becomes the last child\n of `y`\n\n EXAMPLES::\n\n sage: bt = BinaryTree([[],[]])\n sage: bt.to_ordered_tree_left_branch()\n [[], [[]]]\n sage: bt = BinaryTree([[[], [[], None]], [[], []]])\n sage: bt.to_ordered_tree_left_branch()\n [[], [[], []], [[], [[]]]]\n '
return self._to_ordered_tree()
@combinatorial_map(name='To ordered tree, right child = right brother')
def to_ordered_tree_right_branch(self):
'\n Return an ordered tree of size `n+1` by the following recursive rule:\n\n - if `x` is the right child of `y`, `x` becomes the right brother\n of `y`\n - if `x` is the left child of `y`, `x` becomes the first child\n of `y`\n\n EXAMPLES::\n\n sage: bt = BinaryTree([[],[]])\n sage: bt.to_ordered_tree_right_branch()\n [[[]], []]\n sage: bt = BinaryTree([[[], [[], None]], [[], []]])\n sage: bt.to_ordered_tree_right_branch()\n [[[[]], [[]]], [[]], []]\n '
return self._to_ordered_tree(bijection='right')
def _postfix_word(self, left_first=True, start=1):
'\n Internal recursive method to obtain a postfix canonical read of the\n binary tree.\n\n EXAMPLES::\n\n sage: bt = BinaryTree([[],[]])\n sage: bt._postfix_word()\n [1, 3, 2]\n sage: bt._postfix_word(left_first=False)\n [3, 1, 2]\n sage: bt = BinaryTree([[[], [[], None]], [[], []]])\n sage: bt._postfix_word()\n [1, 3, 4, 2, 6, 8, 7, 5]\n sage: bt._postfix_word(left_first=False)\n [8, 6, 7, 3, 4, 1, 2, 5]\n '
if (not self):
return []
left = self[0]._postfix_word(left_first, start)
label = (start + self[0].node_number())
right = self[1]._postfix_word(left_first, start=(label + 1))
if left_first:
left.extend(right)
left.append(label)
return left
else:
right.extend(left)
right.append(label)
return right
def tamari_sorting_tuple(self, reverse=False):
'\n Return the Tamari sorting tuple of ``self`` and the\n size of ``self``.\n\n This is a pair `(w, n)`, where `n` is the number of\n nodes of ``self``, and `w` is an `n`-tuple whose\n `i`-th entry is the number of all nodes among the\n descendants of the right child of the `i`-th node\n of ``self``. Here, the nodes of ``self`` are numbered\n from left to right.\n\n INPUT:\n\n - ``reverse`` -- boolean (default ``False``) if ``True``,\n return instead the result for the left-right symmetric of the\n binary tree\n\n OUTPUT:\n\n a pair `(w, n)`, where `w` is a tuple of integers,\n and `n` the size\n\n Two binary trees of the same size are comparable in\n the Tamari order if and only if the associated tuples\n `w` are componentwise comparable.\n (This is essentially the Theorem in [HT1972]_.)\n This is used in :meth:`tamari_lequal`.\n\n EXAMPLES::\n\n sage: [t.tamari_sorting_tuple() for t in BinaryTrees(3)]\n [((2, 1, 0), 3),\n ((2, 0, 0), 3),\n ((0, 1, 0), 3),\n ((1, 0, 0), 3),\n ((0, 0, 0), 3)]\n\n sage: t = BinaryTrees(10).random_element() # needs sage.combinat\n sage: u = t.left_right_symmetry() # needs sage.combinat\n sage: t.tamari_sorting_tuple(True) == u.tamari_sorting_tuple() # needs sage.combinat\n True\n\n REFERENCES:\n\n - [HT1972]_\n '
if (not self):
return (tuple(), 0)
if (not reverse):
(t1, t2) = self
else:
(t2, t1) = self
(u1, n1) = t1.tamari_sorting_tuple(reverse=reverse)
(u2, n2) = t2.tamari_sorting_tuple(reverse=reverse)
return (((u1 + (n2,)) + u2), ((n1 + 1) + n2))
@combinatorial_map(name='To 312 avoiding permutation')
def to_312_avoiding_permutation(self):
'\n Return a 312-avoiding permutation corresponding to the binary tree.\n\n The linear extensions of a binary tree form an interval of the weak\n order called the sylvester class of the tree. This permutation is\n the minimal element of this sylvester class.\n\n EXAMPLES::\n\n sage: bt = BinaryTree([[],[]])\n sage: bt.to_312_avoiding_permutation()\n [1, 3, 2]\n sage: bt = BinaryTree([[[], [[], None]], [[], []]])\n sage: bt.to_312_avoiding_permutation()\n [1, 3, 4, 2, 6, 8, 7, 5]\n\n TESTS::\n\n sage: bt = BinaryTree([[],[]])\n sage: bt == bt.to_312_avoiding_permutation().binary_search_tree_shape(left_to_right=False)\n True\n sage: bt = BinaryTree([[[], [[], None]], [[], []]])\n sage: bt == bt.to_312_avoiding_permutation().binary_search_tree_shape(left_to_right=False)\n True\n '
from sage.combinat.permutation import Permutation
return Permutation(self._postfix_word())
@combinatorial_map(name='To complete tree')
def as_ordered_tree(self, with_leaves=True):
'\n Return the same tree seen as an ordered tree. By default, leaves\n are transformed into actual nodes, but this can be avoided by\n setting the optional variable ``with_leaves`` to ``False``.\n\n EXAMPLES::\n\n sage: bt = BinaryTree([]); bt\n [., .]\n sage: bt.as_ordered_tree()\n [[], []]\n sage: bt.as_ordered_tree(with_leaves = False)\n []\n sage: bt = bt.canonical_labelling(); bt\n 1[., .]\n sage: bt.as_ordered_tree()\n 1[None[], None[]]\n sage: bt.as_ordered_tree(with_leaves=False)\n 1[]\n '
if with_leaves:
children = [child.as_ordered_tree(with_leaves) for child in self]
else:
if (not self):
raise ValueError('the empty binary tree cannot be made into an ordered tree with with_leaves = False')
children = [child.as_ordered_tree(with_leaves) for child in self if (not child.is_empty())]
if (self in LabelledBinaryTrees()):
from sage.combinat.ordered_tree import LabelledOrderedTree
return LabelledOrderedTree(children, label=self.label())
else:
from sage.combinat.ordered_tree import OrderedTree
return OrderedTree(children)
@combinatorial_map(name='To graph')
def to_undirected_graph(self, with_leaves=False):
'\n Return the undirected graph obtained from the tree nodes and edges.\n\n Leaves are ignored by default, but one can set ``with_leaves`` to\n ``True`` to obtain the graph of the complete tree.\n\n INPUT:\n\n - ``with_leaves`` -- (default: ``False``) a Boolean, determining\n whether the resulting graph will be formed from the leaves\n and the nodes of ``self`` (if ``True``), or only from the\n nodes of ``self`` (if ``False``)\n\n EXAMPLES::\n\n sage: bt = BinaryTree([])\n sage: bt.to_undirected_graph()\n Graph on 1 vertex\n sage: bt.to_undirected_graph(with_leaves=True)\n Graph on 3 vertices\n\n sage: bt = BinaryTree()\n sage: bt.to_undirected_graph()\n Graph on 0 vertices\n sage: bt.to_undirected_graph(with_leaves=True)\n Graph on 1 vertex\n\n If the tree is labelled, we use its labelling to label the graph.\n Otherwise, we use the graph canonical labelling which means that\n two different trees can have the same graph.\n\n EXAMPLES::\n\n sage: bt = BinaryTree([[],[None,[]]])\n sage: bt.canonical_labelling().to_undirected_graph() == bt.to_undirected_graph()\n False\n sage: BinaryTree([[],[]]).to_undirected_graph() == BinaryTree([[[],None],None]).to_undirected_graph()\n True\n '
if ((not with_leaves) and (not self)):
from sage.graphs.graph import Graph
return Graph([])
return self.as_ordered_tree(with_leaves).to_undirected_graph()
def to_tilting(self):
"\n Transform a binary tree into a tilting object.\n\n Let `t` be a binary tree with `n` nodes. There exists a unique\n depiction of `t` (above the diagonal) such that all leaves are\n regularly distributed on the diagonal line from `(0,0)` to\n `(n,n)` and all edges are either horizontal or vertical. This\n method provides the coordinates of this depiction, with the\n root as the top-left vertex.\n\n OUTPUT:\n\n a list of pairs of integers.\n\n Every vertex of the binary tree is mapped to a pair of\n integers. The conventions are the following. The root has\n coordinates `(0, n)` where `n` is the node number.\n If a vertex is the left (right) son of\n another vertex, they share the first (second) coordinate.\n\n EXAMPLES::\n\n sage: t = BinaryTrees(1)[0]\n sage: t.to_tilting()\n [(0, 1)]\n\n sage: for t in BinaryTrees(2):\n ....: print(t.to_tilting())\n [(1, 2), (0, 2)]\n [(0, 1), (0, 2)]\n\n sage: from sage.combinat.abstract_tree import from_hexacode\n sage: t = from_hexacode('2020222002000', BinaryTrees())\n sage: print(t.to_tilting())\n [(0, 1), (2, 3), (4, 5), (6, 7), (4, 7), (8, 9), (10, 11),\n (8, 11), (4, 11), (12, 13), (4, 13), (2, 13), (0, 13)]\n\n sage: w = DyckWord([1,1,1,1,0,1,1,0,0,0,1,1,0,1,0,1,1,0,1,1,0,0,0,0,0,0]) # needs sage.combinat\n sage: t2 = w.to_binary_tree() # needs sage.combinat\n sage: len(t2.to_tilting()) == t2.node_number() # needs sage.combinat\n True\n "
if (not self):
return []
return self._to_tilting_rec()[0]
def _to_tilting_rec(self, shift=0):
'\n Auxiliary method for :meth:`to_tilting`.\n\n INPUT:\n\n ``shift`` -- an integer (default 0)\n\n OUTPUT:\n\n list of tilting coordinates and number of leaves\n\n EXAMPLES::\n\n sage: all(t._to_tilting_rec()[1] == 4 for t in BinaryTrees(3))\n True\n '
(u, v) = self
if u:
(resu, N_u) = u._to_tilting_rec(shift=shift)
else:
resu = []
N_u = 1
if v:
(tilt_v, N_v) = v._to_tilting_rec(shift=(shift + N_u))
resu.extend(tilt_v)
else:
N_v = 1
N = (N_u + N_v)
resu.append((shift, ((shift + N) - 1)))
return (resu, N)
@combinatorial_map(name='To poset')
def to_poset(self, with_leaves=False, root_to_leaf=False):
'\n Return the poset obtained by interpreting the tree as a Hasse\n diagram.\n\n The default orientation is from leaves to root but you can\n pass ``root_to_leaf=True`` to obtain the inverse orientation.\n\n Leaves are ignored by default, but one can set ``with_leaves`` to\n ``True`` to obtain the poset of the complete tree.\n\n INPUT:\n\n - ``with_leaves`` -- (default: ``False``) a Boolean, determining\n whether the resulting poset will be formed from the leaves\n and the nodes of ``self`` (if ``True``), or only from the\n nodes of ``self`` (if ``False``)\n - ``root_to_leaf`` -- (default: ``False``) a Boolean,\n determining whether the poset orientation should be from root\n to leaves (if ``True``) or from leaves to root (if ``False``).\n\n EXAMPLES::\n\n sage: bt = BinaryTree([])\n sage: bt.to_poset()\n Finite poset containing 1 elements\n sage: bt.to_poset(with_leaves=True)\n Finite poset containing 3 elements\n sage: P1 = bt.to_poset(with_leaves=True)\n sage: len(P1.maximal_elements())\n 1\n sage: len(P1.minimal_elements())\n 2\n sage: bt = BinaryTree([])\n sage: P2 = bt.to_poset(with_leaves=True,root_to_leaf=True)\n sage: len(P2.maximal_elements())\n 2\n sage: len(P2.minimal_elements())\n 1\n\n If the tree is labelled, we use its labelling to label the poset.\n Otherwise, we use the poset canonical labelling::\n\n sage: bt = BinaryTree([[],[None,[]]]).canonical_labelling()\n sage: bt\n 2[1[., .], 3[., 4[., .]]]\n sage: bt.to_poset().cover_relations()\n [[4, 3], [3, 2], [1, 2]]\n\n Let us check that the empty binary tree is correctly handled::\n\n sage: bt = BinaryTree()\n sage: bt.to_poset()\n Finite poset containing 0 elements\n sage: bt.to_poset(with_leaves=True)\n Finite poset containing 1 elements\n '
if ((not with_leaves) and (not self)):
from sage.combinat.posets.posets import Poset
return Poset({})
return self.as_ordered_tree(with_leaves).to_poset(root_to_leaf)
@combinatorial_map(name='To 132 avoiding permutation')
def to_132_avoiding_permutation(self):
'\n Return a 132-avoiding permutation corresponding to the binary tree.\n\n The linear extensions of a binary tree form an interval of the weak\n order called the sylvester class of the tree. This permutation is\n the maximal element of this sylvester class.\n\n EXAMPLES::\n\n sage: bt = BinaryTree([[],[]])\n sage: bt.to_132_avoiding_permutation()\n [3, 1, 2]\n sage: bt = BinaryTree([[[], [[], None]], [[], []]])\n sage: bt.to_132_avoiding_permutation()\n [8, 6, 7, 3, 4, 1, 2, 5]\n\n TESTS::\n\n sage: bt = BinaryTree([[],[]])\n sage: bt == bt.to_132_avoiding_permutation().binary_search_tree_shape(left_to_right=False)\n True\n sage: bt = BinaryTree([[[], [[], None]], [[], []]])\n sage: bt == bt.to_132_avoiding_permutation().binary_search_tree_shape(left_to_right=False)\n True\n '
from sage.combinat.permutation import Permutation
return Permutation(self._postfix_word(left_first=False))
def left_children_node_number(self, direction='left'):
"\n Return the number of nodes which are left children in ``self``.\n\n Every node (except the root) is either the left child or the\n right child of its parent node. The total number of nodes\n is `1` plus the number of left-children nodes plus the number of\n right-children nodes.\n\n INPUT:\n\n - ``direction`` -- either ``'left'`` (default) or ``'right'`` ; if\n set to ``'right'``, instead count nodes that are right children\n\n EXAMPLES::\n\n sage: bt = BinaryTree([[None,[[],[]]],[None,[[],None]]])\n sage: ascii_art(bt)\n __o__\n / \\\n o o\n \\ \\\n o o\n / \\ /\n o o o\n sage: bt.left_children_node_number('left')\n 3\n sage: bt.left_children_node_number('right')\n 4\n\n sage: all(5 == 1 + bt.left_children_node_number()\n ....: + bt.left_children_node_number('right')\n ....: for bt in BinaryTrees(5))\n True\n\n TESTS::\n\n sage: BinaryTree([[],None]).left_children_node_number()\n 1\n sage: BinaryTree([None,[]]).left_children_node_number()\n 0\n sage: BinaryTree([]).left_children_node_number()\n 0\n sage: BinaryTree().left_children_node_number()\n 0\n\n sage: BinaryTree([[],None]).left_children_node_number('right')\n 0\n sage: BinaryTree([None,[]]).left_children_node_number('right')\n 1\n sage: BinaryTree([]).left_children_node_number('right')\n 0\n sage: BinaryTree().left_children_node_number('right')\n 0\n "
if self.is_empty():
return 0
res = 0
if self[0]:
if (direction == 'left'):
res += 1
res += self[0].left_children_node_number(direction)
if self[1]:
if (direction == 'right'):
res += 1
res += self[1].left_children_node_number(direction)
return res
@combinatorial_map(order=2, name='Left-right symmetry')
def left_right_symmetry(self):
'\n Return the left-right symmetrized tree of ``self``.\n\n EXAMPLES::\n\n sage: BinaryTree().left_right_symmetry()\n .\n sage: BinaryTree([]).left_right_symmetry()\n [., .]\n sage: BinaryTree([[],None]).left_right_symmetry()\n [., [., .]]\n sage: BinaryTree([[None, []],None]).left_right_symmetry()\n [., [[., .], .]]\n '
if (not self):
return BinaryTree()
if (self not in LabelledBinaryTrees()):
a = self.tamari_sorting_tuple(reverse=True)[0]
return from_tamari_sorting_tuple(a)
tree = [self[1].left_right_symmetry(), self[0].left_right_symmetry()]
return LabelledBinaryTree(tree, label=self.label())
@combinatorial_map(order=2, name='Left border symmetry')
def left_border_symmetry(self):
"\n Return the tree where a symmetry has been applied recursively on\n all left borders. If a tree is made of three trees `[T_1, T_2,\n T_3]` on its left border, it becomes `[T_3', T_2', T_1']` where\n same symmetry has been applied to `T_1, T_2, T_3`.\n\n EXAMPLES::\n\n sage: BinaryTree().left_border_symmetry()\n .\n sage: BinaryTree([]).left_border_symmetry()\n [., .]\n sage: BinaryTree([[None,[]],None]).left_border_symmetry()\n [[., .], [., .]]\n sage: BinaryTree([[None,[None,[]]],None]).left_border_symmetry()\n [[., .], [., [., .]]]\n sage: bt = BinaryTree([[None,[None,[]]],None]).canonical_labelling()\n sage: bt\n 4[1[., 2[., 3[., .]]], .]\n sage: bt.left_border_symmetry()\n 1[4[., .], 2[., 3[., .]]]\n "
if (not self):
return BinaryTree()
border = []
labelled = (self in LabelledBinaryTrees())
labels = []
t = self
while t:
border.append(t[1].left_border_symmetry())
if labelled:
labels.append(t.label())
t = t[0]
tree = BinaryTree()
for r in border:
if labelled:
tree = LabelledBinaryTree([tree, r], label=labels.pop(0))
else:
tree = BinaryTree([tree, r])
return tree
def canopee(self):
'\n Return the canopee of ``self``.\n\n The *canopee* of a non-empty binary tree `T` with `n` internal nodes is\n the list `l` of `0` and `1` of length `n-1` obtained by going along the\n leaves of `T` from left to right except the two extremal ones, writing\n `0` if the leaf is a right leaf and `1` if the leaf is a left leaf.\n\n EXAMPLES::\n\n sage: BinaryTree([]).canopee()\n []\n sage: BinaryTree([None, []]).canopee()\n [1]\n sage: BinaryTree([[], None]).canopee()\n [0]\n sage: BinaryTree([[], []]).canopee()\n [0, 1]\n sage: BinaryTree([[[], [[], None]], [[], []]]).canopee()\n [0, 1, 0, 0, 1, 0, 1]\n\n The number of pairs `(t_1, t_2)` of binary trees of size `n` such that\n the canopee of `t_1` is the complementary of the canopee of `t_2` is\n also the number of Baxter permutations (see [DG1994]_, see\n also :oeis:`A001181`). We check this in small cases::\n\n sage: [len([(u,v) for u in BinaryTrees(n) for v in BinaryTrees(n)\n ....: if [1 - x for x in u.canopee()] == v.canopee()])\n ....: for n in range(1, 5)]\n [1, 2, 6, 22]\n\n Here is a less trivial implementation of this::\n\n sage: from sage.sets.finite_set_map_cy import fibers\n sage: def baxter(n):\n ....: f = fibers(lambda t: tuple(t.canopee()),\n ....: BinaryTrees(n))\n ....: return sum(len(f[i])*len(f[tuple(1-x for x in i)])\n ....: for i in f)\n sage: [baxter(n) for n in range(1, 7)]\n [1, 2, 6, 22, 92, 422]\n\n TESTS::\n\n sage: t = BinaryTree().canopee()\n Traceback (most recent call last):\n ...\n ValueError: canopee is only defined for non empty binary trees\n '
if (not self):
raise ValueError('canopee is only defined for non empty binary trees')
res = []
def add_leaf_rec(tr):
for i in range(2):
if tr[i]:
add_leaf_rec(tr[i])
else:
res.append((1 - i))
add_leaf_rec(self)
return res[1:(- 1)]
def in_order_traversal_iter(self):
'\n The depth-first infix-order traversal iterator for the binary\n tree ``self``.\n\n This method iters each vertex (node and leaf alike) of the given\n binary tree following the depth-first infix order traversal\n algorithm.\n\n The *depth-first infix order traversal algorithm* iterates\n through a binary tree as follows::\n\n iterate through the left subtree (by the depth-first infix\n order traversal algorithm);\n yield the root;\n iterate through the right subtree (by the depth-first infix\n order traversal algorithm).\n\n For example on the following binary tree `T`, where we denote\n leaves by `a, b, c, \\ldots` and nodes by `1, 2, 3, \\ldots`::\n\n | ____3____ |\n | / \\ |\n | 1 __7__ |\n | / \\ / \\ |\n | a 2 _5_ 8 |\n | / \\ / \\ / \\ |\n | b c 4 6 h i |\n | / \\ / \\ |\n | d e f g |\n\n the depth-first infix-order traversal algorithm iterates through\n the vertices of `T` in the following order:\n `a,1,b,2,c,3,d,4,e,5,f,6,g,7,h,8,i`.\n\n See :meth:`in_order_traversal` for a version of this algorithm\n which not only iterates through, but actually does something at\n the vertices of tree.\n\n TESTS::\n\n sage: b = BinaryTree([[],[[],[]]]); ascii_art([b])\n [ _o_ ]\n [ / \\ ]\n [ o o ]\n [ / \\ ]\n [ o o ]\n sage: ascii_art(list(b.in_order_traversal_iter()))\n [ , o, , _o_ , , o, , o , , o, ]\n [ / \\ / \\ ]\n [ o o o o ]\n [ / \\ ]\n [ o o ]\n sage: ascii_art([node for node in\n ....: b.canonical_labelling().in_order_traversal_iter()\n ....: if node.label() is not None])\n [ 1, _2_ , 3, 4 , 5 ]\n [ / \\ / \\ ]\n [ 1 4 3 5 ]\n [ / \\ ]\n [ 3 5 ]\n\n sage: list(BinaryTree(None).in_order_traversal_iter())\n [.]\n '
if self.is_empty():
(yield self)
return
(yield from self[0].in_order_traversal_iter())
(yield self)
(yield from self[1].in_order_traversal_iter())
def in_order_traversal(self, node_action=None, leaf_action=None):
"\n Explore the binary tree ``self`` using the depth-first infix-order\n traversal algorithm, executing the ``node_action`` function\n whenever traversing a node and executing the ``leaf_action``\n function whenever traversing a leaf.\n\n In more detail, what this method does to a tree `T` is the\n following::\n\n if the root of `T` is a node:\n apply in_order_traversal to the left subtree of `T`\n (with the same node_action and leaf_action);\n apply node_action to the root of `T`;\n apply in_order_traversal to the right subtree of `T`\n (with the same node_action and leaf_action);\n else:\n apply leaf_action to the root of `T`.\n\n For example on the following binary tree `T`, where we denote\n leaves by `a, b, c, \\ldots` and nodes by `1, 2, 3, \\ldots`::\n\n | ____3____ |\n | / \\ |\n | 1 __7__ |\n | / \\ / \\ |\n | a 2 _5_ 8 |\n | / \\ / \\ / \\ |\n | b c 4 6 h i |\n | / \\ / \\ |\n | d e f g |\n\n this method first applies ``leaf_action`` to `a`, then applies\n ``node_action`` to `1`, then ``leaf_action`` to `b`, then\n ``node_action`` to `2`, etc., with the vertices being traversed\n in the order `a,1,b,2,c,3,d,4,e,5,f,6,g,7,h,8,i`.\n\n See :meth:`in_order_traversal_iter` for a version of this\n algorithm which only iterates through the vertices rather than\n applying any function to them.\n\n INPUT:\n\n - ``node_action`` -- (optional) a function which takes a node in input\n and does something during the exploration\n - ``leaf_action`` -- (optional) a function which takes a leaf in input\n and does something during the exploration\n\n TESTS::\n\n sage: nb_leaf = 0\n sage: def l_action(_):\n ....: global nb_leaf\n ....: nb_leaf += 1\n sage: nb_node = 0\n sage: def n_action(_):\n ....: global nb_node\n ....: nb_node += 1\n\n sage: BinaryTree().in_order_traversal(n_action, l_action)\n sage: nb_leaf, nb_node\n (1, 0)\n\n sage: nb_leaf, nb_node = 0, 0\n sage: b = BinaryTree([[],[[],[]]]); b\n [[., .], [[., .], [., .]]]\n sage: b.in_order_traversal(n_action, l_action)\n sage: nb_leaf, nb_node\n (6, 5)\n sage: nb_leaf, nb_node = 0, 0\n sage: b = b.canonical_labelling()\n sage: b.in_order_traversal(n_action, l_action)\n sage: nb_leaf, nb_node\n (6, 5)\n sage: l = []\n sage: b.in_order_traversal(lambda node: l.append( node.label() ))\n sage: l\n [1, 2, 3, 4, 5]\n\n sage: leaf = 'a'\n sage: l = []\n sage: def l_action(_):\n ....: global leaf, l\n ....: l.append(leaf)\n ....: leaf = chr( ord(leaf)+1 )\n sage: n_action = lambda node: l.append( node.label() )\n sage: b = BinaryTree([[None,[]],[[[],[]],[]]])\n sage: b = b.canonical_labelling()\n sage: b.in_order_traversal(n_action, l_action)\n sage: l\n ['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5, 'f', 6, 'g', 7, 'h', 8,\n 'i']\n "
if (leaf_action is None):
def leaf_action(x):
return None
if (node_action is None):
def node_action(x):
return None
for node in self.in_order_traversal_iter():
if node.is_empty():
leaf_action(node)
else:
node_action(node)
def tamari_lequal(self, t2):
'\n Return ``True`` if ``self`` is less or equal to another binary\n tree ``t2`` (of the same size as ``self``) in the Tamari order.\n\n The Tamari order on binary trees of size `n` is the partial order\n on the set of all binary trees of size `n` generated by the\n following requirement: If a binary tree `T\'` is obtained by\n right rotation (see :meth:`right_rotate`) from a binary tree `T`,\n then `T < T\'`.\n This not only is a well-defined partial order, but actually is\n a lattice structure on the set of binary trees of size `n`, and\n is a quotient of the weak order on the `n`-th symmetric group\n (also known as the right permutohedron order, see\n :meth:`~sage.combinat.permutation.Permutation.permutohedron_lequal`).\n See [CP2012]_. The set of binary trees of size `n` equipped with\n the Tamari order is called the `n`-th Tamari poset.\n\n The Tamari order can equivalently be defined as follows:\n\n If `T` and `S` are two binary trees of size `n`, then the\n following four statements are equivalent:\n\n - We have `T \\leq S` in the Tamari order.\n\n - There exist elements `t` and `s` of the Sylvester classes\n (:meth:`sylvester_class`) of `T` and `S`, respectively,\n such that `t \\leq s` in the weak order on the symmetric\n group.\n\n - The 132-avoiding permutation corresponding to `T` (see\n :meth:`to_132_avoiding_permutation`) is `\\leq` to the\n 132-avoiding permutation corresponding to `S` in the weak\n order on the symmetric group.\n\n - The 312-avoiding permutation corresponding to `T` (see\n :meth:`to_312_avoiding_permutation`) is `\\leq` to the\n 312-avoiding permutation corresponding to `S` in the weak\n order on the symmetric group.\n\n .. SEEALSO::\n\n :meth:`tamari_smaller`, :meth:`tamari_greater`,\n :meth:`tamari_pred`, :meth:`tamari_succ`,\n :meth:`tamari_interval`\n\n EXAMPLES:\n\n This tree::\n\n | o |\n | / \\ |\n | o o |\n | / |\n | o |\n | / \\ |\n | o o |\n\n is Tamari-`\\leq` to the following tree::\n\n | _o_ |\n | / \\ |\n | o o |\n | / \\ \\ |\n | o o o |\n\n Checking this::\n\n sage: b = BinaryTree([[[[], []], None], []])\n sage: c = BinaryTree([[[],[]],[None,[]]])\n sage: b.tamari_lequal(c)\n True\n\n TESTS::\n\n sage: for T in BinaryTrees(4):\n ....: for S in T.tamari_smaller():\n ....: if S != T and T.tamari_lequal(S):\n ....: print("FAILURE")\n ....: if not S.tamari_lequal(T):\n ....: print("FAILURE")\n '
(self_word, n1) = self.tamari_sorting_tuple()
(t2_word, n2) = t2.tamari_sorting_tuple()
if (n1 != n2):
return False
return all(((x <= y) for (x, y) in zip(self_word, t2_word)))
def tamari_greater(self):
'\n The list of all trees greater or equal to ``self`` in the Tamari\n order.\n\n This is the order filter of the Tamari order generated by ``self``.\n\n See :meth:`tamari_lequal` for the definition of the Tamari poset.\n\n .. SEEALSO::\n\n :meth:`tamari_smaller`\n\n EXAMPLES:\n\n For example, the tree::\n\n | __o__ |\n | / \\ |\n | o o |\n | / \\ / |\n | o o o |\n\n has these trees greater or equal to it::\n\n |o , o , o , o , o , o ,|\n | \\ \\ \\ \\ \\ \\ |\n | o o o o _o_ __o__ |\n | \\ \\ \\ \\ / \\ / \\ |\n | o o o _o_ o o o o |\n | \\ \\ / \\ / \\ \\ \\ \\ / |\n | o o o o o o o o o o |\n | \\ \\ \\ / |\n | o o o o |\n | \\ / |\n | o o |\n <BLANKLINE>\n | o , o , _o_ , _o__ , __o__ , ___o___ ,|\n | / \\ / \\ / \\ / \\ / \\ / \\ |\n | o o o o o o o _o_ o o o o |\n | \\ \\ / \\ / \\ \\ \\ \\ / |\n | o o o o o o o o o o |\n | \\ \\ \\ / \\ \\ |\n | o o o o o o |\n | \\ / |\n | o o |\n <BLANKLINE>\n | _o_ , __o__ |\n | / \\ / \\ |\n | o o o o|\n | / \\ \\ / \\ / |\n | o o o o o o |\n\n TESTS::\n\n sage: B = BinaryTree\n sage: b = B([None, B([None, B([None, B([])])])]);b\n [., [., [., [., .]]]]\n sage: b.tamari_greater()\n [[., [., [., [., .]]]]]\n sage: b = B([B([B([B([]), None]), None]), None]);b\n [[[[., .], .], .], .]\n sage: b.tamari_greater()\n [[., [., [., [., .]]]], [., [., [[., .], .]]],\n [., [[., .], [., .]]], [., [[., [., .]], .]],\n [., [[[., .], .], .]], [[., .], [., [., .]]],\n [[., .], [[., .], .]], [[., [., .]], [., .]],\n [[., [., [., .]]], .], [[., [[., .], .]], .],\n [[[., .], .], [., .]], [[[., .], [., .]], .],\n [[[., [., .]], .], .], [[[[., .], .], .], .]]\n '
from sage.combinat.tools import transitive_ideal
return transitive_ideal((lambda x: x.tamari_succ()), self)
def tamari_pred(self):
'\n Compute the list of predecessors of ``self`` in the Tamari poset.\n\n This list is computed by performing all left rotates possible on\n its nodes.\n\n See :meth:`tamari_lequal` for the definition of the Tamari poset.\n\n EXAMPLES:\n\n For this tree::\n\n | __o__ |\n | / \\ |\n | o o |\n | / \\ / |\n | o o o |\n\n the list is::\n\n | o , _o_ |\n | / / \\ |\n | _o_ o o |\n | / \\ / / |\n | o o o o |\n | / \\ / |\n | o o o |\n\n TESTS::\n\n sage: B = BinaryTree\n sage: b = B([B([B([B([]), None]), None]), None]);b\n [[[[., .], .], .], .]\n sage: b.tamari_pred()\n []\n sage: b = B([None, B([None, B([None, B([])])])]);b\n [., [., [., [., .]]]]\n sage: b.tamari_pred()\n [[[., .], [., [., .]]], [., [[., .], [., .]]], [., [., [[., .], .]]]]\n '
if (not self):
return []
(s0, s1) = self
if s1:
res = [self.left_rotate()]
else:
res = []
B = self.parent()._element_constructor_
return ((res + [B([g, s1], check=False) for g in s0.tamari_pred()]) + [B([s0, d], check=False) for d in s1.tamari_pred()])
def tamari_smaller(self):
'\n The list of all trees smaller or equal to ``self`` in the Tamari\n order.\n\n This is the order ideal of the Tamari order generated by ``self``.\n\n See :meth:`tamari_lequal` for the definition of the Tamari poset.\n\n .. SEEALSO::\n\n :meth:`tamari_greater`\n\n EXAMPLES:\n\n The tree::\n\n | __o__ |\n | / \\ |\n | o o |\n | / \\ / |\n | o o o |\n\n has these trees smaller or equal to it::\n\n | __o__ , _o_ , o , o, o, o |\n | / \\ / \\ / / / / |\n | o o o o _o_ o o o |\n | / \\ / / / / \\ / \\ / / |\n |o o o o o o o o o o o |\n | / / \\ / / / |\n | o o o o o o |\n | / / \\ / |\n | o o o o |\n | / |\n | o |\n\n TESTS::\n\n sage: B = BinaryTree\n sage: b = B([None, B([None, B([None, B([])])])]);b\n [., [., [., [., .]]]]\n sage: b.tamari_smaller()\n [[., [., [., [., .]]]], [., [., [[., .], .]]],\n [., [[., .], [., .]]], [., [[., [., .]], .]],\n [., [[[., .], .], .]], [[., .], [., [., .]]],\n [[., .], [[., .], .]], [[., [., .]], [., .]],\n [[., [., [., .]]], .], [[., [[., .], .]], .],\n [[[., .], .], [., .]], [[[., .], [., .]], .],\n [[[., [., .]], .], .], [[[[., .], .], .], .]]\n sage: b = B([B([B([B([]), None]), None]), None]);b\n [[[[., .], .], .], .]\n sage: b.tamari_smaller()\n [[[[[., .], .], .], .]]\n '
from sage.combinat.tools import transitive_ideal
return transitive_ideal((lambda x: x.tamari_pred()), self)
def tamari_succ(self):
'\n Compute the list of successors of ``self`` in the Tamari poset.\n\n This is the list of all trees obtained by a right rotate of\n one of its nodes.\n\n See :meth:`tamari_lequal` for the definition of the Tamari poset.\n\n EXAMPLES:\n\n The list of successors of::\n\n | __o__ |\n | / \\ |\n | o o |\n | / \\ / |\n | o o o |\n\n is::\n\n | _o__ , ___o___ , _o_ |\n | / \\ / \\ / \\ |\n | o _o_ o o o o |\n | / \\ \\ / / \\ \\ |\n | o o o o o o o |\n | / \\ |\n | o o |\n\n TESTS::\n\n sage: B = BinaryTree\n sage: b = B([B([B([B([]), None]), None]), None]);b\n [[[[., .], .], .], .]\n sage: b.tamari_succ()\n [[[[., .], .], [., .]], [[[., .], [., .]], .], [[[., [., .]], .], .]]\n\n sage: b = B([])\n sage: b.tamari_succ()\n []\n\n sage: b = B([[],[]])\n sage: b.tamari_succ()\n [[., [., [., .]]]]\n '
res = []
if self.is_empty():
return []
B = self.parent()._element_constructor_
if (not self[0].is_empty()):
res.append(self.right_rotate())
return ((res + [B([g, self[1]]) for g in self[0].tamari_succ()]) + [B([self[0], d]) for d in self[1].tamari_succ()])
def single_edge_cut_shapes(self):
'\n Return the list of possible single-edge cut shapes for the binary tree.\n\n This is used in :meth:`sage.combinat.interval_posets.TamariIntervalPoset.is_new`.\n\n OUTPUT:\n\n a list of triples `(m, i, n)` of integers\n\n This is a list running over all inner edges (i.e., edges\n joining two non-leaf vertices) of the binary tree. The removal\n of each inner edge defines two binary trees (connected\n components), the root-tree and the sub-tree. Thus, to every\n inner edge, we can assign three positive integers:\n `m` is the node number of the root-tree `R`, and `n` is\n the node number of the sub-tree `S`. The integer `i` is the\n index of the leaf of `R` on which `S` is grafted to obtain the\n original tree. The leaves of `R` are numbered starting from\n `1` (from left to right), hence `1 \\leq i \\leq m+1`.\n\n In fact, each of `m` and `n` determines the other, as the\n total node number of `R` and `S` is the node number of\n ``self``.\n\n EXAMPLES::\n\n sage: BT = BinaryTrees(3)\n sage: [t.single_edge_cut_shapes() for t in BT]\n [[(2, 3, 1), (1, 2, 2)],\n [(2, 2, 1), (1, 2, 2)],\n [(2, 1, 1), (2, 3, 1)],\n [(2, 2, 1), (1, 1, 2)],\n [(2, 1, 1), (1, 1, 2)]]\n\n sage: BT = BinaryTrees(2)\n sage: [t.single_edge_cut_shapes() for t in BT]\n [[(1, 2, 1)], [(1, 1, 1)]]\n\n sage: BT = BinaryTrees(1)\n sage: [t.single_edge_cut_shapes() for t in BT]\n [[]]\n '
resu = []
(left, right) = list(self)
L = left.node_number()
R = right.node_number()
if L:
resu += [(((m + R) + 1), i, n) for (m, i, n) in left.single_edge_cut_shapes()]
resu += [((R + 1), 1, L)]
if R:
resu += [(((m + L) + 1), ((i + L) + 1), n) for (m, i, n) in right.single_edge_cut_shapes()]
resu += [((L + 1), (L + 2), R)]
return resu
def comb(self, side='left'):
"\n Return the comb of a tree.\n\n There are two combs in a binary tree: a left comb and a right comb.\n\n Consider all the vertices of the leftmost (resp. rightmost) branch of\n the root. The left (resp. right) comb is the list of right (resp. left)\n subtrees of each of these vertices.\n\n INPUT:\n\n - ``side`` -- (default: 'left') set to 'left' to obtain a left\n comb, and to 'right' to obtain a right comb.\n\n OUTPUT:\n\n A list of binary trees.\n\n .. SEEALSO::\n\n :meth:`over_decomposition`, :meth:`under_decomposition`\n\n EXAMPLES::\n\n sage: BT = BinaryTree( '.' )\n sage: [BT.comb('left'), BT.comb('right')]\n [[], []]\n sage: BT = BinaryTree( '[.,.]' )\n sage: [BT.comb('left'), BT.comb('right')]\n [[], []]\n sage: BT = BinaryTree( '[[[.,.], .], [.,.]]' )\n sage: BT.comb('left')\n [., .]\n sage: BT.comb('right')\n [.]\n sage: BT = BinaryTree( '[[[[., [., .]], .], [[., .], [[[., .], [., .]], [., .]]]], [., [[[., .], [[[., .], [., .]], .]], .]]]' )\n sage: ascii_art(BT)\n ________o________\n / \\\n __o__ o\n / \\ \\\n o __o___ o\n / / \\ /\n o o _o_ __o__\n \\ / \\ / \\\n o o o o o\n / \\ /\n o o o\n / \\\n o o\n sage: BT.comb('left')\n [[[., .], [[[., .], [., .]], [., .]]], ., [., .]]\n sage: ascii_art(BT.comb('left'))\n [ __o___ , , o ]\n [ / \\ ]\n [ o _o_ ]\n [ / \\ ]\n [ o o ]\n [ / \\ ]\n [ o o ]\n sage: BT.comb('right')\n [., [[., .], [[[., .], [., .]], .]]]\n sage: ascii_art(BT.comb('right'))\n [ , __o__ ]\n [ / \\ ]\n [ o o ]\n [ / ]\n [ o ]\n [ / \\ ]\n [ o o ]\n "
def _comb(side):
if self.is_empty():
return []
tree = self[side]
res = []
while (not tree.is_empty()):
res.append(tree[(1 - side)])
tree = tree[side]
return res
if (side == 'left'):
return _comb(0)
elif (side == 'right'):
return _comb(1)
def hook_number(self):
"\n Return the number of hooks.\n\n Recalling that a branch is a path from a vertex of the tree to a leaf,\n the leftmost (resp. rightmost) branch of a vertex `v` is the branch from\n `v` made only of left (resp. right) edges.\n\n The hook of a vertex `v` is a set of vertices formed by the\n union of `{v}`, and the vertices of its leftmost and rightmost branches.\n\n There is a unique way to partition the set of vertices in hooks.\n The number of hooks in such a partition is the hook number of the tree.\n\n We can obtain this partition recursively by extracting the root's hook\n and iterating the processus on each tree of the remaining forest.\n\n EXAMPLES::\n\n sage: BT = BinaryTree( '.' )\n sage: BT.hook_number()\n 0\n sage: BT = BinaryTree( '[.,.]' )\n sage: BT.hook_number()\n 1\n sage: BT = BinaryTree( '[[[.,.], .], [.,.]]' ); ascii_art(BT)\n o\n / \\\n o o\n /\n o\n sage: BT.hook_number()\n 1\n sage: BT = BinaryTree( '[[[[., [., .]], .], [[., .], [[[., .], [., .]], [., .]]]], [., [[[., .], [[[., .], [., .]], .]], .]]]' )\n sage: ascii_art(BT)\n ________o________\n / \\\n __o__ o\n / \\ \\\n o __o___ o\n / / \\ /\n o o _o_ __o__\n \\ / \\ / \\\n o o o o o\n / \\ /\n o o o\n / \\\n o o\n sage: BT.hook_number()\n 6\n "
if self.is_empty():
return 0
return (1 + sum((t.hook_number() for t in (self.comb('left') + self.comb('right')))))
def twisting_number(self):
"\n Return a pair (number of maximal left branches, number of maximal right\n branches).\n\n Recalling that a branch of a vertex `v` is a path from a vertex of the\n tree to a leaf, a left (resp. right) branch is a branch made only of\n left (resp. right) edges. The length of a branch is the number of edges\n composing it. A left (resp. right) branch is maximal if it is not\n included in a strictly longer left (resp. right) branch.\n\n OUTPUT:\n\n A list of two integers\n\n EXAMPLES::\n\n sage: BT = BinaryTree( '.' )\n sage: BT.twisting_number()\n [0, 0]\n sage: BT = BinaryTree( '[.,.]' )\n sage: BT.twisting_number()\n [0, 0]\n sage: BT = BinaryTree( '[[[.,.], .], [.,.]]' ); ascii_art(BT)\n o\n / \\\n o o\n /\n o\n sage: BT.twisting_number()\n [1, 1]\n sage: BT = BinaryTree( '[[[[., [., .]], .], [[., .], [[[., .], [., .]], [., .]]]], [., [[[., .], [[[., .], [., .]], .]], .]]]' )\n sage: ascii_art(BT)\n ________o________\n / \\\n __o__ o\n / \\ \\\n o __o___ o\n / / \\ /\n o o _o_ __o__\n \\ / \\ / \\\n o o o o o\n / \\ /\n o o o\n / \\\n o o\n sage: BT.twisting_number()\n [5, 6]\n sage: BT = BinaryTree( '[.,[[[.,.],.],.]]' ); ascii_art(BT)\n o\n \\\n o\n /\n o\n /\n o\n sage: BT.twisting_number()\n [1, 1]\n "
tn = [0, 0]
if (self.node_number() <= 1):
return tn
L = self.comb('left')
if L:
tn[0] += 1
for h in L:
tw = BinaryTree([None, h]).twisting_number()
tn[0] += tw[0]
tn[1] += tw[1]
R = self.comb('right')
if R:
tn[1] += 1
for l in R:
tw = BinaryTree([l, None]).twisting_number()
tn[0] += tw[0]
tn[1] += tw[1]
return tn
def q_hook_length_fraction(self, q=None, q_factor=False):
'\n Compute the ``q``-hook length fraction of the binary tree ``self``,\n with an additional "q-factor" if desired.\n\n If `T` is a (plane) binary tree and `q` is a polynomial\n indeterminate over some ring, then the `q`-hook length fraction\n `h_{q} (T)` of `T` is defined by\n\n .. MATH::\n\n h_{q} (T)\n = \\frac{[\\lvert T \\rvert]_q!}{\\prod_{t \\in T}\n [\\lvert T_t \\rvert]_q},\n\n where the product ranges over all nodes `t` of `T`, where `T_t`\n denotes the subtree of `T` consisting of `t` and its all\n descendants, and where for every tree `S`, we denote by\n `\\lvert S \\rvert` the number of nodes of `S`. While this\n definition only shows that `h_{q} (T)` is a rational function\n in `T`, it is in fact easy to show that `h_{q} (T)` is\n actually a polynomial in `T`, and thus makes sense when any\n element of a commutative ring is substituted for `q`.\n This can also be explicitly seen from the following recursive\n formula for `h_{q} (T)`:\n\n .. MATH::\n\n h_{q} (T)\n = \\binom{ \\lvert T \\rvert - 1 }{ \\lvert T_1 \\rvert }_q\n h_{q} (T_1) h_{q} (T_2),\n\n where `T` is any nonempty binary tree, and `T_1` and `T_2` are\n the two child trees of the root of `T`, and where\n `\\binom{a}{b}_q` denotes a `q`-binomial coefficient.\n\n A variation of the `q`-hook length fraction is the following\n "`q`-hook length fraction with `q`-factor":\n\n .. MATH::\n\n f_{q} (T)\n = h_{q} (T) \\cdot\n \\prod_{t \\in T} q^{\\lvert T_{\\mathrm{right}(t)} \\rvert},\n\n where for every node `t`, we denote by `\\mathrm{right}(t)` the\n right child of `t`.\n This `f_{q} (T)` differs from `h_{q} (T)` only in a\n multiplicative factor, which is a power of `q`.\n\n When `q = 1`, both `f_{q} (T)` and `h_{q} (T)` equal the number\n of permutations whose binary search tree (see [HNT2005]_ for the\n definition) is `T` (after dropping the labels). For example,\n there are `20` permutations which give a binary tree of the\n following shape::\n\n | __o__ |\n | / \\ |\n | o o |\n | / \\ / |\n | o o o |\n\n by the binary search insertion algorithm, in accordance with\n the fact that this tree satisfies `f_{1} (T) = 20`.\n\n When `q` is considered as a polynomial indeterminate,\n `f_{q} (T)` is the generating function for all permutations\n whose binary search tree is `T` (after dropping the labels)\n with respect to the number of inversions (i. e., the Coxeter\n length) of the permutations.\n\n Objects similar to `h_{q} (T)` also make sense for general\n ordered forests (rather than just binary trees), see e. g.\n [BW1988]_, Theorem 9.1.\n\n INPUT:\n\n - ``q`` -- a ring element which is to be substituted as `q`\n into the `q`-hook length fraction (by default, this is\n set to be the indeterminate `q` in the polynomial ring\n `\\ZZ[q]`)\n\n - ``q_factor`` -- a Boolean (default: ``False``) which\n determines whether to compute `h_{q} (T)` or to\n compute `f_{q} (T)` (namely, `h_{q} (T)` is obtained when\n ``q_factor == False``, and `f_{q} (T)` is obtained when\n ``q_factor == True``)\n\n EXAMPLES:\n\n Let us start with a simple example. Actually, let us start\n with the easiest possible example -- the binary tree with\n only one vertex (which is a leaf)::\n\n sage: b = BinaryTree()\n sage: b.q_hook_length_fraction() # needs sage.combinat\n 1\n sage: b.q_hook_length_fraction(q_factor=True) # needs sage.combinat\n 1\n\n Nothing different for a tree with one node and two leaves::\n\n sage: b = BinaryTree([]); b\n [., .]\n sage: b.q_hook_length_fraction() # needs sage.combinat\n 1\n sage: b.q_hook_length_fraction(q_factor=True) # needs sage.combinat\n 1\n\n Let us get to a more interesting tree::\n\n sage: # needs sage.combinat\n sage: b = BinaryTree([[[],[]],[[],None]]); b\n [[[., .], [., .]], [[., .], .]]\n sage: b.q_hook_length_fraction()(q=1)\n 20\n sage: b.q_hook_length_fraction()\n q^7 + 2*q^6 + 3*q^5 + 4*q^4 + 4*q^3 + 3*q^2 + 2*q + 1\n sage: b.q_hook_length_fraction(q_factor=True)\n q^10 + 2*q^9 + 3*q^8 + 4*q^7 + 4*q^6 + 3*q^5 + 2*q^4 + q^3\n sage: b.q_hook_length_fraction(q=2)\n 465\n sage: b.q_hook_length_fraction(q=2, q_factor=True)\n 3720\n sage: q = PolynomialRing(ZZ, \'q\').gen()\n sage: b.q_hook_length_fraction(q=q**2)\n q^14 + 2*q^12 + 3*q^10 + 4*q^8 + 4*q^6 + 3*q^4 + 2*q^2 + 1\n\n Let us check the fact that `f_{q} (T)` is the generating function\n for all permutations whose binary search tree is `T` (after\n dropping the labels) with respect to the number of inversions of\n the permutations::\n\n sage: def q_hook_length_fraction_2(T):\n ....: P = PolynomialRing(ZZ, \'q\')\n ....: q = P.gen()\n ....: res = P.zero()\n ....: for w in T.sylvester_class():\n ....: res += q ** Permutation(w).length()\n ....: return res\n sage: def test_genfun(i):\n ....: return all( q_hook_length_fraction_2(T)\n ....: == T.q_hook_length_fraction(q_factor=True)\n ....: for T in BinaryTrees(i) )\n sage: test_genfun(4) # needs sage.combinat\n True\n '
from sage.combinat.q_analogues import q_binomial
if (q is None):
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.integer_ring import ZZ
basering = PolynomialRing(ZZ, 'q')
q = basering.gen()
else:
basering = q.base_ring()
if q_factor:
def product_of_subtrees(b):
if b.is_empty():
return basering.one()
b0 = b[0]
b1 = b[1]
return (((q_binomial((b.node_number() - 1), b0.node_number(), q=q) * product_of_subtrees(b0)) * product_of_subtrees(b1)) * (q ** b1.node_number()))
else:
def product_of_subtrees(b):
if b.is_empty():
return basering.one()
b0 = b[0]
b1 = b[1]
return ((q_binomial((b.node_number() - 1), b0.node_number(), q=q) * product_of_subtrees(b0)) * product_of_subtrees(b1))
return product_of_subtrees(self)
@combinatorial_map(name='Right rotate')
def right_rotate(self):
'\n Return the result of right rotation applied to the binary\n tree ``self``.\n\n Right rotation on binary trees is defined as follows:\n Let `T` be a binary tree such that the left child of the\n root of `T` is a node. Let `C` be the right\n child of the root of `T`, and let `A` and `B` be the\n left and right children of the left child of the root\n of `T`. (Keep in mind that nodes of trees are identified\n with the subtrees consisting of their descendants.)\n Then, the right rotation of `T` is the binary tree in\n which the left child of the root is `A`, whereas\n the right child of the root is a node whose left and right\n children are `B` and `C`. In pictures::\n\n | * * |\n | / \\ / \\ |\n | * C -right-rotate-> A * |\n | / \\ / \\ |\n | A B B C |\n\n where asterisks signify a single node each (but `A`, `B`\n and `C` might be empty).\n\n For example, ::\n\n | o _o_ |\n | / / \\ |\n | o -right-rotate-> o o |\n | / \\ / |\n | o o o |\n <BLANKLINE>\n | __o__ _o__ |\n | / \\ / \\ |\n | o o -right-rotate-> o _o_ |\n | / \\ / / \\ |\n | o o o o o |\n | / \\ \\ |\n | o o o |\n\n Right rotation is the inverse operation to left rotation\n (:meth:`left_rotate`).\n\n The right rotation operation introduced here is the one defined\n in Definition 2.1 of [CP2012]_.\n\n .. SEEALSO::\n\n :meth:`left_rotate`\n\n EXAMPLES::\n\n sage: b = BinaryTree([[[],[]], None]); ascii_art([b])\n [ o ]\n [ / ]\n [ o ]\n [ / \\ ]\n [ o o ]\n sage: ascii_art([b.right_rotate()])\n [ _o_ ]\n [ / \\ ]\n [ o o ]\n [ / ]\n [ o ]\n sage: b = BinaryTree([[[[],None],[None,[]]], []]); ascii_art([b])\n [ __o__ ]\n [ / \\ ]\n [ o o ]\n [ / \\ ]\n [ o o ]\n [ / \\ ]\n [ o o ]\n sage: ascii_art([b.right_rotate()])\n [ _o__ ]\n [ / \\ ]\n [ o _o_ ]\n [ / / \\ ]\n [ o o o ]\n [ \\ ]\n [ o ]\n '
B = self.parent()._element_constructor_
return B([self[0][0], B([self[0][1], self[1]])])
@combinatorial_map(name='Left rotate')
def left_rotate(self):
'\n Return the result of left rotation applied to the binary\n tree ``self``.\n\n Left rotation on binary trees is defined as follows:\n Let `T` be a binary tree such that the right child of the\n root of `T` is a node. Let `A` be the left\n child of the root of `T`, and let `B` and `C` be the\n left and right children of the right child of the root\n of `T`. (Keep in mind that nodes of trees are identified\n with the subtrees consisting of their descendants.)\n Then, the left rotation of `T` is the binary tree in\n which the right child of the root is `C`, whereas\n the left child of the root is a node whose left and right\n children are `A` and `B`. In pictures::\n\n | * * |\n | / \\ / \\ |\n | A * -left-rotate-> * C |\n | / \\ / \\ |\n | B C A B |\n\n where asterisks signify a single node each (but `A`, `B`\n and `C` might be empty).\n\n For example, ::\n\n | _o_ o |\n | / \\ / |\n | o o -left-rotate-> o |\n | / / \\ |\n | o o o |\n <BLANKLINE>\n | __o__ o |\n | / \\ / |\n | o o -left-rotate-> o |\n | / \\ / |\n | o o o |\n | / \\ / \\ |\n | o o o o |\n | / \\ |\n | o o |\n\n Left rotation is the inverse operation to right rotation\n (:meth:`right_rotate`).\n\n .. SEEALSO::\n\n :meth:`right_rotate`\n\n EXAMPLES::\n\n sage: b = BinaryTree([[],[[],None]]); ascii_art([b])\n [ _o_ ]\n [ / \\ ]\n [ o o ]\n [ / ]\n [ o ]\n sage: ascii_art([b.left_rotate()])\n [ o ]\n [ / ]\n [ o ]\n [ / \\ ]\n [ o o ]\n sage: b.left_rotate().right_rotate() == b\n True\n '
B = self.parent()._element_constructor_
return B([B([self[0], self[1][0]]), self[1][1]])
@combinatorial_map(name='Over operation on Binary Trees')
def over(self, bt):
'\n Return ``self`` over ``bt``, where "over" is the ``over``\n (`/`) operation.\n\n If `T` and `T\'` are two binary trees, then `T` over `T\'`\n (written `T / T\'`) is defined as the tree obtained by grafting\n `T\'` on the rightmost leaf of `T`. More precisely, `T / T\'` is\n defined by identifying the root of the `T\'` with the rightmost\n leaf of `T`. See section 4.5 of [HNT2005]_.\n\n If `T` is empty, then `T / T\' = T\'`.\n\n The definition of this "over" operation goes back to\n Loday-Ronco [LR0102066]_ (Definition 2.2), but it is\n denoted by `\\backslash` and called the "under" operation there.\n In fact, trees in sage have their root at the top, contrary to\n the trees in [LR0102066]_ which are growing upwards. For\n this reason, the names of the over and under operations are\n swapped, in order to keep a graphical meaning.\n (Our notation follows that of section 4.5 of [HNT2005]_.)\n\n .. SEEALSO::\n\n :meth:`under`\n\n EXAMPLES:\n\n Showing only the nodes of a binary tree, here is an\n example for the over operation::\n\n | o __o__ _o_ |\n | / \\ / / \\ = / \\ |\n | o o o o o o |\n | \\ / \\ |\n | o o __o__ |\n | / \\ |\n | o o |\n | \\ / |\n | o o |\n\n A Sage example::\n\n sage: b1 = BinaryTree([[],[[],[]]])\n sage: b2 = BinaryTree([[None, []],[]])\n sage: ascii_art((b1, b2, b1/b2))\n ( _o_ , _o_ , _o_ )\n ( / \\ / \\ / \\ )\n ( o o o o o o_ )\n ( / \\ \\ / \\ )\n ( o o o o o )\n ( \\ )\n ( _o_ )\n ( / \\ )\n ( o o )\n ( \\ )\n ( o )\n\n TESTS::\n\n sage: b1 = BinaryTree([[],[]]); ascii_art([b1])\n [ o ]\n [ / \\ ]\n [ o o ]\n sage: b2 = BinaryTree([[None,[]],[[],None]]); ascii_art([b2])\n [ __o__ ]\n [ / \\ ]\n [ o o ]\n [ \\ / ]\n [ o o ]\n sage: ascii_art([b1.over(b2)])\n [ _o_ ]\n [ / \\ ]\n [ o o ]\n [ \\ ]\n [ __o__ ]\n [ / \\ ]\n [ o o ]\n [ \\ / ]\n [ o o ]\n\n The same in the labelled case::\n\n sage: b1 = b1.canonical_labelling()\n sage: b2 = b2.canonical_labelling()\n sage: ascii_art([b1.over(b2)])\n [ _2_ ]\n [ / \\ ]\n [ 1 3 ]\n [ \\ ]\n [ __3__ ]\n [ / \\ ]\n [ 1 5 ]\n [ \\ / ]\n [ 2 4 ]\n '
B = self.parent()._element_constructor_
if self.is_empty():
return bt
if hasattr(self, 'label'):
lab = self.label()
return B([self[0], self[1].over(bt)], lab)
else:
return B([self[0], self[1].over(bt)])
__truediv__ = over
@combinatorial_map(name='Under operation on Binary Trees')
def under(self, bt):
'\n Return ``self`` under ``bt``, where "under" is the ``under``\n (`\\backslash`) operation.\n\n If `T` and `T\'` are two binary trees, then `T` under `T\'`\n (written `T \\backslash T\'`) is defined as the tree obtained\n by grafting `T` on the leftmost leaf of `T\'`. More precisely,\n `T \\backslash T\'` is defined by identifying the root of `T`\n with the leftmost leaf of `T\'`.\n\n If `T\'` is empty, then `T \\backslash T\' = T`.\n\n The definition of this "under" operation goes back to\n Loday-Ronco [LR0102066]_ (Definition 2.2), but it is\n denoted by `/` and called the "over" operation there. In fact,\n trees in sage have their root at the top, contrary to the trees\n in [LR0102066]_ which are growing upwards. For this reason,\n the names of the over and under operations are swapped, in\n order to keep a graphical meaning.\n (Our notation follows that of section 4.5 of [HNT2005]_.)\n\n .. SEEALSO::\n\n :meth:`over`\n\n EXAMPLES:\n\n Showing only the nodes of a binary tree, here is an\n example for the under operation::\n\n sage: b1 = BinaryTree([[],[]])\n sage: b2 = BinaryTree([None,[]])\n sage: ascii_art((b1, b2, b1.under(b2)))\n ( o , o , _o_ )\n ( / \\ \\ / \\ )\n ( o o o o o )\n ( / \\ )\n ( o o )\n\n TESTS::\n\n sage: b1 = BinaryTree([[],[[None,[]],None]]); ascii_art([b1])\n [ _o_ ]\n [ / \\ ]\n [ o o ]\n [ / ]\n [ o ]\n [ \\ ]\n [ o ]\n sage: b2 = BinaryTree([[],[None,[]]]); ascii_art([b2])\n [ o ]\n [ / \\ ]\n [ o o ]\n [ \\ ]\n [ o ]\n sage: ascii_art([b1.under(b2)])\n [ o_ ]\n [ / \\ ]\n [ o o ]\n [ / \\ ]\n [ _o_ o ]\n [ / \\ ]\n [ o o ]\n [ / ]\n [ o ]\n [ \\ ]\n [ o ]\n\n The same in the labelled case::\n\n sage: b1 = b1.canonical_labelling()\n sage: b2 = b2.canonical_labelling()\n sage: ascii_art([b1.under(b2)])\n [ 2_ ]\n [ / \\ ]\n [ 1 3 ]\n [ / \\ ]\n [ _2_ 4 ]\n [ / \\ ]\n [ 1 5 ]\n [ / ]\n [ 3 ]\n [ \\ ]\n [ 4 ]\n '
if bt.is_empty():
return self
B = self.parent()._element_constructor_
if hasattr(bt, 'label'):
lab = bt.label()
return B([self.under(bt[0]), bt[1]], lab)
else:
return B([self.under(bt[0]), bt[1]])
_backslash_ = deprecated_function_alias(36394, under)
def under_decomposition(self):
'\n Return the unique maximal decomposition as an under product.\n\n This means that the tree is cut along all edges of its leftmost path.\n\n Beware that the factors are ordered starting from the root.\n\n .. SEEALSO::\n\n :meth:`comb`, :meth:`over_decomposition`\n\n EXAMPLES::\n\n sage: g = BinaryTree([])\n sage: r = g.over(g); r\n [., [., .]]\n sage: l = g.under(g); l\n [[., .], .]\n sage: l.under_decomposition()\n [[., .], [., .]]\n sage: r.under_decomposition() == [r]\n True\n\n sage: x = r.under(g).under(r).under(g)\n sage: ascii_art(x)\n o\n /\n o\n / \\\n o o\n /\n o\n \\\n o\n sage: x.under_decomposition() == [g,r,g,r]\n True\n '
if self.is_empty():
return []
B = self.parent()._element_constructor_
resu = []
bt = self
while (not bt.is_empty()):
if hasattr(bt, 'label'):
lab = bt.label()
resu.append(B([None, bt[1]], lab))
else:
resu.append(B([None, bt[1]]))
bt = bt[0]
return resu
def over_decomposition(self):
'\n Return the unique maximal decomposition as an over product.\n\n This means that the tree is cut along all edges of its rightmost path.\n\n Beware that the factors are ordered starting from the root.\n\n .. SEEALSO::\n\n :meth:`comb`, :meth:`under_decomposition`\n\n EXAMPLES::\n\n sage: g = BinaryTree([])\n sage: r = g.over(g); r\n [., [., .]]\n sage: l = g.under(g); l\n [[., .], .]\n sage: r.over_decomposition()\n [[., .], [., .]]\n sage: l.over_decomposition() == [l]\n True\n\n sage: x = g.over(l).over(l).over(g).over(g)\n sage: ascii_art(x)\n o\n _o_\n / o o\n / o o\n o\n sage: x.over_decomposition() == [g,l,l,g,g]\n True\n '
if self.is_empty():
return []
B = self.parent()._element_constructor_
resu = []
bt = self
while (not bt.is_empty()):
if hasattr(bt, 'label'):
lab = bt.label()
resu.append(B([bt[0], None], lab))
else:
resu.append(B([bt[0], None]))
bt = bt[1]
return resu
def dendriform_shuffle(self, other):
'\n Return the list of terms in the dendriform product.\n\n This is the list of all binary trees that can be obtained by\n identifying the rightmost path in ``self`` and the leftmost\n path in ``other``. Every term corresponds to a shuffle of the\n vertices on the rightmost path in ``self`` and the vertices on\n the leftmost path in ``other``.\n\n EXAMPLES::\n\n sage: u = BinaryTree()\n sage: g = BinaryTree([])\n sage: l = BinaryTree([g, u])\n sage: r = BinaryTree([u, g])\n\n sage: list(g.dendriform_shuffle(g)) # needs sage.combinat\n [[[., .], .], [., [., .]]]\n\n sage: list(l.dendriform_shuffle(l)) # needs sage.combinat\n [[[[[., .], .], .], .], [[[., .], [., .]], .],\n [[., .], [[., .], .]]]\n\n sage: list(l.dendriform_shuffle(r)) # needs sage.combinat\n [[[[., .], .], [., .]], [[., .], [., [., .]]]]\n\n TESTS::\n\n sage: # needs sage.combinat\n sage: list(u.dendriform_shuffle(u))\n [.]\n sage: list(u.dendriform_shuffle(g))\n [[., .]]\n sage: list(u.dendriform_shuffle(l))\n [[[., .], .]]\n sage: list(u.dendriform_shuffle(r))\n [[., [., .]]]\n sage: list(r.dendriform_shuffle(u))\n [[., [., .]]]\n sage: list(l.dendriform_shuffle(u))\n [[[., .], .]]\n '
from sage.combinat.words.shuffle_product import ShuffleProduct_w1w2
from sage.combinat.words.word import Word
if self.is_empty():
(yield other)
elif other.is_empty():
(yield self)
else:
B = self.parent()._element_constructor_
left_list = self.over_decomposition()
right_list = other.under_decomposition()
w_left = Word(('L' * len(left_list)))
w_right = Word(('R' * len(right_list)))
for w in ShuffleProduct_w1w2(w_left, w_right):
t = B(None)
c_left_list = list(left_list)
c_right_list = list(right_list)
for letter in w:
if (letter == 'L'):
lt = c_left_list.pop()
t = lt.over(t)
else:
rt = c_right_list.pop()
t = t.under(rt)
(yield t)
def sylvester_class(self, left_to_right=False):
"\n Iterate over the sylvester class corresponding to the binary tree\n ``self``.\n\n The sylvester class of a tree `T` is the set of permutations\n `\\sigma` whose right-to-left binary search tree (a notion defined\n in [HNT2005]_, Definition 7) is `T` after forgetting the labels.\n This is an equivalence class of the sylvester congruence (the\n congruence on words which holds two words `uacvbw` and `ucavbw`\n congruent whenever `a`, `b`, `c` are letters satisfying\n `a \\leq b < c`, and extends by transitivity) on the symmetric\n group.\n\n For example the following tree's sylvester class consists of the\n permutations `(1,3,2)` and `(3,1,2)`::\n\n [ o ]\n [ / \\ ]\n [ o o ]\n\n (only the nodes are drawn here).\n\n The right-to-left binary search tree of a word is constructed by\n an RSK-like insertion algorithm which proceeds as follows: Start\n with an empty labelled binary tree, and read the word from right\n to left. Each time a letter is read from the word, insert this\n letter in the existing tree using binary search tree insertion\n (:meth:`~sage.combinat.binary_tree.LabelledBinaryTree.binary_search_insert`).\n This is what the\n :meth:`~sage.combinat.permutation.Permutation.binary_search_tree`\n method computes if it is given the keyword\n ``left_to_right=False``.\n\n Here are two more descriptions of the sylvester class of a binary\n search tree:\n\n - The sylvester class of a binary search tree `T` is the set of\n all linear extensions of the poset corresponding to `T` (that\n is, of the poset whose Hasse diagram is `T`, with the root on\n top), provided that the nodes of `T` are labelled with\n `1, 2, \\ldots, n` in a binary-search-tree way (i.e., every left\n descendant of a node has a label smaller than that of the node,\n and every right descendant of a node has a label higher than\n that of the node).\n\n - The sylvester class of a binary search tree `T` (with vertex\n labels `1, 2, \\ldots, n`) is the interval `[u, v]` in the right\n permutohedron order\n (:meth:`~sage.combinat.permutation.Permutation.permutohedron_lequal`),\n where `u` is the 312-avoiding permutation corresponding to `T`\n (:meth:`to_312_avoiding_permutation`), and where `v` is the\n 132-avoiding permutation corresponding to `T`\n (:meth:`to_132_avoiding_permutation`).\n\n If the optional keyword variable ``left_to_right`` is set to\n ``True``, then the *left* sylvester class of ``self`` is\n returned instead. This is the set of permutations `\\sigma` whose\n left-to-right binary search tree (that is, the result of the\n :meth:`~sage.combinat.permutation.Permutation.binary_search_tree`\n with ``left_to_right`` set to ``True``) is ``self``. It is an\n equivalence class of the left sylvester congruence.\n\n .. WARNING::\n\n This method yields the elements of the sylvester class as\n raw lists, not as permutations!\n\n EXAMPLES:\n\n Verifying the claim that the right-to-left binary search trees of\n the permutations in the sylvester class of a tree `t` all equal\n `t`::\n\n sage: def test_bst_of_sc(n, left_to_right):\n ....: for t in BinaryTrees(n):\n ....: for p in t.sylvester_class(left_to_right=left_to_right):\n ....: p_per = Permutation(p)\n ....: tree = p_per.binary_search_tree(left_to_right=left_to_right)\n ....: if not BinaryTree(tree) == t:\n ....: return False\n ....: return True\n sage: test_bst_of_sc(4, False) # needs sage.combinat\n True\n sage: test_bst_of_sc(5, False) # long time # needs sage.combinat\n True\n\n The same with the left-to-right version of binary search::\n\n sage: test_bst_of_sc(4, True) # needs sage.combinat\n True\n sage: test_bst_of_sc(5, True) # long time # needs sage.combinat\n True\n\n Checking that the sylvester class is the set of linear extensions\n of the poset of the tree::\n\n sage: all(sorted(t.canonical_labelling().sylvester_class()) # needs sage.combinat sage.modules\n ....: == sorted(list(v)\n ....: for v in t.canonical_labelling().to_poset().linear_extensions())\n ....: for t in BinaryTrees(4))\n True\n\n TESTS::\n\n sage: list(BinaryTree([[],[]]).sylvester_class()) # needs sage.combinat\n [[1, 3, 2], [3, 1, 2]]\n sage: bt = BinaryTree([[[],None],[[],[]]])\n sage: l = list(bt.sylvester_class()); l # needs sage.combinat\n [[1, 2, 4, 6, 5, 3],\n [1, 4, 2, 6, 5, 3],\n [1, 4, 6, 2, 5, 3],\n [1, 4, 6, 5, 2, 3],\n [4, 1, 2, 6, 5, 3],\n [4, 1, 6, 2, 5, 3],\n [4, 1, 6, 5, 2, 3],\n [4, 6, 1, 2, 5, 3],\n [4, 6, 1, 5, 2, 3],\n [4, 6, 5, 1, 2, 3],\n [1, 2, 6, 4, 5, 3],\n [1, 6, 2, 4, 5, 3],\n [1, 6, 4, 2, 5, 3],\n [1, 6, 4, 5, 2, 3],\n [6, 1, 2, 4, 5, 3],\n [6, 1, 4, 2, 5, 3],\n [6, 1, 4, 5, 2, 3],\n [6, 4, 1, 2, 5, 3],\n [6, 4, 1, 5, 2, 3],\n [6, 4, 5, 1, 2, 3]]\n sage: len(l) == Integer(bt.q_hook_length_fraction()(q=1)) # needs sage.combinat\n True\n\n Border cases::\n\n sage: list(BinaryTree().sylvester_class()) # needs sage.combinat\n [[]]\n sage: list(BinaryTree([]).sylvester_class()) # needs sage.combinat\n [[1]]\n "
if self.is_empty():
(yield [])
return
from itertools import product
from sage.combinat.words.word import Word as W
from sage.combinat.words.shuffle_product import ShuffleProduct_w1w2 as shuffle
if left_to_right:
def builder(i, p):
return ([i] + list(p))
else:
def builder(i, p):
return (list(p) + [i])
shift = (self[0].node_number() + 1)
for (l, r) in product(self[0].sylvester_class(left_to_right=left_to_right), self[1].sylvester_class(left_to_right=left_to_right)):
for p in shuffle(W(l), W([(shift + ri) for ri in r])):
(yield builder(shift, p))
def is_full(self):
'\n Return ``True`` if ``self`` is full, else return ``False``.\n\n A full binary tree is a tree in which every node either has two\n child nodes or has two child leaves.\n\n This is also known as *proper binary tree* or *2-tree* or *strictly\n binary tree*.\n\n For example::\n\n | __o__ |\n | / \\ |\n | o o |\n | / \\ |\n | o o |\n | / \\ |\n | o o |\n\n is not full but the next one is::\n\n | ___o___ |\n | / \\ |\n | __o__ o |\n | / \\ |\n | o o |\n | / \\ / \\ |\n | o o o o |\n\n EXAMPLES::\n\n sage: BinaryTree([[[[],None],[None,[]]], []]).is_full()\n False\n sage: BinaryTree([[[[],[]],[[],[]]], []]).is_full()\n True\n sage: ascii_art([bt for bt in BinaryTrees(5) if bt.is_full()])\n [ _o_ , _o_ ]\n [ / \\ / \\ ]\n [ o o o o ]\n [ / \\ / \\ ]\n [ o o o o ]\n '
if self.is_empty():
return True
if (self[0].is_empty() != self[1].is_empty()):
return False
return (self[0].is_full() and self[1].is_full())
def to_full(self):
'\n Return the full binary tree constructed from ``self``.\n\n Let `T` be a binary tree with `n` nodes. We construct a full\n binary tree `F` from `T` by attaching a leaf to each node of\n `T` which does not have 2 children. The resulting tree will\n have `2n + 1` nodes.\n\n OUTPUT:\n\n A full binary tree. See :meth:`is_full` for the definition of full.\n\n .. SEEALSO::\n\n :meth:`prune`\n\n EXAMPLES::\n\n sage: bt = BinaryTree([[None,[]],None])\n sage: bt.to_full().is_full()\n True\n sage: ascii_art(bt)\n o\n /\n o\n \\\n o\n sage: ascii_art(bt.to_full())\n __o___\n / \\\n _o_ o\n / \\\n o o\n / \\\n o o\n\n sage: bt = BinaryTree([[],[]])\n sage: ascii_art(bt)\n o\n / \\\n o o\n sage: ascii_art(bt.to_full())\n __o__\n / \\\n o o\n / \\ / \\\n o o o o\n\n sage: BinaryTree(None).to_full()\n [., .]\n\n '
if self.is_empty():
return BinaryTree('[.,.]')
return BinaryTree([self[0].to_full(), self[1].to_full()])
def prune(self):
'\n Return the binary tree obtained by deleting each leaf of ``self``.\n\n The operation of pruning is the left inverse of attaching as\n many leaves as possible to each node of a binary tree.\n That is to say, for all binary trees ``bt``, we have::\n\n bt == bt.to_full().prune()\n\n However, it is only a right inverse if and only if ``bt``\n is a full binary tree::\n\n bt == bt.prune().to_full()\n\n OUTPUT:\n\n A binary tree.\n\n .. SEEALSO::\n\n :meth:`to_full`\n\n EXAMPLES::\n\n sage: bt = BinaryTree([[[None, []], [[], []]], None])\n sage: ascii_art(bt)\n o\n /\n __o__\n / \\\n o o\n \\ / \\\n o o o\n sage: ascii_art(bt.prune())\n o\n /\n o\n / \\\n o o\n\n We check the relationship with :meth:`to_full`::\n\n sage: bt = BinaryTree([[[], [[None, []], []]], [[],[]]])\n sage: bt == bt.to_full().prune()\n True\n sage: bt == bt.prune().to_full()\n False\n\n sage: bt = BinaryTree([[[], []], [[], [[[], []], []]]])\n sage: bt.is_full()\n True\n sage: bt == bt.prune().to_full()\n True\n\n Pruning the empty tree is again the empty tree::\n\n sage: bt = BinaryTree(None)\n sage: bt.prune()\n .\n '
if self.is_empty():
return self
if (self == BinaryTree([])):
return BinaryTree()
return BinaryTree([self[0].prune(), self[1].prune()])
def is_perfect(self):
'\n Return ``True`` if ``self`` is perfect, else return ``False``.\n\n A perfect binary tree is a full tree in which all leaves are at the\n same depth.\n\n For example::\n\n | ___o___ |\n | / \\ |\n | __o__ o |\n | / \\ |\n | o o |\n | / \\ / \\ |\n | o o o o |\n\n is not perfect but the next one is::\n\n | __o__ |\n | / \\ |\n | o o |\n | / \\ / \\ |\n | o o o o |\n\n EXAMPLES::\n\n sage: def lst(i):\n ....: return [bt for bt in BinaryTrees(i) if bt.is_perfect()]\n sage: for i in range(8): ascii_art(lst(i)) # long time\n [ ]\n [ o ]\n [ ]\n [ o ]\n [ / \\ ]\n [ o o ]\n [ ]\n [ ]\n [ ]\n [ __o__ ]\n [ / \\ ]\n [ o o ]\n [ / \\ / \\ ]\n [ o o o o ]\n '
return (((2 ** self.depth()) - 1) == self.node_number())
def is_complete(self):
'\n Return ``True`` if ``self`` is complete, else return ``False``.\n\n In a nutshell, a complete binary tree is a perfect binary tree\n except possibly in the last level, with all nodes in the last\n level "flush to the left".\n\n In more detail:\n A complete binary tree (also called binary heap) is a binary tree in\n which every level, except possibly the last one (the deepest), is\n completely filled. At depth `n`, all nodes must be as far left as\n possible.\n\n For example::\n\n | ___o___ |\n | / \\ |\n | __o__ o |\n | / \\ |\n | o o |\n | / \\ / \\ |\n | o o o o |\n\n is not complete but the following ones are::\n\n | __o__ _o_ ___o___ |\n | / \\ / \\ / \\ |\n | o o o o __o__ o |\n | / \\ / \\ / \\ / \\ / \\ |\n | o o o o, o o , o o o o |\n | / \\ / |\n | o o o |\n\n EXAMPLES::\n\n sage: def lst(i):\n ....: return [bt for bt in BinaryTrees(i) if bt.is_complete()]\n sage: for i in range(8): ascii_art(lst(i)) # long time\n [ ]\n [ o ]\n [ o ]\n [ / ]\n [ o ]\n [ o ]\n [ / \\ ]\n [ o o ]\n [ o ]\n [ / \\ ]\n [ o o ]\n [ / ]\n [ o ]\n [ _o_ ]\n [ / \\ ]\n [ o o ]\n [ / \\ ]\n [ o o ]\n [ __o__ ]\n [ / \\ ]\n [ o o ]\n [ / \\ / ]\n [ o o o ]\n [ __o__ ]\n [ / \\ ]\n [ o o ]\n [ / \\ / \\ ]\n [ o o o o ]\n '
if self.is_empty():
return True
dL = self[0].depth()
dR = self[1].depth()
if self[0].is_perfect():
if (dL == dR):
return self[1].is_complete()
elif (dL == (dR + 1)):
return self[1].is_perfect()
return False
return (self[0].is_complete() and self[1].is_perfect() and (dL == (dR + 1)))
|
class BinaryTrees(UniqueRepresentation, Parent):
'\n Factory for binary trees.\n\n A binary tree is a tree with at most 2 children. The binary\n trees considered here are also ordered (a.k.a. planar), that is\n to say, their children are ordered.\n\n A full binary tree is a binary tree with no nodes with 1 child.\n\n INPUT:\n\n - ``size`` -- (optional) an integer\n - ``full`` -- (optional) a boolean\n\n OUTPUT:\n\n The set of all (full if ``full=True``) binary trees (of the given\n ``size`` if specified).\n\n .. SEEALSO::\n\n :class:`BinaryTree`, :meth:`BinaryTree.is_full`\n\n EXAMPLES::\n\n sage: BinaryTrees()\n Binary trees\n\n sage: BinaryTrees(2)\n Binary trees of size 2\n\n sage: BinaryTrees(full=True)\n Full binary trees\n\n sage: BinaryTrees(3, full=True)\n Full binary trees of size 3\n\n sage: BinaryTrees(4, full=True)\n Traceback (most recent call last):\n ...\n ValueError: n must be 0 or odd\n\n .. NOTE::\n\n This is a factory class whose constructor returns instances of\n subclasses.\n\n .. NOTE::\n\n The fact that BinaryTrees is a class instead of a simple callable\n is an implementation detail. It could be changed in the future\n and one should not rely on it.\n '
@staticmethod
def __classcall_private__(cls, n=None, full=False):
'\n TESTS::\n\n sage: from sage.combinat.binary_tree import (BinaryTrees_all,\n ....: BinaryTrees_size, FullBinaryTrees_all, FullBinaryTrees_size)\n sage: isinstance(BinaryTrees(2), BinaryTrees)\n True\n sage: isinstance(BinaryTrees(), BinaryTrees)\n True\n sage: isinstance(BinaryTrees(3, full=True), BinaryTrees)\n True\n sage: isinstance(BinaryTrees(full=True), BinaryTrees)\n True\n sage: BinaryTrees(2) is BinaryTrees_size(2)\n True\n sage: BinaryTrees(5).cardinality()\n 42\n sage: BinaryTrees() is BinaryTrees_all()\n True\n sage: BinaryTrees(3, full=True) is FullBinaryTrees_size(3)\n True\n sage: BinaryTrees(5, full=True).cardinality()\n 2\n sage: BinaryTrees(full=True) is FullBinaryTrees_all()\n True\n '
if (n is None):
if full:
return FullBinaryTrees_all()
else:
return BinaryTrees_all()
else:
if (not (isinstance(n, (Integer, int)) and (n >= 0))):
raise ValueError('n must be a nonnegative integer')
if (not full):
return BinaryTrees_size(Integer(n))
elif (((n % 2) == 1) or (n == 0)):
return FullBinaryTrees_size(Integer(n))
else:
raise ValueError('n must be 0 or odd')
@cached_method
def leaf(self):
'\n Return a leaf tree with ``self`` as parent.\n\n EXAMPLES::\n\n sage: BinaryTrees().leaf()\n .\n\n TESTS::\n\n sage: (BinaryTrees().leaf() is\n ....: sage.combinat.binary_tree.BinaryTrees_all().leaf())\n True\n '
return self(None)
|
def from_tamari_sorting_tuple(key):
'\n Return a binary tree from its Tamari-sorting tuple.\n\n See :meth:`~sage.combinat.binary_tree.BinaryTree.tamari_sorting_tuple`\n\n INPUT:\n\n - ``key`` -- a tuple of integers\n\n EXAMPLES::\n\n sage: from sage.combinat.binary_tree import from_tamari_sorting_tuple\n sage: t = BinaryTrees(60).random_element() # needs sage.combinat\n sage: from_tamari_sorting_tuple(t.tamari_sorting_tuple()[0]) == t # needs sage.combinat\n True\n '
if (not key):
return BinaryTree()
n = len(key)
for (i, v) in enumerate(key):
if (v == ((n - i) - 1)):
break
return BinaryTree([from_tamari_sorting_tuple(key[:i]), from_tamari_sorting_tuple(key[(i + 1):])])
|
class BinaryTrees_all(DisjointUnionEnumeratedSets, BinaryTrees):
def __init__(self):
'\n TESTS::\n\n sage: from sage.combinat.binary_tree import BinaryTrees_all\n sage: B = BinaryTrees_all()\n sage: B.cardinality()\n +Infinity\n\n sage: it = iter(B)\n sage: (next(it), next(it), next(it), next(it), next(it))\n (., [., .], [., [., .]], [[., .], .], [., [., [., .]]])\n sage: next(it).parent()\n Binary trees\n sage: B([])\n [., .]\n\n sage: B is BinaryTrees_all()\n True\n sage: TestSuite(B).run() # long time\n '
DisjointUnionEnumeratedSets.__init__(self, Family(NonNegativeIntegers(), BinaryTrees_size), facade=True, keepkey=False)
def _repr_(self):
'\n TESTS::\n\n sage: BinaryTrees() # indirect doctest\n Binary trees\n '
return 'Binary trees'
def __contains__(self, x):
'\n TESTS::\n\n sage: S = BinaryTrees()\n sage: 1 in S\n False\n sage: S([]) in S\n True\n '
return isinstance(x, self.element_class)
def __call__(self, x=None, *args, **keywords):
'\n Ensure that ``None`` instead of ``0`` is passed by default.\n\n TESTS::\n\n sage: B = BinaryTrees()\n sage: B()\n .\n '
return super().__call__(x, *args, **keywords)
def unlabelled_trees(self):
'\n Return the set of unlabelled trees associated to ``self``.\n\n EXAMPLES::\n\n sage: BinaryTrees().unlabelled_trees()\n Binary trees\n '
return self
def labelled_trees(self):
'\n Return the set of labelled trees associated to ``self``.\n\n EXAMPLES::\n\n sage: BinaryTrees().labelled_trees()\n Labelled binary trees\n '
return LabelledBinaryTrees()
def _element_constructor_(self, *args, **keywords):
'\n EXAMPLES::\n\n sage: B = BinaryTrees()\n sage: B._element_constructor_([])\n [., .]\n sage: B([[],[]]) # indirect doctest\n [[., .], [., .]]\n sage: B(None) # indirect doctest\n .\n '
return self.element_class(self, *args, **keywords)
Element = BinaryTree
|
class BinaryTrees_size(BinaryTrees):
'\n The enumerated sets of binary trees of given size.\n\n TESTS::\n\n sage: from sage.combinat.binary_tree import BinaryTrees_size\n sage: for i in range(6): TestSuite(BinaryTrees_size(i)).run()\n '
def __init__(self, size):
'\n TESTS::\n\n sage: S = BinaryTrees(3)\n sage: S == loads(dumps(S))\n True\n\n sage: S is BinaryTrees(3)\n True\n '
super().__init__(facade=BinaryTrees_all(), category=FiniteEnumeratedSets())
self._size = size
def _repr_(self):
'\n TESTS::\n\n sage: BinaryTrees(3) # indirect doctest\n Binary trees of size 3\n '
return ('Binary trees of size %s' % self._size)
def __contains__(self, x):
'\n TESTS::\n\n sage: S = BinaryTrees(3)\n sage: 1 in S\n False\n sage: S([[],[]]) in S\n True\n '
return (isinstance(x, BinaryTree) and (x.node_number() == self._size))
def _an_element_(self):
'\n TESTS::\n\n sage: BinaryTrees(0).an_element() # indirect doctest\n .\n '
return self.first()
def cardinality(self):
'\n The cardinality of ``self``\n\n This is a Catalan number.\n\n TESTS::\n\n sage: BinaryTrees(0).cardinality()\n 1\n sage: BinaryTrees(5).cardinality()\n 42\n '
from .combinat import catalan_number
return catalan_number(self._size)
def random_element(self):
'\n Return a random ``BinaryTree`` with uniform probability.\n\n This method generates a random ``DyckWord`` and then uses a\n bijection between Dyck words and binary trees.\n\n EXAMPLES::\n\n sage: BinaryTrees(5).random_element() # random # needs sage.combinat\n [., [., [., [., [., .]]]]]\n sage: BinaryTrees(0).random_element() # needs sage.combinat\n .\n sage: BinaryTrees(1).random_element() # needs sage.combinat\n [., .]\n\n TESTS::\n\n sage: all(BinaryTrees(10).random_element() in BinaryTrees(10) # needs sage.combinat\n ....: for i in range(20))\n True\n '
from sage.combinat.dyck_word import CompleteDyckWords_size
dw = CompleteDyckWords_size(self._size).random_element()
return dw.to_binary_tree_tamari()
def __iter__(self):
'\n A basic generator.\n\n .. TODO:: could be optimized.\n\n TESTS::\n\n sage: BinaryTrees(0).list()\n [.]\n sage: BinaryTrees(1).list()\n [[., .]]\n sage: BinaryTrees(3).list()\n [[., [., [., .]]], [., [[., .], .]], [[., .], [., .]], [[., [., .]], .], [[[., .], .], .]]\n '
if (self._size == 0):
(yield self._element_constructor_())
else:
for i in range(self._size):
for lft in self.__class__(i):
for rgt in self.__class__(((self._size - 1) - i)):
(yield self._element_constructor_([lft, rgt]))
def _element_constructor_(self, *args, **keywords):
'\n EXAMPLES::\n\n sage: S = BinaryTrees(0)\n sage: S([]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: wrong number of nodes\n sage: S(None) # indirect doctest\n .\n\n sage: S = BinaryTrees(1) # indirect doctest\n sage: S([])\n [., .]\n '
res = BinaryTree(*args, **keywords)
if (res.node_number() != self._size):
raise ValueError('wrong number of nodes')
return res
|
class FullBinaryTrees_all(DisjointUnionEnumeratedSets, BinaryTrees):
'\n All full binary trees.\n '
def __init__(self):
'\n TESTS::\n\n sage: from sage.combinat.binary_tree import FullBinaryTrees_all\n sage: FB = FullBinaryTrees_all()\n sage: FB.cardinality()\n +Infinity\n\n sage: it = iter(FB)\n sage: (next(it), next(it), next(it), next(it), next(it))\n (., [., .], [[., .], [., .]], [[., .], [[., .], [., .]]], [[[., .], [., .]], [., .]])\n sage: next(it).parent()\n Binary trees\n sage: FB([])\n [., .]\n\n sage: FB is FullBinaryTrees_all()\n True\n sage: TestSuite(FB).run() # long time\n '
DisjointUnionEnumeratedSets.__init__(self, Family(NonNegativeIntegers(), _full_construction), facade=True, keepkey=False)
def _repr_(self):
'\n TESTS::\n\n sage: BinaryTrees(full=True)\n Full binary trees\n '
return 'Full binary trees'
def __contains__(self, x):
'\n TESTS::\n\n sage: FB = BinaryTrees(full=True)\n sage: 1 in FB\n False\n sage: FB([]) in FB\n True\n '
return (isinstance(x, BinaryTree) and x.is_full())
def _element_constructor_(self, *args, **keywords):
'\n EXAMPLES::\n\n sage: FB = BinaryTrees(full=True)\n sage: FB._element_constructor_([])\n [., .]\n sage: FB([[],[]]) # indirect doctest\n [[., .], [., .]]\n sage: FB(None) # indirect doctest\n .\n sage: FB([None, []]) #indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: not full\n '
res = BinaryTree(*args, **keywords)
if (not res.is_full()):
raise ValueError('not full')
return res
|
def _full_construction(n):
'\n Helper function for the disjoint union construction.\n\n TESTS::\n\n sage: from sage.combinat.binary_tree import _full_construction\n sage: _full_construction(0)\n Full binary trees of size 0\n sage: _full_construction(1)\n Full binary trees of size 1\n sage: _full_construction(2)\n Full binary trees of size 3\n sage: _full_construction(3)\n Full binary trees of size 5\n '
if (n == 0):
return FullBinaryTrees_size(0)
return FullBinaryTrees_size(((2 * n) - 1))
|
class FullBinaryTrees_size(BinaryTrees):
'\n Full binary trees of a fixed size (number of nodes).\n '
def __init__(self, size):
'\n TESTS::\n\n sage: from sage.combinat.binary_tree import FullBinaryTrees_size\n sage: for i in range(1,6):\n ....: TestSuite(BinaryTrees(2*i-1, full=True)).run()\n '
super().__init__(facade=BinaryTrees_all(), category=FiniteEnumeratedSets())
self._size = size
def _repr_(self):
'\n TESTS::\n\n sage: BinaryTrees(3, full=True)\n Full binary trees of size 3\n '
return ('Full binary trees of size %s' % self._size)
def __contains__(self, x):
'\n TESTS::\n\n sage: FB3 = BinaryTrees(3, full=True)\n sage: 1 in FB3\n False\n sage: FB3([[], []]) in FB3\n True\n sage: BinaryTree([[], []]) in FB3\n True\n sage: BinaryTree([None, []]) in FB3\n False\n '
return (isinstance(x, BinaryTree) and (x.node_number() == self._size) and x.is_full())
def _an_element_(self):
'\n TESTS::\n\n sage: BinaryTrees(0, full=True).an_element()\n .\n\n sage: ascii_art(BinaryTrees(5, full=True).an_element())\n _o_\n / \\\n o o\n / \\\n o o\n '
return self.first()
def cardinality(self):
'\n The cardinality of ``self``\n\n This is a Catalan number.\n\n TESTS::\n\n sage: BinaryTrees(0, full=True).cardinality()\n 1\n sage: BinaryTrees(5, full=True).cardinality()\n 2\n sage: BinaryTrees(11, full=True).cardinality()\n 42\n '
if (self._size == 0):
return Integer(1)
from sage.combinat.combinat import catalan_number
return catalan_number(((self._size - 1) // 2))
def random_element(self):
'\n Return a random ``FullBinaryTree`` with uniform probability.\n\n This method generates a random ``DyckWord`` of size `(s-1) / 2`,\n where `s` is the size of ``self``, which uses a bijection between\n Dyck words and binary trees to get a binary tree, and convert it\n to a full binary tree.\n\n EXAMPLES::\n\n sage: BinaryTrees(5, full=True).random_element() # random # needs sage.combinat\n [[], [[], []]]\n sage: BinaryTrees(0, full=True).random_element() # needs sage.combinat\n .\n sage: BinaryTrees(1, full=True).random_element() # needs sage.combinat\n [., .]\n\n TESTS::\n\n sage: B = BinaryTrees(19, full=True)\n sage: all(B.random_element() in B for i in range(20)) # needs sage.combinat\n True\n '
from sage.combinat.dyck_word import CompleteDyckWords_size
if (self._size == 0):
return BinaryTree(None)
dw = CompleteDyckWords_size(((self._size - 1) // 2)).random_element()
return dw.to_binary_tree_tamari().to_full()
def __iter__(self):
'\n A basic generator.\n\n .. TODO:: could be optimized.\n\n TESTS::\n\n sage: BinaryTrees(0, full=True).list()\n [.]\n sage: BinaryTrees(1, full=True).list()\n [[., .]]\n sage: BinaryTrees(7, full=True).list()\n [[[., .], [[., .], [[., .], [., .]]]],\n [[., .], [[[., .], [., .]], [., .]]],\n [[[., .], [., .]], [[., .], [., .]]],\n [[[., .], [[., .], [., .]]], [., .]],\n [[[[., .], [., .]], [., .]], [., .]]]\n '
if (self._size == 0):
(yield self._element_constructor_())
if (self._size == 1):
(yield self._element_constructor_('[.,.]'))
else:
k = ((self._size - 1) // 2)
for i in range(k):
for lft in FullBinaryTrees_size(((2 * i) + 1)):
for rgt in FullBinaryTrees_size(((2 * ((k - 1) - i)) + 1)):
(yield self._element_constructor_([lft, rgt]))
def _element_constructor_(self, *args, **keywords):
'\n EXAMPLES::\n\n sage: FB0 = BinaryTrees(0, full=True)\n sage: FB0(None)\n .\n sage: FB0([])\n Traceback (most recent call last):\n ...\n ValueError: wrong number of nodes\n\n sage: FB1 = BinaryTrees(1, full=True)\n sage: FB1([])\n [., .]\n\n sage: FB5 = BinaryTrees(5, full=True)\n sage: FB5([[], [None, [None, []]]])\n Traceback (most recent call last):\n ...\n ValueError: not full\n '
res = BinaryTree(*args, **keywords)
if (res.node_number() != self._size):
raise ValueError('wrong number of nodes')
if (not res.is_full()):
raise ValueError('not full')
return res
|
class LabelledBinaryTree(AbstractLabelledClonableTree, BinaryTree):
'\n Labelled binary trees.\n\n A labelled binary tree is a binary tree (see :class:`BinaryTree` for\n the meaning of this) with a label assigned to each node.\n The labels need not be integers, nor are they required to be distinct.\n ``None`` can be used as a label.\n\n .. WARNING::\n\n While it is possible to assign values to leaves (not just nodes)\n using this class, these labels are disregarded by various\n methods such as\n :meth:`~sage.combinat.abstract_tree.AbstractLabelledTree.labels`,\n :meth:`~sage.combinat.abstract_tree.AbstractLabelledTree.map_labels`,\n and (ironically)\n :meth:`~sage.combinat.abstract_tree.AbstractLabelledTree.leaf_labels`.\n\n INPUT:\n\n - ``children`` -- ``None`` (default) or a list, tuple or iterable of\n length `2` of labelled binary trees or convertible objects. This\n corresponds to the standard recursive definition of a labelled\n binary tree as being either a leaf, or a pair of:\n\n - a pair of labelled binary trees,\n - and a label.\n\n (The label is specified in the keyword variable ``label``; see\n below.)\n\n Syntactic sugar allows leaving out all but the outermost calls\n of the ``LabelledBinaryTree()`` constructor, so that, e. g.,\n ``LabelledBinaryTree([LabelledBinaryTree(None),LabelledBinaryTree(None)])``\n can be shortened to ``LabelledBinaryTree([None,None])``. However,\n using this shorthand, it is impossible to label any vertex of\n the tree other than the root (because there is no way to pass a\n ``label`` variable without calling ``LabelledBinaryTree``\n explicitly).\n\n It is also allowed to abbreviate ``[None, None]`` by ``[]`` if\n one does not want to label the leaves (which one should not do\n anyway!).\n\n - ``label`` -- (default: ``None``) the label to be put on the root\n of this tree.\n\n - ``check`` -- (default: ``True``) whether checks should be\n performed or not.\n\n .. TODO::\n\n It is currently not possible to use ``LabelledBinaryTree()``\n as a shorthand for ``LabelledBinaryTree(None)`` (in analogy to\n similar syntax in the ``BinaryTree`` class).\n\n EXAMPLES::\n\n sage: LabelledBinaryTree(None)\n .\n sage: LabelledBinaryTree(None, label="ae") # not well supported\n \'ae\'\n sage: LabelledBinaryTree([])\n None[., .]\n sage: LabelledBinaryTree([], label=3) # not well supported\n 3[., .]\n sage: LabelledBinaryTree([None, None])\n None[., .]\n sage: LabelledBinaryTree([None, None], label=5)\n 5[., .]\n sage: LabelledBinaryTree([None, []])\n None[., None[., .]]\n sage: LabelledBinaryTree([None, []], label=4)\n 4[., None[., .]]\n sage: LabelledBinaryTree([[], None])\n None[None[., .], .]\n sage: LabelledBinaryTree("[[], .]", label=False)\n False[None[., .], .]\n sage: LabelledBinaryTree([None, LabelledBinaryTree([None, None], label=4)], label=3)\n 3[., 4[., .]]\n sage: LabelledBinaryTree([None, BinaryTree([None, None])], label=3)\n 3[., None[., .]]\n\n sage: LabelledBinaryTree([[], None, []])\n Traceback (most recent call last):\n ...\n ValueError: this is not a binary tree\n\n sage: LBT = LabelledBinaryTree\n sage: t1 = LBT([[LBT([], label=2), None], None], label=4); t1\n 4[None[2[., .], .], .]\n\n TESTS::\n\n sage: t1 = LabelledBinaryTree([[None, [[],[[], None]]],[[],[]]])\n sage: t2 = LabelledBinaryTree([[[],[]],[]])\n sage: with t1.clone() as t1c:\n ....: t1c[1,1,1] = t2\n sage: t1 == t1c\n False\n\n We check for :trac:`16314`::\n\n sage: t1 = LBT([ LBT([LBT([], label=2),\n ....: LBT([], label=5)], label=6),\n ....: None], label=4); t1\n 4[6[2[., .], 5[., .]], .]\n sage: class Foo(LabelledBinaryTree):\n ....: pass\n sage: t2 = Foo(t1.parent(), t1); t2\n 4[6[2[., .], 5[., .]], .]\n sage: t2.label()\n 4\n sage: t2[0].label()\n 6\n sage: t2.__class__, t2[0].__class__\n (<class \'__main__.Foo\'>, <class \'__main__.Foo\'>)\n '
@staticmethod
def __classcall_private__(cls, *args, **opts):
"\n Ensure that trees created by the sets and directly are the same and\n that they are instances of :class:`LabelledTree`.\n\n TESTS::\n\n sage: issubclass(LabelledBinaryTrees().element_class, LabelledBinaryTree)\n True\n sage: t0 = LabelledBinaryTree([[],[[], None]], label = 3)\n sage: t0.parent()\n Labelled binary trees\n sage: type(t0)\n <class 'sage.combinat.binary_tree.LabelledBinaryTrees_with_category.element_class'>\n "
return cls._auto_parent.element_class(cls._auto_parent, *args, **opts)
@lazy_class_attribute
def _auto_parent(cls):
'\n The automatic parent of the elements of this class.\n\n When calling the constructor of an element of this class, one needs a\n parent. This class attribute specifies which parent is used.\n\n EXAMPLES::\n\n sage: LabelledBinaryTree._auto_parent\n Labelled binary trees\n sage: LabelledBinaryTree([], label = 3).parent()\n Labelled binary trees\n '
return LabelledBinaryTrees()
def _repr_(self):
'\n TESTS::\n\n sage: LBT = LabelledBinaryTree\n sage: t1 = LBT([[LBT([], label=2), None], None], label=4); t1\n 4[None[2[., .], .], .]\n sage: LBT([[],[[], None]], label = 3) # indirect doctest\n 3[None[., .], None[None[., .], .]]\n '
if (not self):
if (self._label is not None):
return repr(self._label)
else:
return '.'
else:
return ('%s%s' % (self._label, self[:]))
def _sort_key(self):
"\n Return a tuple encoding the labelled binary tree ``self``.\n\n The first entry of the tuple is a pair consisting of the\n number of children of the root and the label of the root. Then\n the rest of the tuple is the concatenation of the tuples\n associated to these children (we view the children of\n a tree as trees themselves) from left to right.\n\n This tuple characterizes the labelled tree uniquely, and can\n be used to sort the labelled binary trees provided that the\n labels belong to a type which is totally ordered.\n\n EXAMPLES::\n\n sage: L2 = LabelledBinaryTree([], label='a')\n sage: L3 = LabelledBinaryTree([], label='b')\n sage: T23 = LabelledBinaryTree([L2, L3], label='c')\n sage: T23._sort_key()\n ((2, 'c'), (2, 'a'), (0,), (0,), (2, 'b'), (0,), (0,))\n "
l = len(self)
if (l == 0):
return ((0,),)
resu = ([(l, self.label())] + [u for t in self for u in t._sort_key()])
return tuple(resu)
__hash__ = ClonableArray.__hash__
def binary_search_insert(self, letter):
'\n Return the result of inserting a letter ``letter`` into the\n right strict binary search tree ``self``.\n\n INPUT:\n\n - ``letter`` -- any object comparable with the labels of ``self``\n\n OUTPUT:\n\n The right strict binary search tree ``self`` with ``letter``\n inserted into it according to the binary search insertion\n algorithm.\n\n .. NOTE:: ``self`` is supposed to be a binary search tree.\n This is not being checked!\n\n A right strict binary search tree is defined to be a labelled\n binary tree such that for each node `n` with label `x`,\n every descendant of the left child of `n` has a label `\\leq x`,\n and every descendant of the right child of `n` has a label\n `> x`. (Here, only nodes count as descendants, and every node\n counts as its own descendant too.) Leaves are assumed to have\n no labels.\n\n Given a right strict binary search tree `t` and a letter `i`,\n the result of inserting `i` into `t` (denoted `Ins(i, t)` in\n the following) is defined recursively as follows:\n\n - If `t` is empty, then `Ins(i, t)` is the tree with one node\n only, and this node is labelled with `i`.\n\n - Otherwise, let `j` be the label of the root of `t`. If\n `i > j`, then `Ins(i, t)` is obtained by replacing the\n right child of `t` by `Ins(i, r)` in `t`, where `r` denotes\n the right child of `t`. If `i \\leq j`, then `Ins(i, t)` is\n obtained by replacing the left child of `t` by `Ins(i, l)`\n in `t`, where `l` denotes the left child of `t`.\n\n See, for example, [HNT2005]_ for properties of this algorithm.\n\n .. WARNING::\n\n If `t` is nonempty, then inserting `i` into `t` does not\n change the root label of `t`. Hence, as opposed to\n algorithms like Robinson-Schensted-Knuth, binary\n search tree insertion involves no bumping.\n\n EXAMPLES:\n\n The example from Fig. 2 of [HNT2005]_::\n\n sage: LBT = LabelledBinaryTree\n sage: x = LBT(None)\n sage: x\n .\n sage: x = x.binary_search_insert("b"); x\n b[., .]\n sage: x = x.binary_search_insert("d"); x\n b[., d[., .]]\n sage: x = x.binary_search_insert("e"); x\n b[., d[., e[., .]]]\n sage: x = x.binary_search_insert("a"); x\n b[a[., .], d[., e[., .]]]\n sage: x = x.binary_search_insert("b"); x\n b[a[., b[., .]], d[., e[., .]]]\n sage: x = x.binary_search_insert("d"); x\n b[a[., b[., .]], d[d[., .], e[., .]]]\n sage: x = x.binary_search_insert("a"); x\n b[a[a[., .], b[., .]], d[d[., .], e[., .]]]\n sage: x = x.binary_search_insert("c"); x\n b[a[a[., .], b[., .]], d[d[c[., .], .], e[., .]]]\n\n Other examples::\n\n sage: LBT = LabelledBinaryTree\n sage: LBT(None).binary_search_insert(3)\n 3[., .]\n sage: LBT([], label = 1).binary_search_insert(3)\n 1[., 3[., .]]\n sage: LBT([], label = 3).binary_search_insert(1)\n 3[1[., .], .]\n sage: res = LBT(None)\n sage: for i in [3,1,5,2,4,6]:\n ....: res = res.binary_search_insert(i)\n sage: res\n 3[1[., 2[., .]], 5[4[., .], 6[., .]]]\n '
LT = self.parent()._element_constructor_
if (not self):
return LT([], label=letter, check=False)
elif (letter <= self.label()):
fils = self[0].binary_search_insert(letter)
return LT([fils, self[1]], label=self.label(), check=False)
else:
fils = self[1].binary_search_insert(letter)
return LT([self[0], fils], label=self.label(), check=False)
def semistandard_insert(self, letter):
'\n Return the result of inserting a letter ``letter`` into the\n semistandard tree ``self`` using the bumping algorithm.\n\n INPUT:\n\n - ``letter`` -- any object comparable with the labels of ``self``\n\n OUTPUT:\n\n The semistandard tree ``self`` with ``letter`` inserted into it\n according to the bumping algorithm.\n\n .. NOTE:: ``self`` is supposed to be a semistandard tree.\n This is not being checked!\n\n A semistandard tree is defined to be a labelled binary tree\n such that for each node `n` with label `x`, every descendant of\n the left child of `n` has a label `> x`, and every descendant\n of the right child of `n` has a label `\\geq x`. (Here, only\n nodes count as descendants, and every node counts as its own\n descendant too.) Leaves are assumed to have no labels.\n\n Given a semistandard tree `t` and a letter `i`, the result of\n inserting `i` into `t` (denoted `Ins(i, t)` in the following)\n is defined recursively as follows:\n\n - If `t` is empty, then `Ins(i, t)` is the tree with one node\n only, and this node is labelled with `i`.\n\n - Otherwise, let `j` be the label of the root of `t`. If\n `i \\geq j`, then `Ins(i, t)` is obtained by replacing the\n right child of `t` by `Ins(i, r)` in `t`, where `r` denotes\n the right child of `t`. If `i < j`, then `Ins(i, t)` is\n obtained by replacing the label at the root of `t` by `i`,\n and replacing the left child of `t` by `Ins(j, l)`\n in `t`, where `l` denotes the left child of `t`.\n\n This algorithm is similar to the Robinson-Schensted-Knuth\n insertion algorithm for semistandard Young tableaux.\n\n AUTHORS:\n\n - Darij Grinberg (10 Nov 2013).\n\n EXAMPLES::\n\n sage: LBT = LabelledBinaryTree\n sage: x = LBT(None)\n sage: x\n .\n sage: x = x.semistandard_insert("b"); x\n b[., .]\n sage: x = x.semistandard_insert("d"); x\n b[., d[., .]]\n sage: x = x.semistandard_insert("e"); x\n b[., d[., e[., .]]]\n sage: x = x.semistandard_insert("a"); x\n a[b[., .], d[., e[., .]]]\n sage: x = x.semistandard_insert("b"); x\n a[b[., .], b[d[., .], e[., .]]]\n sage: x = x.semistandard_insert("d"); x\n a[b[., .], b[d[., .], d[e[., .], .]]]\n sage: x = x.semistandard_insert("a"); x\n a[b[., .], a[b[d[., .], .], d[e[., .], .]]]\n sage: x = x.semistandard_insert("c"); x\n a[b[., .], a[b[d[., .], .], c[d[e[., .], .], .]]]\n\n Other examples::\n\n sage: LBT = LabelledBinaryTree\n sage: LBT(None).semistandard_insert(3)\n 3[., .]\n sage: LBT([], label = 1).semistandard_insert(3)\n 1[., 3[., .]]\n sage: LBT([], label = 3).semistandard_insert(1)\n 1[3[., .], .]\n sage: res = LBT(None)\n sage: for i in [3,1,5,2,4,6]:\n ....: res = res.semistandard_insert(i)\n sage: res\n 1[3[., .], 2[5[., .], 4[., 6[., .]]]]\n '
LT = self.parent()._element_constructor_
if (not self):
return LT([], label=letter)
else:
root_label = self.label()
if (letter < root_label):
fils = self[0].semistandard_insert(root_label)
return LT([fils, self[1]], label=letter)
else:
fils = self[1].semistandard_insert(letter)
return LT([self[0], fils], label=root_label)
def right_rotate(self):
'\n Return the result of right rotation applied to the labelled\n binary tree ``self``.\n\n Right rotation on labelled binary trees is defined as\n follows: Let `T` be a labelled binary tree such that the\n left child of the root of `T` is a node. Let\n `C` be the right child of the root of `T`, and let `A`\n and `B` be the left and right children of the left child\n of the root of `T`. (Keep in mind that nodes of trees are\n identified with the subtrees consisting of their\n descendants.) Furthermore, let `y` be the label at the\n root of `T`, and `x` be the label at the left child of the\n root of `T`.\n Then, the right rotation of `T` is the labelled binary\n tree in which the root is labelled `x`, the left child of\n the root is `A`, whereas the right child of the root is a\n node labelled `y` whose left and right children are `B`\n and `C`. In pictures::\n\n | y x |\n | / \\ / \\ |\n | x C -right-rotate-> A y |\n | / \\ / \\ |\n | A B B C |\n\n Right rotation is the inverse operation to left rotation\n (:meth:`left_rotate`).\n\n TESTS::\n\n sage: LB = LabelledBinaryTree\n sage: b = LB([LB([LB([],"A"), LB([],"B")],"x"),LB([],"C")], "y"); b\n y[x[A[., .], B[., .]], C[., .]]\n sage: b.right_rotate()\n x[A[., .], y[B[., .], C[., .]]]\n '
B = self.parent()._element_constructor_
s0 = self[0]
return B([s0[0], B([s0[1], self[1]], self.label())], s0.label())
def left_rotate(self):
'\n Return the result of left rotation applied to the labelled\n binary tree ``self``.\n\n Left rotation on labelled binary trees is defined as\n follows: Let `T` be a labelled binary tree such that the\n right child of the root of `T` is a node. Let\n `A` be the left child of the root of `T`, and let `B`\n and `C` be the left and right children of the right child\n of the root of `T`. (Keep in mind that nodes of trees are\n identified with the subtrees consisting of their\n descendants.) Furthermore, let `x` be the label at the\n root of `T`, and `y` be the label at the right child of the\n root of `T`.\n Then, the left rotation of `T` is the labelled binary tree\n in which the root is labelled `y`, the right child of the\n root is `C`, whereas the left child of the root is a node\n labelled `x` whose left and right children are `A` and `B`.\n In pictures::\n\n | y x |\n | / \\ / \\ |\n | x C <-left-rotate- A y |\n | / \\ / \\ |\n | A B B C |\n\n Left rotation is the inverse operation to right rotation\n (:meth:`right_rotate`).\n\n TESTS::\n\n sage: LB = LabelledBinaryTree\n sage: b = LB([LB([LB([],"A"), LB([],"B")],"x"),LB([],"C")], "y"); b\n y[x[A[., .], B[., .]], C[., .]]\n sage: b == b.right_rotate().left_rotate()\n True\n '
B = self.parent()._element_constructor_
s1 = self[1]
return B([B([self[0], s1[0]], self.label()), s1[1]], s1.label())
def heap_insert(self, l):
'\n Return the result of inserting a letter ``l`` into the binary\n heap (tree) ``self``.\n\n A binary heap is a labelled complete binary tree such that for\n each node, the label at the node is greater or equal to the\n label of each of its child nodes. (More precisely, this is\n called a max-heap.)\n\n For example::\n\n | _7_ |\n | / \\ |\n | 5 6 |\n | / \\ |\n | 3 4 |\n\n is a binary heap.\n\n See :wikipedia:`Binary_heap#Insert` for a description of how to\n insert a letter into a binary heap. The result is another binary\n heap.\n\n INPUT:\n\n - ``letter`` -- any object comparable with the labels of ``self``\n\n .. NOTE::\n\n ``self`` is assumed to be a binary heap (tree). No check is\n performed.\n\n TESTS::\n\n sage: h = LabelledBinaryTree(None)\n sage: h = h.heap_insert(3); ascii_art([h])\n [ 3 ]\n sage: h = h.heap_insert(4); ascii_art([h])\n [ 4 ]\n [ / ]\n [ 3 ]\n sage: h = h.heap_insert(6); ascii_art([h])\n [ 6 ]\n [ / \\ ]\n [ 3 4 ]\n sage: h = h.heap_insert(2); ascii_art([h])\n [ 6 ]\n [ / \\ ]\n [ 3 4 ]\n [ / ]\n [ 2 ]\n sage: ascii_art([h.heap_insert(5)])\n [ _6_ ]\n [ / \\ ]\n [ 5 4 ]\n [ / \\ ]\n [ 2 3 ]\n '
B = self.parent()._element_constructor_
if self.is_empty():
return B([], l)
if (self.label() < l):
label_root = l
label_insert = self.label()
else:
label_root = self.label()
label_insert = l
(L, R) = self
dL = L.depth()
dR = R.depth()
if (dL > dR):
if L.is_perfect():
return B([L, R.heap_insert(label_insert)], label_root)
return B([L.heap_insert(label_insert), R], label_root)
if R.is_perfect():
return B([L.heap_insert(label_insert), R], label_root)
return B([L, R.heap_insert(label_insert)], label_root)
_UnLabelled = BinaryTree
|
class LabelledBinaryTrees(LabelledOrderedTrees):
'\n This is a parent stub to serve as a factory class for trees with various\n labels constraints.\n '
def _repr_(self):
'\n TESTS::\n\n sage: LabelledBinaryTrees() # indirect doctest\n Labelled binary trees\n '
return 'Labelled binary trees'
def _an_element_(self):
'\n Return a labelled binary tree.\n\n EXAMPLES::\n\n sage: LabelledBinaryTrees().an_element() # indirect doctest\n toto[42[3[., .], 3[., .]], 5[None[., .], None[., .]]]\n '
LT = self._element_constructor_
t = LT([], label=3)
t1 = LT([t, t], label=42)
t2 = LT([[], []], label=5)
return LT([t1, t2], label='toto')
def unlabelled_trees(self):
'\n Return the set of unlabelled trees associated to ``self``.\n\n EXAMPLES::\n\n sage: LabelledBinaryTrees().unlabelled_trees()\n Binary trees\n\n This is used to compute the shape::\n\n sage: t = LabelledBinaryTrees().an_element().shape(); t\n [[[., .], [., .]], [[., .], [., .]]]\n sage: t.parent()\n Binary trees\n\n TESTS::\n\n sage: t = LabelledBinaryTrees().an_element()\n sage: t.canonical_labelling()\n 4[2[1[., .], 3[., .]], 6[5[., .], 7[., .]]]\n '
return BinaryTrees_all()
def labelled_trees(self):
'\n Return the set of labelled trees associated to ``self``.\n\n EXAMPLES::\n\n sage: LabelledBinaryTrees().labelled_trees()\n Labelled binary trees\n '
return self
Element = LabelledBinaryTree
|
def binary_search_tree_shape(w, left_to_right=True):
'\n Direct computation of the binary search tree shape of a list of integers.\n\n INPUT:\n\n - ``w`` -- a list of integers\n\n - ``left_to_right`` -- boolean (default ``True``)\n\n OUTPUT: a non labelled binary tree\n\n This is used under the same name as a method for permutations.\n\n EXAMPLES::\n\n sage: from sage.combinat.binary_tree import binary_search_tree_shape\n sage: binary_search_tree_shape([1,4,3,2])\n [., [[[., .], .], .]]\n sage: binary_search_tree_shape([5,1,3,2])\n [[., [[., .], .]], .]\n\n By passing the option ``left_to_right=False`` one can have\n the insertion going from right to left::\n\n sage: binary_search_tree_shape([1,6,4,2], False)\n [[., .], [., [., .]]]\n\n TESTS::\n\n sage: t = Permutations(30).random_element()\n sage: t.binary_search_tree().shape() == binary_search_tree_shape(t)\n True\n sage: t.binary_search_tree(False).shape() == binary_search_tree_shape(t, False)\n True\n '
if (not w):
return BinaryTree()
if left_to_right:
root = w[0]
else:
root = w[(- 1)]
left = [x for x in w if (x < root)]
right = [x for x in w if (x > root)]
return BinaryTree([binary_search_tree_shape(left, left_to_right), binary_search_tree_shape(right, left_to_right)])
|
class BlobDiagram(Element):
'\n A blob diagram.\n\n A blob diagram consists of a perfect matching of the set\n `\\{1, \\ldots, n\\} \\sqcup \\{-1, \\ldots, -n\\}` such that the result\n is a noncrossing matching (a :class:`Temperley-Lieb diagram\n <sage.combinat.diagram_algebras.TemperleyLiebDiagram>`), divided\n into two sets of pairs: one for the pairs with blobs and one for\n those without. The blobed pairs must either be either the leftmost\n propagating strand or to the left of it and not nested.\n '
def __init__(self, parent, marked, unmarked):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: from sage.combinat.blob_algebra import BlobDiagrams\n sage: BD4 = BlobDiagrams(4)\n sage: B = BD4([[1,-3]], [[2,-4], [3,4], [-1,-2]])\n sage: TestSuite(B).run()\n '
Element.__init__(self, parent)
self.marked = tuple(sorted([tuple(sorted(pair)) for pair in marked]))
self.unmarked = tuple(sorted([tuple(sorted(pair)) for pair in unmarked]))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.blob_algebra import BlobDiagrams\n sage: BD4 = BlobDiagrams(4)\n sage: BD4([[1,-3]], [[2,-4], [3,4], [-1,-2]])\n ({{-3, 1}}, {{-4, 2}, {-2, -1}, {3, 4}})\n '
return '({{{}}}, {{{}}})'.format(', '.join(((('{' + repr(X)[1:(- 1)]) + '}') for X in self.marked)), ', '.join(((('{' + repr(X)[1:(- 1)]) + '}') for X in self.unmarked)))
def __hash__(self):
'\n Return the hash of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.blob_algebra import BlobDiagrams\n sage: BD4 = BlobDiagrams(4)\n sage: B = BD4([[1,-3]], [[2,-4], [3,4], [-1,-2]])\n sage: hash(B) in [hash(D) for D in BD4]\n True\n sage: len(set([hash(D) for D in BD4])) == len(BD4)\n True\n '
return hash((self.marked, self.unmarked))
def _richcmp_(self, other, op):
'\n Compare ``self`` to ``other`` with operation ``op``.\n\n EXAMPLES::\n\n sage: from sage.combinat.blob_algebra import BlobDiagrams\n sage: BD4 = BlobDiagrams(4)\n sage: B = BD4([[1,-3]], [[2,-4], [3,4], [-1,-2]])\n sage: any(B == D for D in BD4)\n True\n sage: B2 = BD4([], [[1,-3], [2,-4], [3,4], [-1,-2]])\n sage: B == B2\n False\n sage: B != B2\n True\n sage: sorted(BlobDiagrams(3))\n [({}, {{-3, -2}, {-1, 1}, {2, 3}}),\n ({}, {{-3, -2}, {-1, 3}, {1, 2}}),\n ({}, {{-3, 1}, {-2, -1}, {2, 3}}),\n ({}, {{-3, 3}, {-2, -1}, {1, 2}}),\n ({}, {{-3, 3}, {-2, 2}, {-1, 1}}),\n ({{-3, 1}}, {{-2, -1}, {2, 3}}),\n ({{-3, 3}}, {{-2, -1}, {1, 2}}),\n ({{-2, -1}}, {{-3, 1}, {2, 3}}),\n ({{-2, -1}}, {{-3, 3}, {1, 2}}),\n ({{-1, 1}}, {{-3, -2}, {2, 3}}),\n ({{-1, 1}}, {{-3, 3}, {-2, 2}}),\n ({{-1, 3}}, {{-3, -2}, {1, 2}}),\n ({{1, 2}}, {{-3, -2}, {-1, 3}}),\n ({{1, 2}}, {{-3, 3}, {-2, -1}}),\n ({{-3, 1}, {-2, -1}}, {{2, 3}}),\n ({{-3, 3}, {-2, -1}}, {{1, 2}}),\n ({{-3, 3}, {1, 2}}, {{-2, -1}}),\n ({{-2, -1}, {1, 2}}, {{-3, 3}}),\n ({{-1, 3}, {1, 2}}, {{-3, -2}}),\n ({{-3, 3}, {-2, -1}, {1, 2}}, {})]\n '
return richcmp((len(self.marked), self.marked, self.unmarked), (len(other.marked), other.marked, other.unmarked), op)
def temperley_lieb_diagram(self):
'\n Return the Temperley-Lieb diagram corresponding to ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.blob_algebra import BlobDiagrams\n sage: BD4 = BlobDiagrams(4)\n sage: B = BD4([[1,-3]], [[2,-4], [3,4], [-1,-2]])\n sage: B.temperley_lieb_diagram()\n {{-4, 2}, {-3, 1}, {-2, -1}, {3, 4}}\n '
return self.parent()._TL_diagrams((self.marked + self.unmarked))
|
class BlobDiagrams(Parent, UniqueRepresentation):
'\n The set of all blob diagrams.\n '
def __init__(self, n):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: from sage.combinat.blob_algebra import BlobDiagrams\n sage: BD4 = BlobDiagrams(4)\n sage: TestSuite(BD4).run()\n '
self._n = n
self._TL_diagrams = TemperleyLiebDiagrams(n)
Parent.__init__(self, category=FiniteEnumeratedSets())
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.blob_algebra import BlobDiagrams\n sage: BlobDiagrams(4)\n Blob diagrams of order 4\n '
return 'Blob diagrams of order {}'.format(self._n)
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.blob_algebra import BlobDiagrams\n sage: BD4 = BlobDiagrams(4)\n sage: BD4.cardinality()\n 70\n '
return binomial((2 * self._n), self._n)
def order(self):
'\n Return the order of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.blob_algebra import BlobDiagrams\n sage: BD4 = BlobDiagrams(4)\n sage: BD4.order()\n 4\n '
return self._n
@cached_method
def base_set(self):
'\n Return the base set of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.blob_algebra import BlobDiagrams\n sage: BD4 = BlobDiagrams(4)\n sage: sorted(BD4.base_set())\n [-4, -3, -2, -1, 1, 2, 3, 4]\n '
return frozenset(range(1, (self._n + 1))).union(range((- self._n), 0))
def _element_constructor_(self, marked, unmarked=None):
'\n Construct an element of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.blob_algebra import BlobDiagrams\n sage: BD4 = BlobDiagrams(4)\n sage: BD4([[1,-3]], [[-1,-2], [2,3], [-4,4]])\n ({{-3, 1}}, {{-4, 4}, {-2, -1}, {2, 3}})\n sage: BD4([[(1,-3)], ([-1,-2], (2,3), [-4,4])])\n ({{-3, 1}}, {{-4, 4}, {-2, -1}, {2, 3}})\n '
if (unmarked is None):
(marked, unmarked) = marked
ret = self.element_class(self, marked, unmarked)
if (ret not in self):
raise ValueError('not a blob diagram of order {}'.format(self._n))
return ret
def __contains__(self, X):
'\n Check if ``X`` is contained in ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.blob_algebra import BlobDiagrams\n sage: BD4 = BlobDiagrams(4)\n sage: BD4([[1,-3], [-1,-2]], [[2,-4], [3,4]]) # indirect doctest\n ({{-3, 1}, {-2, -1}}, {{-4, 2}, {3, 4}})\n sage: BD4([[1,4], [-1,-2], [-3,-4]], [[2,3]]) # indirect doctest\n ({{-4, -3}, {-2, -1}, {1, 4}}, {{2, 3}})\n\n sage: BD4([[1,-2], [-1,-3]], [[2,-4], [3,4]]) # crossing strands\n Traceback (most recent call last):\n ...\n ValueError: not a blob diagram of order 4\n sage: BD4([[1,-4], [-1,-2]], [[2,-3], [3,4]]) # crossing strands\n Traceback (most recent call last):\n ...\n ValueError: not a blob diagram of order 4\n sage: BD4([[1,-2], [-1,-3]], [[3,-4], [2,4]]) # crossing strands\n Traceback (most recent call last):\n ...\n ValueError: not a blob diagram of order 4\n sage: BD4([[1,-3], [-1,-2], [3,4]], [[2,-4]]) # trapped blob cup\n Traceback (most recent call last):\n ...\n ValueError: not a blob diagram of order 4\n sage: BD4([[-1,3], [1,2], [-3,-4]], [[-2,4]]) # trapped blob cap\n Traceback (most recent call last):\n ...\n ValueError: not a blob diagram of order 4\n sage: BD4([[1,4], [-1,-2], [-3,-4], [2,3]], []) # nested blob cup\n Traceback (most recent call last):\n ...\n ValueError: not a blob diagram of order 4\n sage: BD4([[-1,-4], [1,2], [3,4], [-2,-3]], []) # nested blob cap\n Traceback (most recent call last):\n ...\n ValueError: not a blob diagram of order 4\n sage: BD4([[3,-3]], [[1,-1],[2,-2],[4,-4]]) # trapped propagating line\n Traceback (most recent call last):\n ...\n ValueError: not a blob diagram of order 4\n '
if (not isinstance(X, BlobDiagram)):
return False
TL = (X.marked + X.unmarked)
if (TL not in self._TL_diagrams):
return False
for (x, y) in X.marked:
if (x > 0):
for P in TL:
if (P[1] < 0):
continue
if (P[1] < x):
if (P[0] < 0):
return False
elif (0 < P[0] < x):
return False
elif (y < 0):
for P in TL:
if (P[0] > 0):
continue
if (P[0] > y):
if (P[1] > 0):
return False
elif (0 > P[1] > y):
return False
elif any((((P[0] < 0) and (P[1] > 0) and (P[1] < y)) for P in TL)):
return False
return True
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.blob_algebra import BlobDiagrams\n sage: BD3 = BlobDiagrams(3)\n sage: sorted(BD3)\n [({}, {{-3, -2}, {-1, 1}, {2, 3}}),\n ({}, {{-3, -2}, {-1, 3}, {1, 2}}),\n ({}, {{-3, 1}, {-2, -1}, {2, 3}}),\n ({}, {{-3, 3}, {-2, -1}, {1, 2}}),\n ({}, {{-3, 3}, {-2, 2}, {-1, 1}}),\n ({{-3, 1}}, {{-2, -1}, {2, 3}}),\n ({{-3, 3}}, {{-2, -1}, {1, 2}}),\n ({{-2, -1}}, {{-3, 1}, {2, 3}}),\n ({{-2, -1}}, {{-3, 3}, {1, 2}}),\n ({{-1, 1}}, {{-3, -2}, {2, 3}}),\n ({{-1, 1}}, {{-3, 3}, {-2, 2}}),\n ({{-1, 3}}, {{-3, -2}, {1, 2}}),\n ({{1, 2}}, {{-3, -2}, {-1, 3}}),\n ({{1, 2}}, {{-3, 3}, {-2, -1}}),\n ({{-3, 1}, {-2, -1}}, {{2, 3}}),\n ({{-3, 3}, {-2, -1}}, {{1, 2}}),\n ({{-3, 3}, {1, 2}}, {{-2, -1}}),\n ({{-2, -1}, {1, 2}}, {{-3, 3}}),\n ({{-1, 3}, {1, 2}}, {{-3, -2}}),\n ({{-3, 3}, {-2, -1}, {1, 2}}, {})]\n '
for D in DyckWords(self._n):
markable = set()
unmarked = []
unpaired = []
for (i, d) in enumerate(D):
if (i >= self._n):
i = (((- 2) * self._n) + i)
else:
i += 1
if (d == 1):
unpaired.append(i)
else:
m = unpaired.pop()
if (not unpaired):
markable.add((m, i))
else:
unmarked.append((m, i))
for X in powerset(markable):
(yield self.element_class(self, X, (unmarked + list(markable.difference(X)))))
Element = BlobDiagram
|
class BlobAlgebra(CombinatorialFreeModule):
'\n The blob algebra.\n\n The *blob algebra* (also known as the Temperley-Lieb algebra of type `B`\n in [ILZ2018]_, but is a quotient of the Temperley-Lieb algebra of type `B`\n defined in [Graham1985]_) is a diagram-type algebra introduced in\n [MS1994]_ whose basis consists of :class:`Temperley-Lieb diagrams\n <sage.combinat.diagram_algebras.TemperleyLiebDiagram>`, noncrossing\n perfect matchings, that may contain blobs on strands that can be\n deformed so that the blob touches the left side (which we can think of\n as a frozen pole).\n\n The form we give here has 3 parameters, the natural one from the\n :class:`Temperley-Lieb algebra <sage.combinat.diagram_algebras.TemperleyLiebAlgebra>`,\n one for the idempotent relation, and one for a loop with a blob.\n\n INPUT:\n\n - ``k`` -- the order\n - ``q1`` -- the loop parameter\n - ``q2`` -- the idempotent parameter\n - ``q3`` -- the blob loop parameter\n\n EXAMPLES::\n\n sage: R.<q,r,s> = ZZ[]\n sage: B4 = algebras.Blob(4, q, r, s)\n sage: B = sorted(B4.basis())\n sage: B[14]\n B({{-4, -3}}, {{-2, -1}, {1, 2}, {3, 4}})\n sage: B[40]\n B({{3, 4}}, {{-4, -3}, {-2, -1}, {1, 2}})\n sage: B[14] * B[40]\n q*r*s*B({}, {{-4, -3}, {-2, -1}, {1, 2}, {3, 4}})\n\n REFERENCES:\n\n - [MS1994]_\n - [ILZ2018]_\n '
@staticmethod
def __classcall_private__(cls, k, q1, q2, q3, base_ring=None, prefix='B'):
"\n Normalize input to ensure a unique representation.\n\n TESTS::\n\n sage: R.<q,r,s> = ZZ[]\n sage: B3 = algebras.Blob(3, q, r, s)\n sage: Bp = algebras.Blob(3, q, r, s, R, prefix='B')\n sage: B3 is Bp\n True\n "
if (base_ring is None):
base_ring = get_coercion_model().common_parent(q1, q2, q3)
q1 = base_ring(q1)
q2 = base_ring(q2)
q3 = base_ring(q3)
return super().__classcall__(cls, k, q1, q2, q3, base_ring, prefix)
def __init__(self, k, q1, q2, q3, base_ring, prefix):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: R.<q,r,s> = ZZ[]\n sage: B4 = algebras.Blob(4, q, r, s)\n sage: TestSuite(B4).run()\n\n sage: B3 = algebras.Blob(3, q, r, s)\n sage: B = list(B3.basis())\n sage: TestSuite(B3).run(elements=B) # long time\n '
self._q1 = q1
self._q2 = q2
self._q3 = q3
diagrams = BlobDiagrams(k)
cat = Algebras(base_ring.category()).FiniteDimensional().WithBasis()
CombinatorialFreeModule.__init__(self, base_ring, diagrams, category=cat, prefix=prefix, bracket=False)
def _ascii_art_term(self, diagram):
'\n Return an ascii art representation of ``diagram``.\n\n EXAMPLES::\n\n sage: R.<q,r,s> = ZZ[]\n sage: B2 = algebras.Blob(2, q, r, s)\n sage: x = B2.an_element()\n sage: ascii_art(x) # indirect doctest\n o o o o o o\n 2* `-` + 3* `-` + 2* `0`\n .-. .0. .-.\n o o o o o o\n '
return TL_diagram_ascii_art((diagram.marked + diagram.unmarked), use_unicode=False, blobs=diagram.marked)
def _unicode_art_term(self, diagram):
'\n Return a unicode art representation of ``diagram``.\n\n EXAMPLES::\n\n sage: R.<q,r,s> = ZZ[]\n sage: B2 = algebras.Blob(2, q, r, s)\n sage: x = B2.an_element()\n sage: unicode_art(x) # indirect doctest\n ⚬ ⚬ ⚬ ⚬ ⚬ ⚬\n 2* ╰─╯ + 3* ╰─╯ + 2* ╰●╯\n ╭─╮ ╭●╮ ╭─╮\n ⚬ ⚬ ⚬ ⚬ ⚬ ⚬\n '
return TL_diagram_ascii_art((diagram.marked + diagram.unmarked), use_unicode=True, blobs=diagram.marked)
def _latex_term(self, diagram):
'\n Return a latex representation of ``diagram``.\n\n EXAMPLES::\n\n sage: R.<q,r,s> = ZZ[]\n sage: B2 = algebras.Blob(2, q, r, s)\n sage: latex(B2.an_element()) # indirect doctest\n 2 \\begin{tikzpicture}[scale = 0.5,thick, baseline={(0,-1ex/2)}]\n \\tikzstyle{vertex} = [shape = circle, minimum size = 7pt, inner sep = 1pt]\n \\node[vertex] (G--2) at (1.5, -1) [shape = circle, draw] {};\n \\node[vertex] (G--1) at (0.0, -1) [shape = circle, draw] {};\n \\node[vertex] (G-1) at (0.0, 1) [shape = circle, draw] {};\n \\node[vertex] (G-2) at (1.5, 1) [shape = circle, draw] {};\n \\draw[] (G--2) .. controls +(-0.5, 0.5) and +(0.5, 0.5) .. (G--1);\n \\draw[] (G-1) .. controls +(0.5, -0.5) and +(-0.5, -0.5) .. (G-2);\n \\end{tikzpicture}\n + 3 \\begin{tikzpicture}[scale = 0.5,thick, baseline={(0,-1ex/2)}]\n \\tikzstyle{vertex} = [shape = circle, minimum size = 7pt, inner sep = 1pt]\n \\node[vertex] (G--2) at (1.5, -1) [shape = circle, draw] {};\n \\node[vertex] (G--1) at (0.0, -1) [shape = circle, draw] {};\n \\node[vertex] (G-1) at (0.0, 1) [shape = circle, draw] {};\n \\node[vertex] (G-2) at (1.5, 1) [shape = circle, draw] {};\n \\draw[blue,very thick] (G--2) .. controls +(-0.5, 0.5) and +(0.5, 0.5) .. node[midway,circle,fill,scale=0.6] {} (G--1);\n \\draw[] (G-1) .. controls +(0.5, -0.5) and +(-0.5, -0.5) .. (G-2);\n \\end{tikzpicture}\n + 2 \\begin{tikzpicture}[scale = 0.5,thick, baseline={(0,-1ex/2)}]\n \\tikzstyle{vertex} = [shape = circle, minimum size = 7pt, inner sep = 1pt]\n \\node[vertex] (G-1) at (0.0, 1) [shape = circle, draw] {};\n \\node[vertex] (G-2) at (1.5, 1) [shape = circle, draw] {};\n \\node[vertex] (G--2) at (1.5, -1) [shape = circle, draw] {};\n \\node[vertex] (G--1) at (0.0, -1) [shape = circle, draw] {};\n \\draw[blue,very thick] (G-1) .. controls +(0.5, -0.5) and +(-0.5, -0.5) .. node[midway,circle,fill,scale=0.6] {} (G-2);\n \\draw[] (G--2) .. controls +(-0.5, 0.5) and +(0.5, 0.5) .. (G--1);\n \\end{tikzpicture}\n '
def edge_options(P):
if (P[1] < P[0]):
P = [P[1], P[0]]
if (tuple(P) in diagram.marked):
return 'blue,very thick'
return ''
def edge_additions(P):
if (P[1] < P[0]):
P = [P[1], P[0]]
if (tuple(P) in diagram.marked):
return 'node[midway,circle,fill,scale=0.6] {} '
return ''
return diagram_latex((diagram.marked + diagram.unmarked), edge_options=edge_options, edge_additions=edge_additions)
def order(self):
'\n Return the order of ``self``.\n\n The order of a partition algebra is defined as half of the number\n of nodes in the diagrams.\n\n EXAMPLES::\n\n sage: R.<q,r,s> = ZZ[]\n sage: B4 = algebras.Blob(4, q, r, s)\n sage: B4.order()\n 4\n '
return self._indices.order()
@cached_method
def one_basis(self):
'\n Return the index of the basis element `1`.\n\n EXAMPLES::\n\n sage: R.<q,r,s> = ZZ[]\n sage: B4 = algebras.Blob(4, q, r, s)\n sage: B4.one_basis()\n ({}, {{-4, 4}, {-3, 3}, {-2, 2}, {-1, 1}})\n '
B = self._indices
return B.element_class(B, [], [[i, (- i)] for i in range(1, (self.order() + 1))])
def product_on_basis(self, top, bot):
'\n Return the product of the basis elements indexed by ``top``\n and ``bot``.\n\n EXAMPLES::\n\n sage: R.<q,r,s> = ZZ[]\n sage: B4 = algebras.Blob(4, q, r, s)\n sage: B = B4.basis()\n sage: BD = sorted(B.keys())\n sage: BD[14]\n ({{-4, -3}}, {{-2, -1}, {1, 2}, {3, 4}})\n sage: BD[40]\n ({{3, 4}}, {{-4, -3}, {-2, -1}, {1, 2}})\n sage: B4.product_on_basis(BD[14], BD[40])\n q*r*s*B({}, {{-4, -3}, {-2, -1}, {1, 2}, {3, 4}})\n sage: all(len((x*y).support()) == 1 for x in B for y in B)\n True\n '
ret_lists = [[], []]
coeff = self.base_ring().one()
top_marked = set(top.marked)
top_unmarked = set(top.unmarked)
bot_marked = set(bot.marked)
bot_unmarked = set(bot.unmarked)
for (top_set, is_unmarked) in [(top_marked, 0), (top_unmarked, 1)]:
while top_set:
(cur, stop) = top_set.pop()
unmarked = is_unmarked
if (cur > 0):
ret_lists[unmarked].append((cur, stop))
continue
anchored = bool((stop > 0))
while (anchored or (cur != stop)):
cur = (- cur)
for X in bot_marked:
if (cur in X):
if unmarked:
unmarked = 0
else:
coeff *= self._q2
prev = cur
cur = X[(1 - X.index(prev))]
bot_marked.remove(X)
break
for X in bot_unmarked:
if (cur in X):
prev = cur
cur = X[(1 - X.index(prev))]
bot_unmarked.remove(X)
break
if (cur < 0):
if anchored:
ret_lists[unmarked].append((stop, cur))
break
else:
anchored = True
(stop, cur) = (cur, stop)
continue
cur = (- cur)
for X in top_marked:
if (cur in X):
if unmarked:
unmarked = 0
else:
coeff *= self._q2
prev = cur
cur = X[(1 - X.index(prev))]
top_marked.remove(X)
break
for X in top_unmarked:
if (cur in X):
prev = cur
cur = X[(1 - X.index(prev))]
top_unmarked.remove(X)
break
if (cur > 0):
if anchored:
ret_lists[unmarked].append((stop, cur))
break
else:
anchored = True
(stop, cur) = (cur, stop)
if (cur == stop):
if unmarked:
coeff *= self._q1
else:
coeff *= self._q3
ret_lists[0].extend(bot_marked)
ret_lists[1].extend(bot_unmarked)
if (coeff == 0):
return self.zero()
diagram = self._indices.element_class(self._indices, ret_lists[0], ret_lists[1])
return self._from_dict({diagram: coeff}, remove_zeros=False)
|
class CartesianProduct_iters(EnumeratedSetFromIterator):
"\n Cartesian product of finite sets.\n\n This class will soon be deprecated (see :trac:`18411` and :trac:`19195`).\n One should instead use the functorial construction\n :class:`cartesian_product <sage.categories.cartesian_product.CartesianProductFunctor>`.\n The main differences in behavior are:\n\n - construction: ``CartesianProduct`` takes as many argument as\n there are factors whereas ``cartesian_product`` takes a single\n list (or iterable) of factors;\n\n - representation of elements: elements are represented by plain\n Python list for ``CartesianProduct`` versus a custom element\n class for ``cartesian_product``;\n\n - membership testing: because of the above, plain Python lists are\n not considered as elements of a ``cartesian_product``.\n\n All of these is illustrated in the examples below.\n\n EXAMPLES::\n\n sage: F1 = ['a', 'b']\n sage: F2 = [1, 2, 3, 4]\n sage: F3 = Permutations(3)\n sage: from sage.combinat.cartesian_product import CartesianProduct_iters\n sage: C = CartesianProduct_iters(F1, F2, F3)\n sage: c = cartesian_product([F1, F2, F3])\n\n sage: type(C.an_element())\n <class 'list'>\n sage: type(c.an_element())\n <class 'sage.sets.cartesian_product.CartesianProduct_with_category.element_class'>\n\n sage: l = ['a', 1, Permutation([3,2,1])]\n sage: l in C\n True\n sage: l in c\n False\n sage: elt = c(l)\n sage: elt\n ('a', 1, [3, 2, 1])\n sage: elt in c\n True\n sage: elt.parent() is c\n True\n "
def __init__(self, *iters):
"\n TESTS::\n\n sage: from sage.combinat.cartesian_product import CartesianProduct_iters\n sage: cp = CartesianProduct_iters([1,2],[3,4]); cp\n Cartesian product of [1, 2], [3, 4]\n sage: loads(dumps(cp)) == cp\n True\n sage: TestSuite(cp).run(skip='_test_an_element')\n\n Check that :trac:`24558` is fixed::\n\n sage: from sage.combinat.cartesian_product import CartesianProduct_iters\n sage: from sage.sets.set_from_iterator import EnumeratedSetFromIterator\n sage: I = EnumeratedSetFromIterator(Integers)\n sage: CartesianProduct_iters(I, I)\n Cartesian product of {0, 1, -1, 2, -2, ...}, {0, 1, -1, 2, -2, ...}\n "
self.iters = iters
self._mrange = xmrange_iter(iters)
category = EnumeratedSets()
try:
category = (category.Finite() if self.is_finite() else category.Infinite())
except ValueError:
pass
def iterfunc():
return self.__iterate__()
name = ('Cartesian product of ' + ', '.join(map(str, self.iters)))
EnumeratedSetFromIterator.__init__(self, iterfunc, name=name, category=category, cache=False)
def __contains__(self, x):
'\n EXAMPLES::\n\n sage: from sage.combinat.cartesian_product import CartesianProduct_iters\n sage: cp = CartesianProduct_iters([1,2],[3,4])\n sage: [1,3] in cp\n True\n sage: [1,2] in cp\n False\n sage: [1, 3, 1] in cp\n False\n\n Note that it differs with the behavior of Cartesian products::\n\n sage: cp = cartesian_product([[1,2], [3,4]])\n sage: [1,3] in cp\n False\n '
try:
return ((len(x) == len(self.iters)) and all(((x[i] in self.iters[i]) for i in range(len(self.iters)))))
except (TypeError, IndexError):
return False
def __reduce__(self):
'\n Support for pickle.\n\n TESTS::\n\n sage: cp = cartesian_product([[1,2],range(9)])\n sage: loads(dumps(cp)) == cp\n True\n '
return (self.__class__, self.iters)
def __repr__(self):
'\n EXAMPLES::\n\n sage: from sage.combinat.cartesian_product import CartesianProduct_iters\n sage: CartesianProduct_iters(list(range(2)), list(range(3)))\n Cartesian product of [0, 1], [0, 1, 2]\n '
return ('Cartesian product of ' + ', '.join(map(str, self.iters)))
def cardinality(self):
'\n Returns the number of elements in the Cartesian product of\n everything in \\*iters.\n\n EXAMPLES::\n\n sage: from sage.combinat.cartesian_product import CartesianProduct_iters\n sage: CartesianProduct_iters(range(2), range(3)).cardinality()\n 6\n sage: CartesianProduct_iters(range(2), range(3)).cardinality()\n 6\n sage: CartesianProduct_iters(range(2), range(3), range(4)).cardinality()\n 24\n\n This works correctly for infinite objects::\n\n sage: CartesianProduct_iters(ZZ, QQ).cardinality()\n +Infinity\n sage: CartesianProduct_iters(ZZ, []).cardinality()\n 0\n '
return self._mrange.cardinality()
def __len__(self):
'\n Return the number of elements of the Cartesian product.\n\n OUTPUT:\n\n An ``int``, the number of elements in the Cartesian product. If the\n number of elements is infinite or does not fit into a python ``int``, a\n :class:`TypeError` is raised.\n\n .. SEEALSO::\n\n :meth:`cardinality`\n\n EXAMPLES::\n\n sage: from sage.combinat.cartesian_product import CartesianProduct_iters\n sage: C = CartesianProduct_iters(range(3), range(4))\n sage: len(C)\n 12\n sage: C = CartesianProduct_iters(ZZ, QQ)\n sage: len(C)\n Traceback (most recent call last):\n ...\n TypeError: cardinality does not fit into a Python int\n sage: C = CartesianProduct_iters(ZZ, [])\n sage: len(C)\n 0\n '
return len(self._mrange)
def list(self):
"\n Returns\n\n EXAMPLES::\n\n sage: from sage.combinat.cartesian_product import CartesianProduct_iters\n sage: CartesianProduct_iters(range(3), range(3)).list()\n [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]\n sage: CartesianProduct_iters('dog', 'cat').list()\n [['d', 'c'],\n ['d', 'a'],\n ['d', 't'],\n ['o', 'c'],\n ['o', 'a'],\n ['o', 't'],\n ['g', 'c'],\n ['g', 'a'],\n ['g', 't']]\n "
return [e for e in self]
def __iterate__(self):
"\n An iterator for the elements in the Cartesian product of the\n iterables \\*iters.\n\n From Recipe 19.9 in the Python Cookbook by Alex Martelli and David\n Ascher.\n\n EXAMPLES::\n\n sage: from sage.combinat.cartesian_product import CartesianProduct_iters\n sage: [e for e in CartesianProduct_iters(range(3), range(3))]\n [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]\n sage: [e for e in CartesianProduct_iters('dog', 'cat')]\n [['d', 'c'],\n ['d', 'a'],\n ['d', 't'],\n ['o', 'c'],\n ['o', 'a'],\n ['o', 't'],\n ['g', 'c'],\n ['g', 'a'],\n ['g', 't']]\n "
return iter(self._mrange)
def is_finite(self):
'\n The Cartesian product is finite if all of its inputs are\n finite, or if any input is empty.\n\n EXAMPLES::\n\n sage: from sage.combinat.cartesian_product import CartesianProduct_iters\n sage: CartesianProduct_iters(ZZ, []).is_finite()\n True\n sage: CartesianProduct_iters(4,4).is_finite()\n Traceback (most recent call last):\n ...\n ValueError: unable to determine whether this product is finite\n '
finites = [_is_finite(L, fallback=None) for L in self.iters]
if any(((f is None) for f in finites)):
raise ValueError('unable to determine whether this product is finite')
if all(((f is True) for f in finites)):
return True
lens = [_len(L) for L in self.iters]
if any(((l == 0) for l in lens)):
return True
return False
def unrank(self, x):
'\n For finite Cartesian products, we can reduce unrank to the\n constituent iterators.\n\n EXAMPLES::\n\n sage: from sage.combinat.cartesian_product import CartesianProduct_iters\n sage: C = CartesianProduct_iters(range(1000), range(1000), range(1000))\n sage: C[238792368]\n [238, 792, 368]\n\n Check for :trac:`15919`::\n\n sage: FF = IntegerModRing(29)\n sage: C = CartesianProduct_iters(FF, FF, FF)\n sage: C.unrank(0)\n [0, 0, 0]\n '
try:
lens = [_len(it) for it in self.iters]
except (TypeError, AttributeError):
return CartesianProduct_iters.unrank(self, x)
positions = []
for n in lens:
if (n is infinity):
return CartesianProduct_iters.unrank(self, x)
if (n == 0):
raise IndexError('Cartesian Product is empty')
positions.append((x % n))
x = (x // n)
if (x != 0):
raise IndexError('x larger than the size of the Cartesian Product')
positions.reverse()
return [unrank(L, i) for (L, i) in zip(self.iters, positions)]
def random_element(self):
"\n Return a random element from the Cartesian product of \\*iters.\n\n EXAMPLES::\n\n sage: from sage.combinat.cartesian_product import CartesianProduct_iters\n sage: c = CartesianProduct_iters('dog', 'cat').random_element()\n sage: c in CartesianProduct_iters('dog', 'cat')\n True\n "
return [rnd.choice(w) for w in self.iters]
|
class FSymBasis_abstract(CombinatorialFreeModule, BindableClass):
'\n Abstract base class for graded bases of `FSym` and of `FSym^*`\n indexed by standard tableaux.\n\n This must define the following attributes:\n\n - ``_prefix`` -- the basis prefix\n '
def __init__(self, alg, graded=True):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: G = algebras.FSym(QQ).G()\n sage: TestSuite(G).run() # long time\n\n Checks for the antipode::\n\n sage: FSym = algebras.FSym(QQ)\n sage: G = FSym.G()\n sage: for b in G.basis(degree=3):\n ....: print("%s : %s" % (b, b.antipode()))\n G[123] : -G[1|2|3]\n G[13|2] : -G[13|2]\n G[12|3] : -G[12|3]\n G[1|2|3] : -G[123]\n\n sage: F = FSym.dual().F()\n sage: for b in F.basis(degree=3):\n ....: print("%s : %s" % (b, b.antipode()))\n F[123] : -F[1|2|3]\n F[13|2] : -F[13|2]\n F[12|3] : -F[12|3]\n F[1|2|3] : -F[123]\n '
CombinatorialFreeModule.__init__(self, alg.base_ring(), StandardTableaux(), category=FSymBases(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 - elements of the algebra `FSym` over a base ring with\n a coercion map into ``self.base_ring()``\n\n EXAMPLES::\n\n sage: G = algebras.FSym(GF(7)).G(); G\n Hopf algebra of standard tableaux over the Finite Field of size 7\n in the Fundamental basis\n\n Elements of `FSym` canonically coerce in::\n\n sage: x, y = G([[1]]), G([[1,3],[2]])\n sage: G.coerce(x + y) == x + y\n True\n\n Elements of `FSym` over `\\ZZ` coerce in,\n since `\\ZZ` coerces to `\\GF{7}`::\n\n sage: H = algebras.FSym(ZZ).G()\n sage: Hx, Hy = H([[1]]), H([[1,3],[2]])\n sage: z = G.coerce(Hx+Hy); z\n G[1] + G[13|2]\n sage: z.parent() is G\n True\n\n However, `\\GF{7}` does not coerce to `\\ZZ`, so the\n elements of `FSym` over `\\GF{7}` do not coerce\n to the same algebra over `\\ZZ`::\n\n sage: H.coerce(y)\n Traceback (most recent call last):\n ...\n TypeError: no canonical coercion from Hopf algebra of standard tableaux\n over the Finite Field of size 7 in the Fundamental basis\n to Hopf algebra of standard tableaux over the Integer Ring in the Fundamental basis\n\n TESTS::\n\n sage: G = algebras.FSym(ZZ).G()\n sage: H = algebras.FSym(QQ).G()\n sage: G.has_coerce_map_from(H)\n False\n sage: H.has_coerce_map_from(G)\n True\n sage: G.has_coerce_map_from(QQ)\n False\n sage: H.has_coerce_map_from(QQ)\n True\n sage: G.has_coerce_map_from(PolynomialRing(ZZ, 3, 'x,y,z'))\n False\n sage: G = algebras.FSym(QQ).G()\n sage: TG = G.dual_basis()\n sage: TG.coerce_map_from(G) is None\n True\n sage: G.coerce_map_from(TG) is None\n True\n "
if isinstance(R, FSymBasis_abstract):
FSym = self.realization_of()
if (R.realization_of() == FSym):
return True
if (isinstance(R.realization_of(), FreeSymmetricFunctions) != isinstance(FSym, FreeSymmetricFunctions)):
return False
if (not self.base_ring().has_coerce_map_from(R.base_ring())):
return False
if (self._realization_name() == R._realization_name()):
def coerce_base_ring(self, x):
return self._from_dict(x.monomial_coefficients())
return coerce_base_ring
target = getattr(FSym, R._realization_name())()
return self._coerce_map_via([target], R)
return super()._coerce_map_from_(R)
def some_elements(self):
'\n Return some elements of ``self``.\n\n EXAMPLES::\n\n sage: G = algebras.FSym(QQ).G()\n sage: G.some_elements()\n [G[], G[1], G[12], G[1] + G[1|2], G[] + 1/2*G[1]]\n '
u = self.one()
o = self([[1]])
s = self.base_ring().an_element()
return [u, o, self([[1, 2]]), (o + self([[1], [2]])), (u + (s * o))]
def _repr_term(self, phi):
"\n The string representation of a basis element.\n\n EXAMPLES:\n\n We use a compact notation for standard tableaux::\n\n sage: FSym = algebras.FSym(QQ)\n sage: G = FSym.G()\n sage: G.zero()\n 0\n sage: G._repr_term(StandardTableau([[1],[2],[3],[4]]))\n 'G[1|2|3|4]'\n sage: G[[1,3,5],[2,4]]\n G[135|24]\n "
return '{}[{}]'.format(self._prefix, '|'.join((''.join(map(str, block)) for block in phi)))
|
class FSymBases(Category_realization_of_parent):
'\n The category of graded bases of `FSym` and `FSym^*` indexed\n by standard tableaux.\n '
def super_categories(self):
'\n The super categories of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.chas.fsym import FSymBases\n sage: FSym = algebras.FSym(ZZ)\n sage: bases = FSymBases(FSym)\n sage: bases.super_categories()\n [Category of realizations of Hopf algebra of standard tableaux over the 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 `FSym`.\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(ZZ)\n sage: FSym.G()\n Hopf algebra of standard tableaux over the Integer Ring\n in the Fundamental basis\n '
return '{} in the {} basis'.format(self.realization_of(), self._realization_name())
def __getitem__(self, key):
'\n Override the ``__getitem__`` method to allow passing a standard\n tableau in a nonstandard form (e.g., as a tuple of rows instead\n of a list of rows; or as a single row for a single-rowed tableau).\n\n EXAMPLES:\n\n Construct the basis element indexed by a standard tableau by\n passing data that defines the standard tableau::\n\n sage: FSym = algebras.FSym(QQ)\n sage: G = FSym.G()\n sage: G[[1,3],[2]]\n G[13|2]\n sage: G[(1,3),(2,)]\n G[13|2]\n sage: G[[1,3],[2]].leading_support() in StandardTableaux()\n True\n sage: G[1,2,3]\n G[123]\n '
try:
return self.monomial(self._indices(list(key)))
except (TypeError, ValueError):
return self.monomial(self._indices([key]))
def basis(self, degree=None):
'\n The basis elements (optionally: of the specified degree).\n\n OUTPUT: Family\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: TG = FSym.G()\n sage: TG.basis()\n Lazy family (Term map from Standard tableaux to Hopf algebra of standard tableaux\n over the Rational Field in the Fundamental basis(i))_{i in Standard tableaux}\n sage: TG.basis().keys()\n Standard tableaux\n sage: TG.basis(degree=3).keys()\n Standard tableaux of size 3\n sage: TG.basis(degree=3).list()\n [G[123], G[13|2], G[12|3], G[1|2|3]]\n '
from sage.sets.family import Family
if (degree is None):
return Family(self._indices, self.monomial)
else:
return Family(StandardTableaux(degree), self.monomial)
@cached_method
def one_basis(self):
'\n Return the basis index corresponding to `1`.\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: TG = FSym.G()\n sage: TG.one_basis()\n []\n '
return self._indices([])
def duality_pairing(self, x, y):
'\n The canonical pairing between `FSym` and `FSym^*`.\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: G = FSym.G()\n sage: F = G.dual_basis()\n sage: t1 = StandardTableau([[1,3,5],[2,4]])\n sage: t2 = StandardTableau([[1,3],[2,5],[4]])\n sage: G.duality_pairing(G[t1], F[t2])\n 0\n sage: G.duality_pairing(G[t1], F[t1])\n 1\n sage: G.duality_pairing(G[t2], F[t2])\n 1\n sage: F.duality_pairing(F[t2], G[t2])\n 1\n\n sage: z = G[[1,3,5],[2,4]]\n sage: all(F.duality_pairing(F[p1] * F[p2], z) == c\n ....: for ((p1, p2), c) in z.coproduct())\n True\n\n TESTS:\n\n If ``x`` is zero, then the output still has the right\n type::\n\n sage: z = G.duality_pairing(G.zero(), F.zero()); z\n 0\n sage: parent(z)\n Rational Field\n '
y = self.dual_basis()(y)
return self.base_ring().sum(((coeff * y[t]) for (t, coeff) in x))
def duality_pairing_matrix(self, basis, degree):
'\n The matrix of scalar products between elements of `FSym` and\n elements of `FSym^*`.\n\n INPUT:\n\n - ``basis`` -- a basis of the dual Hopf algebra\n - ``degree`` -- a non-negative integer\n\n OUTPUT:\n\n - the matrix of scalar products between the basis ``self`` and the\n basis ``basis`` in the dual Hopf algebra of degree ``degree``\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: G = FSym.G()\n sage: G.duality_pairing_matrix(G.dual_basis(), 3)\n [1 0 0 0]\n [0 1 0 0]\n [0 0 1 0]\n [0 0 0 1]\n '
from sage.matrix.constructor import matrix
keys = self.basis(degree=degree).keys()
return matrix(self.base_ring(), [[self.duality_pairing(self[s], basis[t]) for t in keys] for s in keys])
def degree_on_basis(self, t):
'\n Return the degree of a standard tableau in the algebra\n of free symmetric functions.\n\n This is the size of the tableau ``t``.\n\n EXAMPLES::\n\n sage: G = algebras.FSym(QQ).G()\n sage: t = StandardTableau([[1,3],[2]])\n sage: G.degree_on_basis(t)\n 3\n sage: u = StandardTableau([[1,3,4,5],[2]])\n sage: G.degree_on_basis(u)\n 5\n '
return t.size()
class ElementMethods():
def duality_pairing(self, other):
'\n Compute the pairing between ``self`` and an element ``other``\n of the dual.\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: G = FSym.G()\n sage: F = G.dual_basis()\n sage: elt = G[[1,3],[2]] - 3*G[[1,2],[3]]\n sage: elt.duality_pairing(F[[1,3],[2]])\n 1\n sage: elt.duality_pairing(F[[1,2],[3]])\n -3\n sage: elt.duality_pairing(F[[1,2]])\n 0\n '
return self.parent().duality_pairing(self, other)
|
class FreeSymmetricFunctions(UniqueRepresentation, Parent):
'\n The free symmetric functions.\n\n The *free symmetric functions* is a combinatorial Hopf algebra\n defined using tableaux and denoted `FSym`.\n\n Consider the Hopf algebra `FQSym`\n (:class:`~sage.combinat.fqsym.FreeQuasisymmetricFunctions`)\n over a commutative ring `R`, and its bases `(F_w)` and `(G_w)`\n (where `w`, in both cases, ranges over all permutations in all\n symmetric groups `S_0, S_1, S_2, \\ldots`).\n For each word `w`, let `P(w)` be the P-tableau of `w` (that\n is, the first of the two tableaux obtained by applying the\n RSK algorithm to `w`; see :meth:`~sage.combinat.rsk.RSK`).\n If `t` is a standard tableau of size `n`, then we define\n `\\mathcal{G}_t \\in FQSym` to be the sum of the `F_w` with\n `w` ranging over all permutations of `\\{1, 2, \\ldots, n\\}`\n satisfying `P(w) = t`. Equivalently, `\\mathcal{G}_t` is the\n sum of the `G_w` with `w` ranging over all permutations of\n `\\{1, 2, \\ldots, n\\}` satisfying `Q(w) = t` (where `Q(w)`\n denotes the Q-tableau of `w`).\n\n The `R`-linear span of the `\\mathcal{G}_t` (for `t` ranging\n over all standard tableaux) is a Hopf subalgebra of `FQSym`,\n denoted by `FSym` and known as the *free symmetric functions*\n or the *Poirier-Reutenauer Hopf algebra of tableaux*. It has been\n introduced in [PoiReu95]_, where it was denoted by\n `(\\ZZ T, \\ast, \\delta)`. (What we call `\\mathcal{G}_t`\n has just been called `t` in [PoiReu95]_.)\n The family `(\\mathcal{G}_t)` (with `t` ranging over all standard\n tableaux) is a basis of `FSym`, called the *Fundamental basis*.\n\n EXAMPLES:\n\n As explained above, `FSym` is constructed as a Hopf subalgebra of\n `FQSym`::\n\n sage: G = algebras.FSym(QQ).G()\n sage: F = algebras.FQSym(QQ).F()\n sage: G[[1,3],[2]]\n G[13|2]\n sage: G[[1,3],[2]].to_fqsym()\n G[2, 1, 3] + G[3, 1, 2]\n sage: F(G[[1,3],[2]])\n F[2, 1, 3] + F[2, 3, 1]\n\n This embedding is a Hopf algebra morphism::\n\n sage: all(F(G[t1] * G[t2]) == F(G[t1]) * F(G[t2])\n ....: for t1 in StandardTableaux(2)\n ....: for t2 in StandardTableaux(3))\n True\n\n sage: FF = F.tensor_square()\n sage: all(FF(G[t].coproduct()) == F(G[t]).coproduct()\n ....: for t in StandardTableaux(4))\n True\n\n There is a Hopf algebra map from `FSym` onto the Hopf algebra\n of symmetric functions, which maps a tableau `t` to the Schur\n function indexed by the shape of `t`::\n\n sage: TG = algebras.FSym(QQ).G()\n sage: t = StandardTableau([[1,3],[2,4],[5]])\n sage: TG[t]\n G[13|24|5]\n sage: TG[t].to_symmetric_function()\n s[2, 2, 1]\n '
def __init__(self, base_ring):
'\n TESTS::\n\n sage: FSym = algebras.FSym(QQ)\n sage: TestSuite(FSym).run()\n '
cat = HopfAlgebras(base_ring).Graded().Connected()
Parent.__init__(self, base=base_ring, category=cat.WithRealizations())
_shorthands = ['G']
def a_realization(self):
'\n Return a particular realization of ``self`` (the Fundamental basis).\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: FSym.a_realization()\n Hopf algebra of standard tableaux over the Rational Field\n in the Fundamental basis\n '
return self.Fundamental()
def dual(self):
'\n Return the dual Hopf algebra of `FSym`.\n\n EXAMPLES::\n\n sage: algebras.FSym(QQ).dual()\n Dual Hopf algebra of standard tableaux over the Rational Field\n '
return FreeSymmetricFunctions_Dual(self.base_ring())
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: algebras.FSym(QQ)\n Hopf algebra of standard tableaux over the Rational Field\n '
return ('Hopf algebra of standard tableaux over the %s' % self.base_ring())
class Fundamental(FSymBasis_abstract):
'\n The Hopf algebra of tableaux on the Fundamental basis.\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: TG = FSym.G()\n sage: TG\n Hopf algebra of standard tableaux over the Rational Field\n in the Fundamental basis\n\n Elements of the algebra look like::\n\n sage: TG.an_element()\n 2*G[] + 2*G[1] + 3*G[12]\n\n TESTS::\n\n sage: FSym = algebras.FSym(QQ)\n sage: TG = FSym.G()\n sage: TestSuite(TG).run()\n '
_prefix = 'G'
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 - elements of the algebra `FSym` over a base ring\n with a coercion map into ``self.base_ring()``\n - non-commutative symmetric functions over a base ring with\n a coercion map into ``self.base_ring()``\n\n EXAMPLES:\n\n There exists a morphism from `NCSF` to `FSym`::\n\n sage: G = algebras.FSym(QQ).G()\n sage: R = NonCommutativeSymmetricFunctions(QQ).R()\n sage: G(R[3,1,2,2,1])\n G[123|46|58|7|9] + G[123|46|58|79] + G[123|468|5|7|9]\n + G[123|468|57|9] + G[123|468|579] + G[123|468|59|7]\n + G[1236|478|5|9] + G[1236|478|59] + G[1236|48|5|7|9]\n + G[1236|48|59|7] + G[12368|4|5|7|9] + G[12368|47|5|9]\n + G[12368|47|59] + G[12368|479|5] + G[12368|49|5|7]\n + G[1238|46|5|7|9] + G[1238|46|57|9] + G[1238|46|59|7]\n + G[1238|469|5|7] + G[1238|469|57]\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: G(S[2,1,2])\n G[12|35|4] + G[123|45] + G[12345] + G[1235|4]\n + G[1245|3] + G[125|3|4] + G[125|34]\n sage: G(R(S[3,1,2,2])) == G(S[3,1,2,2])\n True\n\n This mapping is a Hopf algebra morphism::\n\n sage: all(G(R[a1] * R[a2]) == G(R[a1]) * G(R[a2])\n ....: for a1 in Compositions(2)\n ....: for a2 in Compositions(4))\n True\n\n sage: R2 = R.tensor_square()\n sage: phi = R2.module_morphism(\n ....: lambda x: tensor([G(R[x[0]]), G(R[x[1]])]),\n ....: codomain=G.tensor_square())\n sage: all(phi(R[p].coproduct()) == G(R[p]).coproduct()\n ....: for p in Compositions(4))\n True\n\n sage: all(G(S[a1] * S[a2]) == G(S[a1]) * G(S[a2])\n ....: for a1 in Compositions(2)\n ....: for a2 in Compositions(4))\n True\n\n sage: S2 = S.tensor_square()\n sage: psi = S2.module_morphism(\n ....: lambda x: tensor([G(S[x[0]]), G(S[x[1]])]),\n ....: codomain=G.tensor_square())\n sage: all(psi(S[p].coproduct()) == G(S[p]).coproduct()\n ....: for p in Compositions(4))\n True\n '
if hasattr(R, 'realization_of'):
if (not self.base_ring().has_coerce_map_from(R.base_ring())):
return False
A = R.realization_of()
from sage.combinat.ncsf_qsym.ncsf import NonCommutativeSymmetricFunctions
if isinstance(A, NonCommutativeSymmetricFunctions):
ribbon = A.ribbon()
if (R is ribbon):
ST = self._indices
def R_to_G_on_basis(alpha):
return self.sum_of_monomials((ST(t) for t in StandardTableaux(alpha.size()) if (descent_composition(t) == alpha)))
return ribbon.module_morphism(R_to_G_on_basis, codomain=self)
return self._coerce_map_via([ribbon], R)
return super()._coerce_map_from_(R)
def dual_basis(self):
'\n Return the dual basis to ``self``.\n\n EXAMPLES::\n\n sage: G = algebras.FSym(QQ).G()\n sage: G.dual_basis()\n Dual Hopf algebra of standard tableaux over the Rational Field\n in the FundamentalDual basis\n '
return self.realization_of().dual().F()
@cached_method
def product_on_basis(self, t1, t2):
'\n Return the product of basis elements indexed by ``t1`` and ``t2``.\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: G = FSym.G()\n sage: t1 = StandardTableau([[1,2], [3]])\n sage: t2 = StandardTableau([[1,2,3]])\n sage: G.product_on_basis(t1, t2)\n G[12456|3] + G[1256|3|4] + G[1256|34] + G[126|35|4]\n\n sage: t1 = StandardTableau([[1],[2]])\n sage: t2 = StandardTableau([[1,2]])\n sage: G.product_on_basis(t1, t2)\n G[134|2] + G[14|2|3]\n\n sage: t1 = StandardTableau([[1,2],[3]])\n sage: t2 = StandardTableau([[1],[2]])\n sage: G.product_on_basis(t1, t2)\n G[12|3|4|5] + G[12|34|5] + G[124|3|5] + G[124|35]\n '
n = t1.size()
m = (n + t2.size())
tableaux = []
for t in StandardTableaux(m):
if ((t.restrict(n) == t1) and (standardize(t.anti_restrict(n).rectify()) == t2)):
tableaux.append(t)
return self.sum_of_monomials(tableaux)
@cached_method
def coproduct_on_basis(self, t):
'\n Return the coproduct of the basis element indexed by ``t``.\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: G = FSym.G()\n sage: t = StandardTableau([[1,2,5], [3,4]])\n sage: G.coproduct_on_basis(t)\n G[] # G[125|34] + G[1] # G[12|34] + G[1] # G[124|3]\n + G[1|2] # G[13|2] + G[12] # G[12|3] + G[12] # G[123]\n + G[12|34] # G[1] + G[123] # G[12] + G[125|34] # G[]\n + G[13|2] # G[1|2] + G[13|2] # G[12] + G[134|2] # G[1]\n '
n = t.size()
L = []
dual_basis = self.dual_basis()
for i in range((n + 1)):
for t1 in StandardTableaux(i):
for t2 in StandardTableaux((n - i)):
coeff = (dual_basis[t1] * dual_basis[t2])[t]
if coeff:
L.append(((t1, t2), coeff))
TT = self.tensor_square()
return TT.sum_of_terms(L)
class Element(FSymBasis_abstract.Element):
def to_fqsym(self):
'\n Return the image of ``self`` under the natural inclusion\n map to `FQSym`.\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: G = FSym.G()\n sage: t = StandardTableau([[1,3],[2,4],[5]])\n sage: G[t].to_fqsym()\n G[2, 1, 5, 4, 3] + G[3, 1, 5, 4, 2] + G[3, 2, 5, 4, 1]\n + G[4, 1, 5, 3, 2] + G[4, 2, 5, 3, 1]\n '
from sage.combinat.fqsym import FreeQuasisymmetricFunctions
R = self.parent().base_ring()
G = FreeQuasisymmetricFunctions(R).G()
return G(self)
def to_symmetric_function(self):
'\n Return the image of ``self`` under the natural projection\n map to `Sym`.\n\n The natural projection map `FSym \\to Sym` sends each\n standard tableau `t` to the Schur function `s_\\lambda`,\n where `\\lambda` is the shape of `t`.\n This map is a surjective Hopf algebra homomorphism.\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: G = FSym.G()\n sage: t = StandardTableau([[1,3],[2,4],[5]])\n sage: G[t].to_symmetric_function()\n s[2, 2, 1]\n '
s = SymmetricFunctions(self.parent().base_ring()).s()
return s.sum_of_terms(((t.shape(), coeff) for (t, coeff) in self))
G = Fundamental
|
class FreeSymmetricFunctions_Dual(UniqueRepresentation, Parent):
"\n The Hopf dual `FSym^*` of the free symmetric functions `FSym`.\n\n See :class:`FreeSymmetricFunctions` for the definition of the\n latter.\n\n Recall that the fundamental basis of `FSym` consists of the\n elements `\\mathcal{G}_t` for `t` ranging over all standard\n tableaux. The dual basis of this is called the *dual\n fundamental basis* of `FSym^*`, and is denoted by\n `(\\mathcal{G}_t^*)`.\n The Hopf dual `FSym^*` is isomorphic to the Hopf algebra\n `(\\ZZ T, \\ast', \\delta')` from [PoiReu95]_; the\n isomorphism sends a basis element `\\mathcal{G}_t^*` to `t`.\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: TF = FSym.dual().F()\n sage: TF[1,2] * TF[[1],[2]]\n F[12|3|4] + F[123|4] + F[124|3] + F[13|2|4] + F[134|2] + F[14|2|3]\n sage: TF[[1,2],[3]].coproduct()\n F[] # F[12|3] + F[1] # F[1|2] + F[12] # F[1] + F[12|3] # F[]\n\n The Hopf algebra `FSym^*` is a Hopf quotient of `FQSym`;\n the canonical projection sends `F_w` (for a permutation `w`)\n to `\\mathcal{G}_{Q(w)}^*`, where `Q(w)` is the Q-tableau of\n `w`. This projection is implemented as a coercion::\n\n sage: FQSym = algebras.FQSym(QQ)\n sage: F = FQSym.F()\n sage: TF(F[[1, 3, 2]])\n F[12|3]\n sage: TF(F[[5, 1, 4, 2, 3]])\n F[135|2|4]\n "
def __init__(self, base_ring):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: FSymD = algebras.FSym(QQ).dual()\n sage: TestSuite(FSymD).run()\n '
cat = HopfAlgebras(base_ring).Graded().Connected()
Parent.__init__(self, base=base_ring, category=cat.WithRealizations())
_shorthands = ['F']
def a_realization(self):
'\n Return a particular realization of ``self`` (the Fundamental\n dual basis).\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ).dual()\n sage: FSym.a_realization()\n Dual Hopf algebra of standard tableaux over the Rational Field\n in the FundamentalDual basis\n '
return self.FundamentalDual()
def dual(self):
'\n Return the dual Hopf algebra of ``self``, which is `FSym`.\n\n EXAMPLES::\n\n sage: D = algebras.FSym(QQ).dual()\n sage: D.dual()\n Hopf algebra of standard tableaux over the Rational Field\n '
return FreeSymmetricFunctions(self.base_ring())
def _repr_(self):
'\n EXAMPLES::\n\n sage: algebras.FSym(QQ).dual()\n Dual Hopf algebra of standard tableaux over the Rational Field\n '
return ('Dual Hopf algebra of standard tableaux over the %s' % self.base_ring())
class FundamentalDual(FSymBasis_abstract):
'\n The dual to the Hopf algebra of tableaux,\n on the fundamental dual basis.\n\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: TF = FSym.dual().F()\n sage: TF\n Dual Hopf algebra of standard tableaux over the Rational Field\n in the FundamentalDual basis\n\n Elements of the algebra look like::\n\n sage: TF.an_element()\n 2*F[] + 2*F[1] + 3*F[12]\n\n TESTS::\n\n sage: FSym = algebras.FSym(QQ)\n sage: TF = FSym.dual().F()\n sage: TestSuite(TF).run()\n '
_prefix = 'F'
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 - elements of the algebra `FSym^*` over a base ring\n with a coercion map into ``self.base_ring()``\n - symmetric functions over a base ring with a coercion\n map into ``self.base_ring()``\n - elements of the algebra `FQSym` over a base ring with\n a coercion map into ``self.base_ring()``\n\n EXAMPLES:\n\n `FSym^*` is a quotient Hopf algebra of `FQSym`: the basis\n element `F_\\sigma` indexed by a permutation `\\sigma` is\n mapped to the tableau `Q(\\sigma)`::\n\n sage: TF = algebras.FSym(QQ).dual().F()\n sage: SF = algebras.FQSym(QQ).F()\n sage: TF(SF([3,1,4,5,2]))\n F[134|25]\n sage: SG = algebras.FQSym(QQ).G()\n sage: TF(SG([3,1,4,5,2]))\n F[125|34]\n\n This mapping is a Hopf algebra morphism::\n\n sage: all(TF(SF[p1] * SF[p2]) == TF(SF[p1]) * TF(SF[p2])\n ....: for p1 in Permutations(2)\n ....: for p2 in Permutations(3))\n True\n\n sage: SSym2 = SF.tensor_square()\n sage: phi = SSym2.module_morphism(\n ....: lambda x: tensor([TF(SF[x[0]]), TF(SF[x[1]])]),\n ....: codomain=TF.tensor_square())\n sage: all(phi(SF[p].coproduct()) == TF(SF[p]).coproduct()\n ....: for p in Permutations(4))\n True\n\n There is also an injective Hopf algebra morphism\n `Sym \\to FSym^*` (adjoint to the projection `FSym \\to Sym`\n implemented as\n :meth:`FreeSymmetricFunctions.Fundamental.Element.to_symmetric_function`)\n that sends each Schur function `s_\\lambda` to the sum of\n all standard tableaux of shape `\\lambda`::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: s = Sym.schur()\n sage: TF = algebras.FSym(QQ).dual().F()\n sage: TF(s[2,1])\n F[12|3] + F[13|2]\n sage: TF(s[2,2,1])\n F[12|34|5] + F[12|35|4] + F[13|24|5] + F[13|25|4] + F[14|25|3]\n sage: h = Sym.h()\n sage: TF(h[2,1])\n F[12|3] + F[123] + F[13|2]\n\n This mapping is a Hopf algebra morphism::\n\n sage: all(TF(s[p1] * s[p2]) == TF(s[p1]) * TF(s[p2])\n ....: for p1 in Partitions(2)\n ....: for p2 in Partitions(3))\n True\n\n sage: s2 = s.tensor_square()\n sage: phi = s2.module_morphism(\n ....: lambda x: tensor([TF(s[x[0]]), TF(s[x[1]])]),\n ....: codomain=TF.tensor_square())\n sage: all(phi(s[p].coproduct()) == TF(s[p]).coproduct()\n ....: for p in Partitions(4))\n True\n '
if hasattr(R, 'realization_of'):
if (not self.base_ring().has_coerce_map_from(R.base_ring())):
return False
A = R.realization_of()
from sage.combinat.fqsym import FreeQuasisymmetricFunctions
if isinstance(A, FreeQuasisymmetricFunctions):
F = A.F()
if (R is F):
def F_to_SF_on_basis(sigma):
return self.monomial(sigma.right_tableau())
return F.module_morphism(F_to_SF_on_basis, codomain=self)
return self._coerce_map_via([F], R)
if isinstance(A, SymmetricFunctions):
s = A.s()
if (R is s):
def s_to_F_on_basis(mu):
return self.sum_of_monomials(StandardTableaux(mu))
return s.module_morphism(s_to_F_on_basis, codomain=self)
return self._coerce_map_via([s], R)
return super()._coerce_map_from_(R)
def dual_basis(self):
'\n Return the dual basis to ``self``.\n\n EXAMPLES::\n\n sage: F = algebras.FSym(QQ).dual().F()\n sage: F.dual_basis()\n Hopf algebra of standard tableaux over the Rational Field\n in the Fundamental basis\n '
return self.realization_of().dual().G()
@cached_method
def product_on_basis(self, t1, t2):
'\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: TF = FSym.dual().F()\n sage: t1 = StandardTableau([[1,2]])\n sage: TF.product_on_basis(t1, t1)\n F[12|34] + F[123|4] + F[1234] + F[124|3] + F[13|24] + F[134|2]\n sage: t0 = StandardTableau([])\n sage: TF.product_on_basis(t1, t0) == TF[t1] == TF.product_on_basis(t0, t1)\n True\n '
z = []
n = t1.size()
m = t2.size()
npmp1 = ((n + m) + 1)
ST = self._indices
from itertools import combinations
for I in combinations(range(1, npmp1), n):
J = [j for j in range(1, npmp1) if (j not in I)]
tt1 = [[I[(x - 1)] for x in row] for row in t1]
tt2 = [tuple([J[(x - 1)] for x in row]) for row in t2]
z.append(ST(Tableau(tt1).slide_multiply(tt2)))
return self.sum_of_monomials(z)
@cached_method
def coproduct_on_basis(self, t):
'\n EXAMPLES::\n\n sage: FSym = algebras.FSym(QQ)\n sage: TF = FSym.dual().F()\n sage: t = StandardTableau([[1,2,5], [3,4]])\n sage: TF.coproduct_on_basis(t)\n F[] # F[125|34] + F[1] # F[134|2] + F[12] # F[123]\n + F[12|3] # F[12] + F[12|34] # F[1] + F[125|34] # F[]\n '
terms = [(t.restrict(i), standardize(t.anti_restrict(i).rectify())) for i in range((t.size() + 1))]
return self.tensor_square().sum_of_monomials(terms)
class Element(FSymBasis_abstract.Element):
def to_quasisymmetric_function(self):
'\n Return the image of ``self`` under the canonical projection\n `FSym^* \\to QSym` to the ring of quasi-symmetric functions.\n\n This projection is the adjoint of the canonical injection\n `NSym \\to FSym` (see\n :meth:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.to_fsym`).\n It sends each tableau `t` to the fundamental quasi-symmetric\n function `F_\\alpha`, where `\\alpha` is the descent composition\n of `t`.\n\n EXAMPLES::\n\n sage: F = algebras.FSym(QQ).dual().F()\n sage: F[[1,3,5],[2,4]].to_quasisymmetric_function()\n F[1, 2, 2]\n '
from sage.combinat.ncsf_qsym.qsym import QuasiSymmetricFunctions
QF = QuasiSymmetricFunctions(self.base_ring()).Fundamental()
return QF.sum_of_terms(((descent_composition(t), coeff) for (t, coeff) in self))
F = FundamentalDual
|
def standardize(t):
'\n Return the standard tableau corresponding to a given\n semistandard tableau ``t`` with no repeated entries.\n\n .. NOTE::\n\n This is an optimized version of :meth:`Tableau.standardization`\n for computations in `FSym` by using the assumption of no\n repeated entries in ``t``.\n\n EXAMPLES::\n\n sage: from sage.combinat.chas.fsym import standardize\n sage: t = Tableau([[1,3,5,7],[2,4,8],[9]])\n sage: standardize(t)\n [[1, 3, 5, 6], [2, 4, 7], [8]]\n sage: t = Tableau([[3,8,9,15],[5,10,12],[133]])\n sage: standardize(t)\n [[1, 3, 4, 7], [2, 5, 6], [8]]\n\n TESTS:\n\n This returns an equal tableau if already standard::\n\n sage: t = Tableau([[1,3,4,5],[2,6,7],[8]])\n sage: standardize(t)\n [[1, 3, 4, 5], [2, 6, 7], [8]]\n sage: standardize(t) == t\n True\n '
A = sorted(sum(t, ()))
std = {j: (i + 1) for (i, j) in enumerate(A)}
ST = StandardTableaux()
return ST([[std[i] for i in row] for row in t])
|
def ascent_set(t):
'\n Return the ascent set of a standard tableau ``t``\n (encoded as a sorted list).\n\n The *ascent set* of a standard tableau `t` is defined as\n the set of all entries `i` of `t` such that the number `i+1`\n either appears to the right of `i` or appears in a row above\n `i` or does not appear in `t` at all.\n\n EXAMPLES::\n\n sage: from sage.combinat.chas.fsym import ascent_set\n sage: t = StandardTableau([[1,3,4,7],[2,5,6],[8]])\n sage: ascent_set(t)\n [2, 3, 5, 6, 8]\n sage: ascent_set(StandardTableau([]))\n []\n sage: ascent_set(StandardTableau([[1, 2, 3]]))\n [1, 2, 3]\n sage: ascent_set(StandardTableau([[1, 2, 4], [3]]))\n [1, 3, 4]\n sage: ascent_set([[1, 3, 5], [2, 4]])\n [2, 4, 5]\n '
row_locations = {}
for (i, row) in enumerate(t):
for entry in row:
row_locations[entry] = i
n = len(row_locations)
if (not n):
return []
ascents = [n]
for i in range(1, n):
x = row_locations[i]
u = row_locations[(i + 1)]
if (u <= x):
ascents.append(i)
return sorted(ascents)
|
def descent_set(t):
'\n Return the descent set of a standard tableau ``t``\n (encoded as a sorted list).\n\n The *descent set* of a standard tableau `t` is defined as\n the set of all entries `i` of `t` such that the number `i+1`\n appears in a row below `i` in `t`.\n\n EXAMPLES::\n\n sage: from sage.combinat.chas.fsym import descent_set\n sage: t = StandardTableau([[1,3,4,7],[2,5,6],[8]])\n sage: descent_set(t)\n [1, 4, 7]\n sage: descent_set(StandardTableau([]))\n []\n sage: descent_set(StandardTableau([[1, 2, 3]]))\n []\n sage: descent_set(StandardTableau([[1, 2, 4], [3]]))\n [2]\n sage: descent_set([[1, 3, 5], [2, 4]])\n [1, 3]\n '
ascents = set(ascent_set(t))
n = sum((len(row) for row in t))
return [i for i in range(1, n) if (i not in ascents)]
|
def descent_composition(t):
'\n Return the descent composition of a standard tableau ``t``.\n\n This is the composition of the size of `t` whose partial\n sums are the elements of the descent set of ``t`` (see\n :meth:`descent_set`).\n\n EXAMPLES::\n\n sage: from sage.combinat.chas.fsym import descent_composition\n sage: t = StandardTableau([[1,3,4,7],[2,5,6],[8]])\n sage: descent_composition(t)\n [1, 3, 3, 1]\n sage: descent_composition([[1, 3, 5], [2, 4]])\n [1, 2, 2]\n '
n = sum((len(row) for row in t))
return Composition(from_subset=(descent_set(t), n))
|
class WQSymBasis_abstract(CombinatorialFreeModule, BindableClass):
'\n Abstract base class for bases of `WQSym`.\n\n This must define two attributes:\n\n - ``_prefix`` -- the basis prefix\n - ``_basis_name`` -- the name of the basis (must match one\n of the names that the basis can be constructed from `WQSym`)\n '
def __init__(self, alg, graded=True):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: M = algebras.WQSym(QQ).M()\n sage: TestSuite(M).run() # long time\n '
def sorting_key(X):
return (sum(map(len, X)), X)
CombinatorialFreeModule.__init__(self, alg.base_ring(), OrderedSetPartitions(), category=WQSymBases(alg, graded), sorting_key=sorting_key, bracket='', prefix=self._prefix)
def _repr_term(self, osp):
'\n Return a string representation of an element of WordQuasiSymmetricFunctions\n in the basis ``self``.\n\n TESTS::\n\n sage: M = WordQuasiSymmetricFunctions(QQ).M()\n sage: elt = M[[[1,2]]] * M[[[1]]]; elt\n M[{1, 2}, {3}] + M[{1, 2, 3}] + M[{3}, {1, 2}]\n sage: M.options.objects = "words"\n sage: elt\n M[1, 1, 2] + M[1, 1, 1] + M[2, 2, 1]\n sage: M.options._reset()\n '
return (self._prefix + self.options._dispatch(self, '_repr_', 'objects', osp))
def _repr_compositions(self, osp):
'\n Return a string representation of ``osp`` indexed by ordered set partitions.\n\n This method is called by ``self_repr_term``.\n\n EXAMPLES::\n\n sage: M = WordQuasiSymmetricFunctions(QQ).M()\n sage: elt = M[[[1,2]]] * M[[[1]]]; elt\n M[{1, 2}, {3}] + M[{1, 2, 3}] + M[{3}, {1, 2}]\n sage: M.options.display = "tight"\n sage: elt\n M[{1,2},{3}] + M[{1,2,3}] + M[{3},{1,2}]\n sage: M.options.display = "compact"\n sage: elt\n M[12.3] + M[123] + M[3.12]\n sage: osp = OrderedSetPartition([[2,4], [1,3,7],[5,6]])\n sage: M._repr_compositions(osp) == \'[24.137.56]\'\n True\n sage: M.options._reset(); elt\n M[{1, 2}, {3}] + M[{1, 2, 3}] + M[{3}, {1, 2}]\n '
display = self.options.display
disp = repr(osp)
if (display == 'tight'):
disp = disp.replace(', ', ',')
return disp
elif (display == 'compact'):
disp = disp.replace('}, ', '.').replace('}', '').replace('{', '')
return disp.replace(', ', '')
else:
return disp
def _repr_words(self, osp):
'\n Return a string representation of ``self`` indexed by packed words.\n\n This method is called by ``self_repr_term``.\n\n EXAMPLES::\n\n sage: M = WordQuasiSymmetricFunctions(QQ).M()\n sage: elt = M[[[1,2]]]*M[[[1]]]; elt\n M[{1, 2}, {3}] + M[{1, 2, 3}] + M[{3}, {1, 2}]\n sage: M.options.objects = "words"\n sage: elt\n M[1, 1, 2] + M[1, 1, 1] + M[2, 2, 1]\n sage: M.options.display = "tight"\n sage: elt\n M[1,1,2] + M[1,1,1] + M[2,2,1]\n sage: M.options.display = "compact"\n sage: elt\n M[112] + M[111] + M[221]\n sage: osp = OrderedSetPartition([[2,4], [1,3,7],[5,6]])\n sage: M._repr_words(osp) == \'[2121332]\'\n True\n sage: M.options._reset(); elt\n M[{1, 2}, {3}] + M[{1, 2, 3}] + M[{3}, {1, 2}]\n '
display = self.options.display
disp = repr(list(osp.to_packed_word()))
if (display == 'tight'):
return disp.replace(', ', ',')
elif (display == 'compact'):
return disp.replace(', ', '')
else:
return disp
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 - word quasi-symmetric functions over a base with\n a coercion map into ``self.base_ring()``\n\n EXAMPLES::\n\n sage: M = algebras.WQSym(GF(7)).M(); M\n Word Quasi-symmetric functions over Finite Field of size 7 in the Monomial basis\n\n Elements of the word quasi-symmetric functions canonically coerce in::\n\n sage: x, y = M([[1]]), M([[2,1]])\n sage: M.coerce(x+y) == x+y\n True\n\n The word quasi-symmetric functions over `\\ZZ` coerces in,\n since `\\ZZ` coerces to `\\GF{7}`::\n\n sage: N = algebras.WQSym(ZZ).M()\n sage: Nx, Ny = N([[1]]), N([[2,1]])\n sage: z = M.coerce(Nx+Ny); z\n M[{1}] + M[{1, 2}]\n sage: z.parent() is M\n True\n\n However, `\\GF{7}` does not coerce to `\\ZZ`, so word\n quasi-symmetric functions over `\\GF{7}` does not coerce\n to the same algebra over `\\ZZ`::\n\n sage: N.coerce(y)\n Traceback (most recent call last):\n ...\n TypeError: no canonical coercion from Word Quasi-symmetric functions\n over Finite Field of size 7 in the Monomial basis to\n Word Quasi-symmetric functions over Integer Ring in the Monomial basis\n\n TESTS::\n\n sage: M = algebras.WQSym(ZZ).M()\n sage: N = algebras.WQSym(QQ).M()\n sage: M.has_coerce_map_from(N)\n False\n sage: N.has_coerce_map_from(M)\n True\n sage: M.has_coerce_map_from(QQ)\n False\n sage: N.has_coerce_map_from(QQ)\n True\n sage: M.has_coerce_map_from(PolynomialRing(ZZ, 3, 'x,y,z'))\n False\n "
if isinstance(R, WQSymBasis_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)
return super()._coerce_map_from_(R)
@cached_method
def an_element(self):
'\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: M = algebras.WQSym(QQ).M()\n sage: M.an_element()\n M[{1}] + 2*M[{1}, {2}]\n '
return (self([[1]]) + (2 * self([[1], [2]])))
def some_elements(self):
'\n Return some elements of the word quasi-symmetric functions.\n\n EXAMPLES::\n\n sage: M = algebras.WQSym(QQ).M()\n sage: M.some_elements()\n [M[], M[{1}], M[{1, 2}],\n M[{1}] + M[{1}, {2}],\n M[] + 1/2*M[{1}]]\n '
u = self.one()
o = self([[1]])
s = self.base_ring().an_element()
return [u, o, self([[1, 2]]), (o + self([[1], [2]])), (u + (s * o))]
|
class WordQuasiSymmetricFunctions(UniqueRepresentation, Parent):
'\n The word quasi-symmetric functions.\n\n The ring of word quasi-symmetric functions can be defined 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 For each such word `w`, we define the *packing* of `w` to be the\n word `\\operatorname{pack}(w)` that is obtained from `w` by replacing\n the smallest letter that appears in `w` by `1`, the second-smallest\n letter that appears in `w` by `2`, etc. (for example,\n `\\operatorname{pack}(4112774) = 3112443`).\n A word `w` is said to be *packed* if `\\operatorname{pack}(w) = w`.\n For each packed word `u`, we define the noncommutative power series\n `\\mathbf{M}_u = \\sum w`, where the sum ranges over all words `w`\n satisfying `\\operatorname{pack}(w) = u`.\n The span of these power series `\\mathbf{M}_u` is a subring of the\n ring of all noncommutative power series; it is called the ring of\n word quasi-symmetric functions, and is denoted by `WQSym`.\n\n For each nonnegative integer `n`, there is a bijection between\n packed words of length `n` and ordered set partitions of\n `\\{1, 2, \\ldots, n\\}`. Under this bijection, a packed word\n `u = (u_1, u_2, \\ldots, u_n)` of length `n` corresponds to the\n ordered set partition `P = (P_1, P_2, \\ldots, P_k)` of\n `\\{1, 2, \\ldots, n\\}` whose `i`-th part `P_i` (for each `i`) is the\n set of all `j \\in \\{1, 2, \\ldots, n\\}` such that `u_j = i`.\n\n The basis element `\\mathbf{M}_u` is also denoted as `\\mathbf{M}_P`\n in this situation. The basis `(\\mathbf{M}_P)_P` is called the\n *Monomial basis* and is implemented as\n :class:`~sage.combinat.chas.wqsym.WordQuasiSymmetricFunctions.Monomial`.\n\n Other bases are the cone basis (aka C basis), the characteristic\n basis (aka X basis), the Q basis and the Phi basis.\n\n Bases of `WQSym` are implemented (internally) using ordered set\n partitions. However, the user may access specific basis vectors using\n either packed words or ordered set partitions. See the examples below,\n noting especially the section on ambiguities.\n\n `WQSym` is endowed with a connected graded Hopf algebra structure (see\n Section 2.2 of [NoThWi08]_, Section 1.1 of [FoiMal14]_ and\n Section 4.3.2 of [MeNoTh11]_) given by\n\n .. MATH::\n\n \\Delta(\\mathbf{M}_{(P_1,\\ldots,P_{\\ell})}) = \\sum_{i=0}^{\\ell}\n \\mathbf{M}_{\\operatorname{st}(P_1, \\ldots, P_i)} \\otimes\n \\mathbf{M}_{\\operatorname{st}(P_{i+1}, \\ldots, P_{\\ell})}.\n\n Here, for any ordered set partition `(Q_1, \\ldots, Q_k)` of a\n finite set `Z` of integers, we let `\\operatorname{st}(Q_1, \\ldots, Q_k)`\n denote the set partition obtained from `Z` by replacing the smallest\n element appearing in it by `1`, the second-smallest element by `2`,\n and so on.\n\n A rule for multiplying elements of the monomial basis relies on the\n *quasi-shuffle product* of two ordered set partitions.\n The quasi-shuffle product `\\Box` is given by\n :class:`~sage.combinat.shuffle.ShuffleProduct_overlapping` with the\n ``+`` operation in the overlapping of the shuffles being the\n union of the sets. The product `\\mathbf{M}_P \\mathbf{M}_Q`\n for two ordered set partitions `P` and `Q` of `[n]` and `[m]`\n is then given by\n\n .. MATH::\n\n \\mathbf{M}_P \\mathbf{M}_Q\n = \\sum_{R \\in P \\Box Q^+} \\mathbf{M}_R ,\n\n where `Q^+` means `Q` with all numbers shifted upwards by `n`.\n\n Sometimes, `WQSym` is also denoted as `NCQSym`.\n\n REFERENCES:\n\n - [FoiMal14]_\n - [MeNoTh11]_\n - [NoThWi08]_\n - [BerZab05]_\n\n EXAMPLES:\n\n Constructing the algebra and its Monomial basis::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: WQSym\n Word Quasi-symmetric functions over Integer Ring\n sage: M = WQSym.M()\n sage: M\n Word Quasi-symmetric functions over Integer Ring in the Monomial basis\n sage: M[[]]\n M[]\n\n Calling basis elements using packed words::\n\n sage: x = M[1,2,1]; x\n M[{1, 3}, {2}]\n sage: x == M[[1,2,1]] == M[Word([1,2,1])]\n True\n sage: y = M[1,1,2] - M[1,2,2]; y\n -M[{1}, {2, 3}] + M[{1, 2}, {3}]\n\n Calling basis elements using ordered set partitions::\n\n sage: z = M[[1,2,3],]; z\n M[{1, 2, 3}]\n sage: z == M[[[1,2,3]]] == M[OrderedSetPartition([[1,2,3]])]\n True\n sage: M[[1,2],[3]]\n M[{1, 2}, {3}]\n\n Note that expressions above are output in terms of ordered set partitions,\n even when input as packed words. Output as packed words can be achieved\n by modifying the global options. (See :meth:`OrderedSetPartitions.options`\n for further details.)::\n\n sage: M.options.objects = "words"\n sage: y\n -M[1, 2, 2] + M[1, 1, 2]\n sage: M.options.display = "compact"\n sage: y\n -M[122] + M[112]\n sage: z\n M[111]\n\n The options should be reset to display as ordered set partitions::\n\n sage: M.options._reset()\n sage: z\n M[{1, 2, 3}]\n\n Illustration of the Hopf algebra structure::\n\n sage: M[[2, 3], [5], [6], [4], [1]].coproduct()\n M[] # M[{2, 3}, {5}, {6}, {4}, {1}] + M[{1, 2}] # M[{3}, {4}, {2}, {1}]\n + M[{1, 2}, {3}] # M[{3}, {2}, {1}] + M[{1, 2}, {3}, {4}] # M[{2}, {1}]\n + M[{1, 2}, {4}, {5}, {3}] # M[{1}] + M[{2, 3}, {5}, {6}, {4}, {1}] # M[]\n sage: _ == M[5,1,1,4,2,3].coproduct()\n True\n sage: M[[1,1,1]] * M[[1,1,2]] # packed words\n M[{1, 2, 3}, {4, 5}, {6}] + M[{1, 2, 3, 4, 5}, {6}]\n + M[{4, 5}, {1, 2, 3}, {6}] + M[{4, 5}, {1, 2, 3, 6}]\n + M[{4, 5}, {6}, {1, 2, 3}]\n sage: M[[1,2,3],].antipode() # ordered set partition\n -M[{1, 2, 3}]\n sage: M[[1], [2], [3]].antipode()\n -M[{1, 2, 3}] - M[{2, 3}, {1}] - M[{3}, {1, 2}] - M[{3}, {2}, {1}]\n sage: x = M[[1],[2],[3]] + 3*M[[2],[1]]\n sage: x.counit()\n 0\n sage: x.antipode()\n 3*M[{1}, {2}] + 3*M[{1, 2}] - M[{1, 2, 3}] - M[{2, 3}, {1}]\n - M[{3}, {1, 2}] - M[{3}, {2}, {1}]\n\n .. rubric:: Ambiguities\n\n Some ambiguity arises when accessing basis vectors with the dictionary syntax,\n i.e., ``M[...]``. A common example is when referencing an ordered set partition\n with one part. For example, in the expression ``M[[1,2]]``, does ``[[1,2]]``\n refer to an ordered set partition or does ``[1,2]`` refer to a packed word?\n We choose the latter: if the received arguments do not behave like a tuple of\n iterables, then view them as describing a packed word. (In the running example,\n one argument is received, which behaves as a tuple of integers.) Here are a\n variety of ways to get the same basis vector::\n\n sage: x = M[1,1]; x\n M[{1, 2}]\n sage: x == M[[1,1]] # treated as word\n True\n sage: x == M[[1,2],] == M[[[1,2]]] # treated as ordered set partitions\n True\n\n sage: M[[1,3],[2]] # treat as ordered set partition\n M[{1, 3}, {2}]\n sage: M[[1,3],[2]] == M[1,2,1] # treat as word\n True\n\n TESTS::\n\n sage: M = WordQuasiSymmetricFunctions(QQ).M()\n sage: a = M[OrderedSetPartition([[1]])]\n sage: b = M[OrderedSetPartitions(1)([[1]])]\n sage: c = M[[1]]\n sage: a == b == c\n True\n\n .. TODO::\n\n - Dendriform structure.\n '
def __init__(self, R):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: A = algebras.WQSym(QQ)\n sage: TestSuite(A).run() # long time\n '
category = HopfAlgebras(R).Graded().Connected()
Parent.__init__(self, base=R, category=category.WithRealizations())
def _repr_(self):
'\n Return the string representation of ``self``.\n\n EXAMPLES::\n\n sage: algebras.WQSym(QQ) # indirect doctest\n Word Quasi-symmetric functions over Rational Field\n '
return 'Word Quasi-symmetric functions over {}'.format(self.base_ring())
def a_realization(self):
'\n Return a particular realization of ``self`` (the `M`-basis).\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(QQ)\n sage: WQSym.a_realization()\n Word Quasi-symmetric functions over Rational Field in the Monomial basis\n '
return self.M()
_shorthands = tuple(['M', 'X', 'C', 'Q', 'Phi'])
class options(GlobalOptions):
'\n Set and display the global options for bases of WordQuasiSymmetricFunctions.\n If no parameters are set, then the function returns a copy of the options\n dictionary.\n\n The ``options`` can be accessed as the method\n :obj:`WordQuasiSymmetricFunctions.options` of\n :class:`WordQuasiSymmetricFunctions` or of any associated basis.\n\n @OPTIONS@\n\n The ``\'words\'`` representation of a basis element of\n :class:`WordQuasiSymmetricFunctions`, indexed by an ordered\n set partition `A`, is the packed word associated to `A`.\n See :meth:`OrderedSetPartition.to_packed_word` for details.)\n\n EXAMPLES::\n\n sage: WQ = WordQuasiSymmetricFunctions(QQ)\n sage: M = WQ.M()\n sage: elt = M[[[1,2]]]*M[[[1]]]; elt\n M[{1, 2}, {3}] + M[{1, 2, 3}] + M[{3}, {1, 2}]\n sage: M.options.display = "tight"\n sage: elt\n M[{1,2},{3}] + M[{1,2,3}] + M[{3},{1,2}]\n sage: M.options.display = "compact"\n sage: elt\n M[12.3] + M[123] + M[3.12]\n sage: WQ.options._reset()\n sage: M.options.objects = "words"\n sage: elt\n M[1, 1, 2] + M[1, 1, 1] + M[2, 2, 1]\n sage: M.options.display = "tight"\n sage: elt\n M[1,1,2] + M[1,1,1] + M[2,2,1]\n sage: WQ.options.display = "compact"\n sage: elt\n M[112] + M[111] + M[221]\n sage: M.options._reset()\n sage: elt\n M[{1, 2}, {3}] + M[{1, 2, 3}] + M[{3}, {1, 2}]\n '
NAME = 'WordQuasiSymmetricFunctions element'
module = 'sage.combinat.chas.wqsym'
option_class = 'WordQuasiSymmetricFunctions'
objects = dict(default='compositions', description='Specifies how basis elements of WordQuasiSymmetricFunctions should be indexed', values=dict(compositions='Indexing the basis by ordered set partitions', words='Indexing the basis by packed words'), case_sensitive=False)
display = dict(default='normal', description='Specifies how basis elements of WordQuasiSymmetricFunctions should be printed', values=dict(normal='Using the normal representation', tight='Dropping spaces after commas', compact='Using a severely compacted representation'), case_sensitive=False)
class Monomial(WQSymBasis_abstract):
'\n The Monomial basis of `WQSym`.\n\n The family `(\\mathbf{M}_u)`, as defined in\n :class:`~sage.combinat.chas.wqsym.WordQuasiSymmetricFunctions`\n with `u` ranging over all packed words, is a basis for the\n free `R`-module `WQSym` and called the *Monomial basis*.\n Here it is labelled using ordered set partitions.\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(QQ)\n sage: M = WQSym.M(); M\n Word Quasi-symmetric functions over Rational Field in the Monomial basis\n sage: sorted(M.basis(2))\n [M[{1}, {2}], M[{2}, {1}], M[{1, 2}]]\n '
_prefix = 'M'
_basis_name = 'Monomial'
def product_on_basis(self, x, y):
'\n Return the (associative) `*` product of the basis elements\n of ``self`` indexed by the ordered set partitions `x` and\n `y`.\n\n This is the shifted quasi-shuffle product of `x` and `y`.\n\n EXAMPLES::\n\n sage: A = algebras.WQSym(QQ).M()\n sage: x = OrderedSetPartition([[1],[2,3]])\n sage: y = OrderedSetPartition([[1,2]])\n sage: z = OrderedSetPartition([[1,2],[3]])\n sage: A.product_on_basis(x, y)\n M[{1}, {2, 3}, {4, 5}] + M[{1}, {2, 3, 4, 5}]\n + M[{1}, {4, 5}, {2, 3}] + M[{1, 4, 5}, {2, 3}]\n + M[{4, 5}, {1}, {2, 3}]\n sage: A.product_on_basis(x, z)\n M[{1}, {2, 3}, {4, 5}, {6}] + M[{1}, {2, 3, 4, 5}, {6}]\n + M[{1}, {4, 5}, {2, 3}, {6}] + M[{1}, {4, 5}, {2, 3, 6}]\n + M[{1}, {4, 5}, {6}, {2, 3}] + M[{1, 4, 5}, {2, 3}, {6}]\n + M[{1, 4, 5}, {2, 3, 6}] + M[{1, 4, 5}, {6}, {2, 3}]\n + M[{4, 5}, {1}, {2, 3}, {6}] + M[{4, 5}, {1}, {2, 3, 6}]\n + M[{4, 5}, {1}, {6}, {2, 3}] + M[{4, 5}, {1, 6}, {2, 3}]\n + M[{4, 5}, {6}, {1}, {2, 3}]\n sage: A.product_on_basis(y, y)\n M[{1, 2}, {3, 4}] + M[{1, 2, 3, 4}] + M[{3, 4}, {1, 2}]\n\n TESTS::\n\n sage: one = OrderedSetPartition([])\n sage: all(A.product_on_basis(one, z) == A(z) == A.basis()[z] for z in OrderedSetPartitions(3))\n True\n sage: all(A.product_on_basis(z, one) == A(z) == A.basis()[z] for z in OrderedSetPartitions(3))\n True\n '
K = self.basis().keys()
if (not x):
return self.monomial(y)
m = max((max(part) for part in x))
x = [set(part) for part in x]
yshift = [[(val + m) for val in part] for part in y]
def union(X, Y):
return X.union(Y)
return self.sum_of_monomials(ShuffleProduct_overlapping(x, yshift, K, union))
def coproduct_on_basis(self, x):
'\n Return the coproduct of ``self`` on the basis element\n indexed by the ordered set partition ``x``.\n\n EXAMPLES::\n\n sage: M = algebras.WQSym(QQ).M()\n\n sage: M.coproduct(M.one()) # indirect doctest\n M[] # M[]\n sage: M.coproduct( M([[1]]) ) # indirect doctest\n M[] # M[{1}] + M[{1}] # M[]\n sage: M.coproduct( M([[1,2]]) )\n M[] # M[{1, 2}] + M[{1, 2}] # M[]\n sage: M.coproduct( M([[1], [2]]) )\n M[] # M[{1}, {2}] + M[{1}] # M[{1}] + M[{1}, {2}] # M[]\n '
if (not x):
return self.one().tensor(self.one())
K = self.indices()
def standardize(P):
base = sorted(sum((list(part) for part in P), []))
d = {val: (i + 1) for (i, val) in enumerate(base)}
return K([[d[x] for x in part] for part in P])
T = self.tensor_square()
return T.sum_of_monomials(((standardize(x[:i]), standardize(x[i:])) for i in range((len(x) + 1))))
M = Monomial
class Characteristic(WQSymBasis_abstract):
'\n The Characteristic basis of `WQSym`.\n\n The *Characteristic basis* is a graded basis `(X_P)` of `WQSym`,\n indexed by ordered set partitions `P`. It is defined by\n\n .. MATH::\n\n X_P = (-1)^{\\ell(P)} \\mathbf{M}_P ,\n\n where `(\\mathbf{M}_P)_P` denotes the Monomial basis,\n and where `\\ell(P)` denotes the number of blocks in an ordered\n set partition `P`.\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(QQ)\n sage: X = WQSym.X(); X\n Word Quasi-symmetric functions over Rational Field in the Characteristic basis\n\n sage: X[[[1,2,3]]] * X[[1,2],[3]]\n X[{1, 2, 3}, {4, 5}, {6}] - X[{1, 2, 3, 4, 5}, {6}]\n + X[{4, 5}, {1, 2, 3}, {6}] - X[{4, 5}, {1, 2, 3, 6}]\n + X[{4, 5}, {6}, {1, 2, 3}]\n\n sage: X[[1, 4], [3], [2]].coproduct()\n X[] # X[{1, 4}, {3}, {2}] + X[{1, 2}] # X[{2}, {1}]\n + X[{1, 3}, {2}] # X[{1}] + X[{1, 4}, {3}, {2}] # X[]\n\n sage: M = WQSym.M()\n sage: M(X[[1, 2, 3],])\n -M[{1, 2, 3}]\n sage: M(X[[1, 3], [2]])\n M[{1, 3}, {2}]\n sage: X(M[[1, 2, 3],])\n -X[{1, 2, 3}]\n sage: X(M[[1, 3], [2]])\n X[{1, 3}, {2}]\n '
_prefix = 'X'
_basis_name = 'Characteristic'
def __init__(self, alg):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: X = algebras.WQSym(QQ).X()\n sage: TestSuite(X).run() # long time\n '
WQSymBasis_abstract.__init__(self, alg)
M = self.realization_of().M()
mone = (- self.base_ring().one())
def sgn(P):
return (mone ** len(P))
self.module_morphism(codomain=M, diagonal=sgn).register_as_coercion()
M.module_morphism(codomain=self, diagonal=sgn).register_as_coercion()
class Element(WQSymBasis_abstract.Element):
def algebraic_complement(self):
'\n Return the image of the element ``self`` of `WQSym`\n under the algebraic complement involution.\n\n See\n :meth:`WQSymBases.ElementMethods.algebraic_complement`\n for a definition of the involution and for examples.\n\n .. SEEALSO::\n\n :meth:`coalgebraic_complement`, :meth:`star_involution`\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: X = WQSym.X()\n sage: X[[1,2],[5,6],[3,4]].algebraic_complement()\n X[{3, 4}, {5, 6}, {1, 2}]\n sage: X[[3], [1, 2], [4]].algebraic_complement()\n X[{4}, {1, 2}, {3}]\n\n TESTS::\n\n sage: M = WQSym.M()\n sage: all(M(X[A]).algebraic_complement() == M(X[A].algebraic_complement())\n ....: for A in OrderedSetPartitions(4))\n True\n '
Q = self.parent()
OSPs = Q.basis().keys()
return Q._from_dict({OSPs(A.reversed()): c for (A, c) in self}, remove_zeros=False)
def coalgebraic_complement(self):
'\n Return the image of the element ``self`` of `WQSym`\n under the coalgebraic complement involution.\n\n See\n :meth:`WQSymBases.ElementMethods.coalgebraic_complement`\n for a definition of the involution and for examples.\n\n .. SEEALSO::\n\n :meth:`algebraic_complement`, :meth:`star_involution`\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: X = WQSym.X()\n sage: X[[1,2],[5,6],[3,4]].coalgebraic_complement()\n X[{5, 6}, {1, 2}, {3, 4}]\n sage: X[[3], [1, 2], [4]].coalgebraic_complement()\n X[{2}, {3, 4}, {1}]\n\n TESTS::\n\n sage: M = WQSym.M()\n sage: all(M(X[A]).coalgebraic_complement()\n ....: == M(X[A].coalgebraic_complement())\n ....: for A in OrderedSetPartitions(4))\n True\n '
Q = self.parent()
OSPs = Q.basis().keys()
return Q._from_dict({OSPs(A.complement()): c for (A, c) in self}, remove_zeros=False)
def star_involution(self):
'\n Return the image of the element ``self`` of `WQSym`\n under the star involution.\n\n See\n :meth:`WQSymBases.ElementMethods.star_involution`\n for a definition of the involution and for examples.\n\n .. SEEALSO::\n\n :meth:`algebraic_complement`, :meth:`coalgebraic_complement`\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: X = WQSym.X()\n sage: X[[1,2],[5,6],[3,4]].star_involution()\n X[{3, 4}, {1, 2}, {5, 6}]\n sage: X[[3], [1, 2], [4]].star_involution()\n X[{1}, {3, 4}, {2}]\n\n TESTS:\n\n sage: M = WQSym.M()\n sage: all(M(X[A]).star_involution() == M(X[A].star_involution())\n ....: for A in OrderedSetPartitions(4))\n True\n '
Q = self.parent()
OSPs = Q.basis().keys()
return Q._from_dict({OSPs(A.complement().reversed()): c for (A, c) in self}, remove_zeros=False)
X = Characteristic
class Cone(WQSymBasis_abstract):
"\n The Cone basis of `WQSym`.\n\n Let `(X_P)_P` denote the Characteristic basis of `WQSym`.\n Denote the quasi-shuffle of two ordered set partitions `A` and\n `B` by `A \\Box B`. For an ordered set partition\n `P = (P_1, \\ldots, P_{\\ell})`, we form a list of ordered set\n partitions `[P] := (P'_1, \\ldots, P'_k)` as follows.\n Define a strictly decreasing sequence of integers\n `\\ell + 1 = i_0 > i_1 > \\cdots > i_k = 1` recursively by\n requiring that `\\min P_{i_j} \\leq \\min P_a` for all `a < i_{j-1}`.\n Set `P'_j = (P_{i_j}, \\ldots, P_{i_{j-1}-1})`.\n\n The *Cone basis* `(C_P)_P` is defined by\n\n .. MATH::\n\n C_P = \\sum_Q X_Q,\n\n where the sum is over all elements `Q` of the quasi-shuffle\n product `P'_1 \\Box P'_2 \\Box \\cdots \\Box P'_k` with\n `[P] = (P'_1, \\ldots, P'_k)`.\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(QQ)\n sage: C = WQSym.C()\n sage: C\n Word Quasi-symmetric functions over Rational Field in the Cone basis\n\n sage: X = WQSym.X()\n sage: X(C[[2,3],[1,4]])\n X[{1, 2, 3, 4}] + X[{1, 4}, {2, 3}] + X[{2, 3}, {1, 4}]\n sage: X(C[[1,4],[2,3]])\n X[{1, 4}, {2, 3}]\n sage: X(C[[2,3],[1],[4]])\n X[{1}, {2, 3}, {4}] + X[{1}, {2, 3, 4}] + X[{1}, {4}, {2, 3}]\n + X[{1, 2, 3}, {4}] + X[{2, 3}, {1}, {4}]\n sage: X(C[[3], [2, 5], [1, 4]])\n X[{1, 2, 3, 4, 5}] + X[{1, 2, 4, 5}, {3}] + X[{1, 3, 4}, {2, 5}]\n + X[{1, 4}, {2, 3, 5}] + X[{1, 4}, {2, 5}, {3}]\n + X[{1, 4}, {3}, {2, 5}] + X[{2, 3, 5}, {1, 4}]\n + X[{2, 5}, {1, 3, 4}] + X[{2, 5}, {1, 4}, {3}]\n + X[{2, 5}, {3}, {1, 4}] + X[{3}, {1, 2, 4, 5}]\n + X[{3}, {1, 4}, {2, 5}] + X[{3}, {2, 5}, {1, 4}]\n sage: C(X[[2,3],[1,4]])\n -C[{1, 2, 3, 4}] - C[{1, 4}, {2, 3}] + C[{2, 3}, {1, 4}]\n\n REFERENCES:\n\n - Section 4 of [Early2017]_\n\n .. TODO::\n\n Experiments suggest that :meth:`algebraic_complement`,\n :meth:`coalgebraic_complement`, and :meth:`star_involution`\n should have reasonable formulas on the C basis; at least\n the coefficients of the outputs on any element of the C\n basis seem to be always `0, 1, -1`.\n Is this true? What is the formula?\n "
_prefix = 'C'
_basis_name = 'Cone'
def __init__(self, alg):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: C = algebras.WQSym(QQ).C()\n sage: TestSuite(C).run() # long time\n '
WQSymBasis_abstract.__init__(self, alg)
X = self.realization_of().X()
phi = self.module_morphism(self._C_to_X, codomain=X, unitriangular='upper')
phi.register_as_coercion()
inv_phi = (~ phi)
inv_phi.register_as_coercion()
M = self.realization_of().M()
M.register_coercion((M.coerce_map_from(X) * phi))
self.register_coercion((inv_phi * X.coerce_map_from(M)))
def some_elements(self):
'\n Return some elements of the word quasi-symmetric functions\n in the Cone basis.\n\n EXAMPLES::\n\n sage: C = algebras.WQSym(QQ).C()\n sage: C.some_elements()\n [C[], C[{1}], C[{1, 2}], C[] + 1/2*C[{1}]]\n '
u = self.one()
o = self([[1]])
s = self.base_ring().an_element()
return [u, o, self([[1, 2]]), (u + (s * o))]
def _C_to_X(self, P):
'\n Return the image of the basis element of ``self`` indexed\n by ``P`` in the Characteristic basis.\n\n EXAMPLES::\n\n sage: C = algebras.WQSym(QQ).C()\n sage: OSP = C.basis().keys()\n sage: C._C_to_X(OSP([[2,3],[1,4]]))\n X[{1, 2, 3, 4}] + X[{1, 4}, {2, 3}] + X[{2, 3}, {1, 4}]\n '
X = self.realization_of().X()
if (not P):
return X.one()
OSP = self.basis().keys()
temp = list(P)
data = []
while temp:
i = min((min(X) for X in temp))
for (j, A) in enumerate(temp):
if (i in A):
data.append(OSP(temp[j:]))
temp = temp[:j]
break
def union(X, Y):
return X.union(Y)
cur = {data[0]: 1}
for B in data[1:]:
ret = {}
for A in cur:
for C in ShuffleProduct_overlapping(A, B, element_constructor=OSP, add=union):
if (C in ret):
ret[C] += cur[A]
else:
ret[C] = cur[A]
cur = ret
return X._from_dict(cur, coerce=True)
C = Cone
class StronglyCoarser(WQSymBasis_abstract):
'\n The Q basis of `WQSym`.\n\n We define a partial order `\\leq` on the set of all ordered\n set partitions as follows: `A \\leq B` if and only if\n `A` is strongly finer than `B` (see\n :meth:`~sage.combinat.set_partition_ordered.OrderedSetPartition.is_strongly_finer`\n for a definition of this).\n\n The *Q basis* `(Q_P)_P` is a basis of `WQSym` indexed by ordered\n set partitions, and is defined by\n\n .. MATH::\n\n Q_P = \\sum \\mathbf{M}_W,\n\n where the sum is over ordered set partitions `W` satisfying\n `P \\leq W`.\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(QQ)\n sage: M = WQSym.M(); Q = WQSym.Q()\n sage: Q\n Word Quasi-symmetric functions over Rational Field in the Q basis\n\n sage: Q(M[[2,3],[1,4]])\n Q[{2, 3}, {1, 4}]\n sage: Q(M[[1,2],[3,4]])\n Q[{1, 2}, {3, 4}] - Q[{1, 2, 3, 4}]\n sage: M(Q[[1,2],[3,4]])\n M[{1, 2}, {3, 4}] + M[{1, 2, 3, 4}]\n sage: M(Q[[2,3],[1],[4]])\n M[{2, 3}, {1}, {4}] + M[{2, 3}, {1, 4}]\n sage: M(Q[[3], [2, 5], [1, 4]])\n M[{3}, {2, 5}, {1, 4}]\n sage: M(Q[[1, 4], [2, 3], [5], [6]])\n M[{1, 4}, {2, 3}, {5}, {6}] + M[{1, 4}, {2, 3}, {5, 6}]\n + M[{1, 4}, {2, 3, 5}, {6}] + M[{1, 4}, {2, 3, 5, 6}]\n\n sage: Q[[1, 3], [2]] * Q[[1], [2]]\n Q[{1, 3}, {2}, {4}, {5}] + Q[{1, 3}, {4}, {2}, {5}]\n + Q[{1, 3}, {4}, {5}, {2}] + Q[{4}, {1, 3}, {2}, {5}]\n + Q[{4}, {1, 3}, {5}, {2}] + Q[{4}, {5}, {1, 3}, {2}]\n\n sage: Q[[1, 3], [2]].coproduct()\n Q[] # Q[{1, 3}, {2}] + Q[{1, 2}] # Q[{1}] + Q[{1, 3}, {2}] # Q[]\n\n REFERENCES:\n\n - Section 6 of [BerZab05]_\n '
_prefix = 'Q'
_basis_name = 'Q'
def __init__(self, alg):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: Q = algebras.WQSym(QQ).Q()\n sage: TestSuite(Q).run() # long time\n '
WQSymBasis_abstract.__init__(self, alg)
M = self.realization_of().M()
phi = self.module_morphism(self._Q_to_M, codomain=M, unitriangular='lower')
phi.register_as_coercion()
phi_inv = M.module_morphism(self._M_to_Q, codomain=self, unitriangular='lower')
phi_inv.register_as_coercion()
def some_elements(self):
'\n Return some elements of the word quasi-symmetric functions\n in the Q basis.\n\n EXAMPLES::\n\n sage: Q = algebras.WQSym(QQ).Q()\n sage: Q.some_elements()\n [Q[], Q[{1}], Q[{1, 2}], Q[] + 1/2*Q[{1}]]\n '
u = self.one()
o = self([[1]])
s = self.base_ring().an_element()
return [u, o, self([[1, 2]]), (u + (s * o))]
def _Q_to_M(self, P):
'\n Return the image of the basis element of ``self`` indexed\n by ``P`` in the Monomial basis.\n\n EXAMPLES::\n\n sage: Q = algebras.WQSym(QQ).Q()\n sage: OSP = Q.basis().keys()\n sage: Q._Q_to_M(OSP([[2,3],[1,4]]))\n M[{2, 3}, {1, 4}]\n sage: Q._Q_to_M(OSP([[1,2],[3,4]]))\n M[{1, 2}, {3, 4}] + M[{1, 2, 3, 4}]\n '
M = self.realization_of().M()
if (not P):
return M.one()
OSP = self.basis().keys()
R = M.base_ring()
one = R.one()
return M._from_dict({OSP(G): one for G in P.strongly_fatter()}, coerce=False)
def _M_to_Q(self, P):
'\n Return the image of the basis element of the monomial\n basis indexed by ``P`` in the Q basis ``self``.\n\n EXAMPLES::\n\n sage: Q = algebras.WQSym(QQ).Q()\n sage: M = algebras.WQSym(QQ).M()\n sage: OSP = Q.basis().keys()\n sage: Q._M_to_Q(OSP([[2,3],[1,4]]))\n Q[{2, 3}, {1, 4}]\n sage: Q._M_to_Q(OSP([[1,2],[3,4]]))\n Q[{1, 2}, {3, 4}] - Q[{1, 2, 3, 4}]\n\n TESTS::\n\n sage: Q = algebras.WQSym(QQ).Q()\n sage: M = algebras.WQSym(QQ).M()\n sage: OSP4 = OrderedSetPartitions(4)\n sage: all(M(Q(M[P])) == M[P] for P in OSP4) # long time\n True\n sage: all(Q(M(Q[P])) == Q[P] for P in OSP4) # long time\n True\n '
Q = self
if (not P):
return Q.one()
OSP = self.basis().keys()
R = self.base_ring()
one = R.one()
lenP = len(P)
def sign(R):
if ((len(R) % 2) == (lenP % 2)):
return one
return (- one)
return Q._from_dict({OSP(G): sign(G) for G in P.strongly_fatter()}, coerce=False)
def product_on_basis(self, x, y):
'\n Return the (associative) `*` product of the basis elements\n of the Q basis ``self`` indexed by the ordered set partitions\n `x` and `y`.\n\n This is the shifted shuffle product of `x` and `y`.\n\n EXAMPLES::\n\n sage: A = algebras.WQSym(QQ).Q()\n sage: x = OrderedSetPartition([[1],[2,3]])\n sage: y = OrderedSetPartition([[1,2]])\n sage: z = OrderedSetPartition([[1,2],[3]])\n sage: A.product_on_basis(x, y)\n Q[{1}, {2, 3}, {4, 5}] + Q[{1}, {4, 5}, {2, 3}]\n + Q[{4, 5}, {1}, {2, 3}]\n sage: A.product_on_basis(x, z)\n Q[{1}, {2, 3}, {4, 5}, {6}] + Q[{1}, {4, 5}, {2, 3}, {6}]\n + Q[{1}, {4, 5}, {6}, {2, 3}] + Q[{4, 5}, {1}, {2, 3}, {6}]\n + Q[{4, 5}, {1}, {6}, {2, 3}] + Q[{4, 5}, {6}, {1}, {2, 3}]\n sage: A.product_on_basis(y, y)\n Q[{1, 2}, {3, 4}] + Q[{3, 4}, {1, 2}]\n\n TESTS::\n\n sage: one = OrderedSetPartition([])\n sage: all(A.product_on_basis(one, z) == A(z) == A.basis()[z] for z in OrderedSetPartitions(3))\n True\n sage: all(A.product_on_basis(z, one) == A(z) == A.basis()[z] for z in OrderedSetPartitions(3))\n True\n '
K = self.basis().keys()
if (not x):
return self.monomial(y)
m = max((max(part) for part in x))
x = [set(part) for part in x]
yshift = [[(val + m) for val in part] for part in y]
return self.sum_of_monomials(ShuffleProduct(x, yshift, K))
def coproduct_on_basis(self, x):
'\n Return the coproduct of ``self`` on the basis element\n indexed by the ordered set partition ``x``.\n\n EXAMPLES::\n\n sage: Q = algebras.WQSym(QQ).Q()\n\n sage: Q.coproduct(Q.one()) # indirect doctest\n Q[] # Q[]\n sage: Q.coproduct( Q([[1]]) ) # indirect doctest\n Q[] # Q[{1}] + Q[{1}] # Q[]\n sage: Q.coproduct( Q([[1,2]]) )\n Q[] # Q[{1, 2}] + Q[{1, 2}] # Q[]\n sage: Q.coproduct( Q([[1], [2]]) )\n Q[] # Q[{1}, {2}] + Q[{1}] # Q[{1}] + Q[{1}, {2}] # Q[]\n sage: Q[[1,2],[3],[4]].coproduct()\n Q[] # Q[{1, 2}, {3}, {4}] + Q[{1, 2}] # Q[{1}, {2}]\n + Q[{1, 2}, {3}] # Q[{1}] + Q[{1, 2}, {3}, {4}] # Q[]\n '
if (not x):
return self.one().tensor(self.one())
K = self.indices()
def standardize(P):
base = sorted(sum((list(part) for part in P), []))
d = {val: (i + 1) for (i, val) in enumerate(base)}
return K([[d[x] for x in part] for part in P])
T = self.tensor_square()
return T.sum_of_monomials(((standardize(x[:i]), standardize(x[i:])) for i in range((len(x) + 1))))
class Element(WQSymBasis_abstract.Element):
def algebraic_complement(self):
'\n Return the image of the element ``self`` of `WQSym`\n under the algebraic complement involution.\n\n See\n :meth:`WQSymBases.ElementMethods.algebraic_complement`\n for a definition of the involution and for examples.\n\n .. SEEALSO::\n\n :meth:`coalgebraic_complement`, :meth:`star_involution`\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: Q = WQSym.Q()\n sage: Q[[1,2],[5,6],[3,4]].algebraic_complement()\n Q[{3, 4}, {1, 2, 5, 6}] + Q[{3, 4}, {5, 6}, {1, 2}]\n - Q[{3, 4, 5, 6}, {1, 2}]\n sage: Q[[3], [1, 2], [4]].algebraic_complement()\n Q[{1, 2, 4}, {3}] + Q[{4}, {1, 2}, {3}] - Q[{4}, {1, 2, 3}]\n\n TESTS::\n\n sage: M = WQSym.M()\n sage: all(M(Q[A]).algebraic_complement() # long time\n ....: == M(Q[A].algebraic_complement())\n ....: for A in OrderedSetPartitions(4))\n True\n '
BR = self.base_ring()
one = BR.one()
mine = (- one)
Q = self.parent()
OSPs = Q.basis().keys()
from sage.data_structures.blas_dict import linear_combination
def img(A):
Rs = [Rr.reversed() for Rr in A.strongly_fatter()]
return {OSPs(P): (one if ((len(R) % 2) == (len(P) % 2)) else mine) for R in Rs for P in R.strongly_fatter()}
return Q._from_dict(linear_combination(((img(A), c) for (A, c) in self)))
def coalgebraic_complement(self):
'\n Return the image of the element ``self`` of `WQSym`\n under the coalgebraic complement involution.\n\n See\n :meth:`WQSymBases.ElementMethods.coalgebraic_complement`\n for a definition of the involution and for examples.\n\n .. SEEALSO::\n\n :meth:`algebraic_complement`, :meth:`star_involution`\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: Q = WQSym.Q()\n sage: Q[[1,2],[5,6],[3,4]].coalgebraic_complement()\n Q[{1, 2, 5, 6}, {3, 4}] + Q[{5, 6}, {1, 2}, {3, 4}] - Q[{5, 6}, {1, 2, 3, 4}]\n sage: Q[[3], [1, 2], [4]].coalgebraic_complement()\n Q[{2}, {1, 3, 4}] + Q[{2}, {3, 4}, {1}] - Q[{2, 3, 4}, {1}]\n\n TESTS::\n\n sage: M = WQSym.M()\n sage: all(M(Q[A]).coalgebraic_complement() # long time\n ....: == M(Q[A].coalgebraic_complement())\n ....: for A in OrderedSetPartitions(4))\n True\n '
BR = self.base_ring()
one = BR.one()
mine = (- one)
Q = self.parent()
OSPs = Q.basis().keys()
from sage.data_structures.blas_dict import linear_combination
def img(A):
Rs = [Rr.complement() for Rr in A.strongly_fatter()]
return {OSPs(P): (one if ((len(R) % 2) == (len(P) % 2)) else mine) for R in Rs for P in R.strongly_fatter()}
return Q._from_dict(linear_combination(((img(A), c) for (A, c) in self)))
def star_involution(self):
'\n Return the image of the element ``self`` of `WQSym`\n under the star involution.\n\n See\n :meth:`WQSymBases.ElementMethods.star_involution`\n for a definition of the involution and for examples.\n\n .. SEEALSO::\n\n :meth:`algebraic_complement`, :meth:`coalgebraic_complement`\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: Q = WQSym.Q()\n sage: Q[[1,2],[5,6],[3,4]].star_involution()\n Q[{3, 4}, {1, 2}, {5, 6}]\n sage: Q[[3], [1, 2], [4]].star_involution()\n Q[{1}, {3, 4}, {2}]\n\n TESTS::\n\n sage: M = WQSym.M()\n sage: all(M(Q[A]).star_involution() == M(Q[A].star_involution())\n ....: for A in OrderedSetPartitions(4))\n True\n '
Q = self.parent()
OSPs = Q.basis().keys()
return Q._from_dict({OSPs(A.complement().reversed()): c for (A, c) in self}, remove_zeros=False)
Q = StronglyCoarser
class StronglyFiner(WQSymBasis_abstract):
'\n The Phi basis of `WQSym`.\n\n We define a partial order `\\leq` on the set of all ordered\n set partitions as follows: `A \\leq B` if and only if\n `A` is strongly finer than `B` (see\n :meth:`~sage.combinat.set_partition_ordered.OrderedSetPartition.is_strongly_finer`\n for a definition of this).\n\n The *Phi basis* `(\\Phi_P)_P` is a basis of `WQSym` indexed by ordered\n set partitions, and is defined by\n\n .. MATH::\n\n \\Phi_P = \\sum \\mathbf{M}_W,\n\n where the sum is over ordered set partitions `W` satisfying\n `W \\leq P`.\n\n Novelli and Thibon introduced this basis in [NovThi06]_\n Section 2.7.2, and called it the quasi-ribbon basis.\n It later reappeared in [MeNoTh11]_ Section 4.3.2.\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(QQ)\n sage: M = WQSym.M(); Phi = WQSym.Phi()\n sage: Phi\n Word Quasi-symmetric functions over Rational Field in the Phi basis\n\n sage: Phi(M[[2,3],[1,4]])\n Phi[{2}, {3}, {1}, {4}] - Phi[{2}, {3}, {1, 4}]\n - Phi[{2, 3}, {1}, {4}] + Phi[{2, 3}, {1, 4}]\n sage: Phi(M[[1,2],[3,4]])\n Phi[{1}, {2}, {3}, {4}] - Phi[{1}, {2}, {3, 4}]\n - Phi[{1, 2}, {3}, {4}] + Phi[{1, 2}, {3, 4}]\n sage: M(Phi[[1,2],[3,4]])\n M[{1}, {2}, {3}, {4}] + M[{1}, {2}, {3, 4}]\n + M[{1, 2}, {3}, {4}] + M[{1, 2}, {3, 4}]\n sage: M(Phi[[2,3],[1],[4]])\n M[{2}, {3}, {1}, {4}] + M[{2, 3}, {1}, {4}]\n sage: M(Phi[[3], [2, 5], [1, 4]])\n M[{3}, {2}, {5}, {1}, {4}] + M[{3}, {2}, {5}, {1, 4}]\n + M[{3}, {2, 5}, {1}, {4}] + M[{3}, {2, 5}, {1, 4}]\n sage: M(Phi[[1, 4], [2, 3], [5], [6]])\n M[{1}, {4}, {2}, {3}, {5}, {6}] + M[{1}, {4}, {2, 3}, {5}, {6}]\n + M[{1, 4}, {2}, {3}, {5}, {6}] + M[{1, 4}, {2, 3}, {5}, {6}]\n\n sage: Phi[[1],] * Phi[[1, 3], [2]]\n Phi[{1, 2, 4}, {3}] + Phi[{2}, {1, 4}, {3}]\n + Phi[{2, 4}, {1, 3}] + Phi[{2, 4}, {3}, {1}]\n sage: Phi[[3, 5], [1, 4], [2]].coproduct()\n Phi[] # Phi[{3, 5}, {1, 4}, {2}]\n + Phi[{1}] # Phi[{4}, {1, 3}, {2}]\n + Phi[{1, 2}] # Phi[{1, 3}, {2}]\n + Phi[{2, 3}, {1}] # Phi[{2}, {1}]\n + Phi[{2, 4}, {1, 3}] # Phi[{1}]\n + Phi[{3, 5}, {1, 4}, {2}] # Phi[]\n\n REFERENCES:\n\n - Section 2.7.2 of [NovThi06]_\n '
_prefix = 'Phi'
_basis_name = 'Phi'
def __init__(self, alg):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: Phi = algebras.WQSym(QQ).Phi()\n sage: TestSuite(Phi).run() # long time\n '
WQSymBasis_abstract.__init__(self, alg)
M = self.realization_of().M()
phi = self.module_morphism(self._Phi_to_M, codomain=M, unitriangular='lower')
phi.register_as_coercion()
phi_inv = M.module_morphism(self._M_to_Phi, codomain=self, unitriangular='lower')
phi_inv.register_as_coercion()
def some_elements(self):
'\n Return some elements of the word quasi-symmetric functions\n in the Phi basis.\n\n EXAMPLES::\n\n sage: Phi = algebras.WQSym(QQ).Phi()\n sage: Phi.some_elements()\n [Phi[], Phi[{1}], Phi[{1, 2}], Phi[] + 1/2*Phi[{1}]]\n '
u = self.one()
o = self([[1]])
s = self.base_ring().an_element()
return [u, o, self([[1, 2]]), (u + (s * o))]
def _Phi_to_M(self, P):
'\n Return the image of the basis element of ``self`` indexed\n by ``P`` in the Monomial basis.\n\n EXAMPLES::\n\n sage: Phi = algebras.WQSym(QQ).Phi()\n sage: OSP = Phi.basis().keys()\n sage: Phi._Phi_to_M(OSP([[2,3],[1,4]]))\n M[{2}, {3}, {1}, {4}] + M[{2}, {3}, {1, 4}]\n + M[{2, 3}, {1}, {4}] + M[{2, 3}, {1, 4}]\n sage: Phi._Phi_to_M(OSP([[1,2],[3,4]]))\n M[{1}, {2}, {3}, {4}] + M[{1}, {2}, {3, 4}]\n + M[{1, 2}, {3}, {4}] + M[{1, 2}, {3, 4}]\n '
M = self.realization_of().M()
if (not P):
return M.one()
OSP = self.basis().keys()
R = M.base_ring()
one = R.one()
return M._from_dict({OSP(G): one for G in P.strongly_finer()}, coerce=False)
def _M_to_Phi(self, P):
'\n Return the image of the basis element of the monomial\n basis indexed by ``P`` in the Phi basis ``self``.\n\n EXAMPLES::\n\n sage: Phi = algebras.WQSym(QQ).Phi()\n sage: M = algebras.WQSym(QQ).M()\n sage: OSP = Phi.basis().keys()\n sage: Phi._M_to_Phi(OSP([[2,3],[1,4]]))\n Phi[{2}, {3}, {1}, {4}] - Phi[{2}, {3}, {1, 4}]\n - Phi[{2, 3}, {1}, {4}] + Phi[{2, 3}, {1, 4}]\n sage: Phi._M_to_Phi(OSP([[1,2],[3,4]]))\n Phi[{1}, {2}, {3}, {4}] - Phi[{1}, {2}, {3, 4}]\n - Phi[{1, 2}, {3}, {4}] + Phi[{1, 2}, {3, 4}]\n\n TESTS::\n\n sage: Phi = algebras.WQSym(QQ).Phi()\n sage: M = algebras.WQSym(QQ).M()\n sage: OSP4 = OrderedSetPartitions(4)\n sage: all(M(Phi(M[P])) == M[P] for P in OSP4) # long time\n True\n sage: all(Phi(M(Phi[P])) == Phi[P] for P in OSP4) # long time\n True\n '
Phi = self
if (not P):
return Phi.one()
OSP = self.basis().keys()
R = self.base_ring()
one = R.one()
lenP = len(P)
def sign(R):
if ((len(R) % 2) == (lenP % 2)):
return one
return (- one)
return Phi._from_dict({OSP(G): sign(G) for G in P.strongly_finer()}, coerce=False)
def product_on_basis(self, x, y):
'\n Return the (associative) `*` product of the basis elements\n of the Phi basis ``self`` indexed by the ordered set partitions\n `x` and `y`.\n\n This is obtained by the following algorithm (going back to\n [NovThi06]_):\n\n Let `x` be an ordered set partition of `[m]`, and `y` an\n ordered set partition of `[n]`.\n Transform `x` into a list `u` of all the `m` elements of `[m]`\n by writing out each block of `x` (in increasing order) and\n putting bars between each two consecutive blocks; this is\n called a barred permutation.\n Do the same for `y`, but also shift each entry of the\n resulting barred permutation by `m`. Let `v` be the barred\n permutation of `[m+n] \\setminus [m]` thus obtained.\n Now, shuffle the two barred permutations `u` and `v`\n (ignoring the bars) in all the `\\binom{n+m}{n}` possible ways.\n For each shuffle obtained, place bars between some entries\n of the shuffle, according to the following rule:\n\n * If two consecutive entries of the shuffle both come from\n `u`, then place a bar between them if the corresponding\n entries of `u` had a bar between them.\n\n * If the first of two consecutive entries of the shuffle\n comes from `v` and the second from `u`, then place a bar\n between them.\n\n This results in a barred permutation of `[m+n]`.\n Transform it into an ordered set partition of `[m+n]`,\n by treating the bars as dividers separating consecutive\n blocks.\n\n The product `\\Phi_x \\Phi_y` is the sum of `\\Phi_p` with\n `p` ranging over all ordered set partitions obtained this\n way.\n\n EXAMPLES::\n\n sage: A = algebras.WQSym(QQ).Phi()\n sage: x = OrderedSetPartition([[1],[2,3]])\n sage: y = OrderedSetPartition([[1,2]])\n sage: z = OrderedSetPartition([[1,2],[3]])\n sage: A.product_on_basis(x, y)\n Phi[{1}, {2, 3, 4, 5}] + Phi[{1}, {2, 4}, {3, 5}]\n + Phi[{1}, {2, 4, 5}, {3}] + Phi[{1, 4}, {2, 3, 5}]\n + Phi[{1, 4}, {2, 5}, {3}] + Phi[{1, 4, 5}, {2, 3}]\n + Phi[{4}, {1}, {2, 3, 5}] + Phi[{4}, {1}, {2, 5}, {3}]\n + Phi[{4}, {1, 5}, {2, 3}] + Phi[{4, 5}, {1}, {2, 3}]\n sage: A.product_on_basis(x, z)\n Phi[{1}, {2, 3, 4, 5}, {6}] + Phi[{1}, {2, 4}, {3, 5}, {6}]\n + Phi[{1}, {2, 4, 5}, {3, 6}] + Phi[{1}, {2, 4, 5}, {6}, {3}]\n + Phi[{1, 4}, {2, 3, 5}, {6}] + Phi[{1, 4}, {2, 5}, {3, 6}]\n + Phi[{1, 4}, {2, 5}, {6}, {3}] + Phi[{1, 4, 5}, {2, 3, 6}]\n + Phi[{1, 4, 5}, {2, 6}, {3}] + Phi[{1, 4, 5}, {6}, {2, 3}]\n + Phi[{4}, {1}, {2, 3, 5}, {6}]\n + Phi[{4}, {1}, {2, 5}, {3, 6}]\n + Phi[{4}, {1}, {2, 5}, {6}, {3}]\n + Phi[{4}, {1, 5}, {2, 3, 6}] + Phi[{4}, {1, 5}, {2, 6}, {3}]\n + Phi[{4}, {1, 5}, {6}, {2, 3}] + Phi[{4, 5}, {1}, {2, 3, 6}]\n + Phi[{4, 5}, {1}, {2, 6}, {3}] + Phi[{4, 5}, {1, 6}, {2, 3}]\n + Phi[{4, 5}, {6}, {1}, {2, 3}]\n sage: A.product_on_basis(y, y)\n Phi[{1, 2, 3, 4}] + Phi[{1, 3}, {2, 4}] + Phi[{1, 3, 4}, {2}]\n + Phi[{3}, {1, 2, 4}] + Phi[{3}, {1, 4}, {2}]\n + Phi[{3, 4}, {1, 2}]\n\n TESTS::\n\n sage: one = OrderedSetPartition([])\n sage: all(A.product_on_basis(one, z) == A(z) == A.basis()[z] for z in OrderedSetPartitions(3))\n True\n sage: all(A.product_on_basis(z, one) == A(z) == A.basis()[z] for z in OrderedSetPartitions(3))\n True\n sage: M = algebras.WQSym(QQ).M()\n sage: x = A[[2, 4], [1, 3]]\n sage: y = A[[1, 3], [2]]\n sage: A(M(x) * M(y)) == x * y # long time\n True\n sage: A(M(x) ** 2) == x**2 # long time\n True\n sage: A(M(y) ** 2) == y**2\n True\n '
K = self.basis().keys()
if (not x):
return self.monomial(y)
if (not y):
return self.monomial(x)
xlist = [(j, (k == 0)) for part in x for (k, j) in enumerate(sorted(part))]
m = max((max(part) for part in x))
ylist = [((m + j), (k == 0)) for part in y for (k, j) in enumerate(sorted(part))]
def digest(s):
s0 = [p[0] for p in s]
s1 = [p[1] for p in s]
N = len(s)
bars = ([False] * N)
for i in range((N - 1)):
s0i = s0[i]
s0i1 = s0[(i + 1)]
if ((s0i <= m) and (s0i1 <= m)):
bars[(i + 1)] = s1[(i + 1)]
elif ((s0i > m) and (s0i1 > m)):
bars[(i + 1)] = s1[(i + 1)]
elif ((s0i > m) and (s0i1 <= m)):
bars[(i + 1)] = True
blocks = []
block = []
for i in range(N):
if bars[i]:
blocks.append(block)
block = [s0[i]]
else:
block.append(s0[i])
blocks.append(block)
return K(blocks)
return self.sum_of_monomials((digest(s) for s in ShuffleProduct(xlist, ylist)))
def coproduct_on_basis(self, x):
'\n Return the coproduct of ``self`` on the basis element\n indexed by the ordered set partition ``x``.\n\n The coproduct of the basis element `\\Phi_x` indexed by\n an ordered set partition `x` of `[n]` can be computed by the\n following formula ([NovThi06]_):\n\n .. MATH::\n\n \\Delta \\Phi_x\n = \\sum \\Phi_y \\otimes \\Phi_z ,\n\n where the sum ranges over all pairs `(y, z)` of ordered set\n partitions `y` and `z` such that:\n\n * `y` and `z` are ordered set partitions of two complementary\n subsets of `[n]`;\n\n * `x` is obtained either by concatenating `y` and `z`, or by\n first concatenating `y` and `z` and then merging the two\n "middle blocks" (i.e., the last block of `y` and the first\n block of `z`); in the latter case, the maximum of the last\n block of `y` has to be smaller than the minimum of the first\n block of `z` (so that when merging these blocks, their\n entries don\'t need to be sorted).\n\n EXAMPLES::\n\n sage: Phi = algebras.WQSym(QQ).Phi()\n\n sage: Phi.coproduct(Phi.one()) # indirect doctest\n Phi[] # Phi[]\n sage: Phi.coproduct( Phi([[1]]) ) # indirect doctest\n Phi[] # Phi[{1}] + Phi[{1}] # Phi[]\n sage: Phi.coproduct( Phi([[1,2]]) )\n Phi[] # Phi[{1, 2}] + Phi[{1}] # Phi[{1}] + Phi[{1, 2}] # Phi[]\n sage: Phi.coproduct( Phi([[1], [2]]) )\n Phi[] # Phi[{1}, {2}] + Phi[{1}] # Phi[{1}] + Phi[{1}, {2}] # Phi[]\n sage: Phi[[1,2],[3],[4]].coproduct()\n Phi[] # Phi[{1, 2}, {3}, {4}] + Phi[{1}] # Phi[{1}, {2}, {3}]\n + Phi[{1, 2}] # Phi[{1}, {2}] + Phi[{1, 2}, {3}] # Phi[{1}]\n + Phi[{1, 2}, {3}, {4}] # Phi[]\n\n TESTS::\n\n sage: M = algebras.WQSym(QQ).M()\n sage: x = Phi[[2, 4], [6], [1, 3], [5, 7]]\n sage: MM = M.tensor(M); AA = Phi.tensor(Phi)\n sage: AA(M(x).coproduct()) == x.coproduct()\n True\n '
if (not x):
return self.one().tensor(self.one())
K = self.indices()
def standardize(P):
base = sorted(sum((list(part) for part in P), []))
d = {val: (i + 1) for (i, val) in enumerate(base)}
return K([[d[x] for x in part] for part in P])
deconcatenates = [(x[:i], x[i:]) for i in range((len(x) + 1))]
for i in range(len(x)):
xi = sorted(x[i])
for j in range(1, len(xi)):
left = K((list(x[:i]) + [xi[:j]]))
right = K(([xi[j:]] + list(x[(i + 1):])))
deconcatenates.append((left, right))
T = self.tensor_square()
return T.sum_of_monomials(((standardize(left), standardize(right)) for (left, right) in deconcatenates))
class Element(WQSymBasis_abstract.Element):
def algebraic_complement(self):
'\n Return the image of the element ``self`` of `WQSym`\n under the algebraic complement involution.\n\n See\n :meth:`WQSymBases.ElementMethods.algebraic_complement`\n for a definition of the involution and for examples.\n\n .. SEEALSO::\n\n :meth:`coalgebraic_complement`, :meth:`star_involution`\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: Phi = WQSym.Phi()\n sage: Phi[[1],[2,4],[3]].algebraic_complement()\n -Phi[{3}, {2}, {4}, {1}] + Phi[{3}, {2, 4}, {1}] + Phi[{3}, {4}, {2}, {1}]\n sage: Phi[[1],[2,3],[4]].algebraic_complement()\n -Phi[{4}, {2}, {3}, {1}] + Phi[{4}, {2, 3}, {1}] + Phi[{4}, {3}, {2}, {1}]\n\n TESTS::\n\n sage: M = WQSym.M()\n sage: all(M(Phi[A]).algebraic_complement()\n ....: == M(Phi[A].algebraic_complement())\n ....: for A in OrderedSetPartitions(4))\n True\n '
BR = self.base_ring()
one = BR.one()
mine = (- one)
Phi = self.parent()
OSPs = Phi.basis().keys()
from sage.data_structures.blas_dict import linear_combination
def img(A):
Rs = [Rr.reversed() for Rr in A.strongly_finer()]
return {OSPs(P): (one if ((len(R) % 2) == (len(P) % 2)) else mine) for R in Rs for P in R.strongly_finer()}
return Phi._from_dict(linear_combination(((img(A), c) for (A, c) in self)))
def coalgebraic_complement(self):
'\n Return the image of the element ``self`` of `WQSym`\n under the coalgebraic complement involution.\n\n See\n :meth:`WQSymBases.ElementMethods.coalgebraic_complement`\n for a definition of the involution and for examples.\n\n .. SEEALSO::\n\n :meth:`algebraic_complement`, :meth:`star_involution`\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: Phi = WQSym.Phi()\n sage: Phi[[1],[2],[3,4]].coalgebraic_complement()\n -Phi[{4}, {3}, {1}, {2}] + Phi[{4}, {3}, {1, 2}] + Phi[{4}, {3}, {2}, {1}]\n sage: Phi[[2],[1,4],[3]].coalgebraic_complement()\n -Phi[{3}, {1}, {4}, {2}] + Phi[{3}, {1, 4}, {2}] + Phi[{3}, {4}, {1}, {2}]\n\n TESTS::\n\n sage: M = WQSym.M()\n sage: all(M(Phi[A]).coalgebraic_complement()\n ....: == M(Phi[A].coalgebraic_complement())\n ....: for A in OrderedSetPartitions(4))\n True\n '
BR = self.base_ring()
one = BR.one()
mine = (- one)
Phi = self.parent()
OSPs = Phi.basis().keys()
from sage.data_structures.blas_dict import linear_combination
def img(A):
Rs = [Rr.complement() for Rr in A.strongly_finer()]
return {OSPs(P): (one if ((len(R) % 2) == (len(P) % 2)) else mine) for R in Rs for P in R.strongly_finer()}
return Phi._from_dict(linear_combination(((img(A), c) for (A, c) in self)))
def star_involution(self):
'\n Return the image of the element ``self`` of `WQSym`\n under the star involution.\n\n See\n :meth:`WQSymBases.ElementMethods.star_involution`\n for a definition of the involution and for examples.\n\n .. SEEALSO::\n\n :meth:`algebraic_complement`, :meth:`coalgebraic_complement`\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: Phi = WQSym.Phi()\n sage: Phi[[1,2],[5,6],[3,4]].star_involution()\n Phi[{3, 4}, {1, 2}, {5, 6}]\n sage: Phi[[3], [1, 2], [4]].star_involution()\n Phi[{1}, {3, 4}, {2}]\n\n TESTS::\n\n sage: M = WQSym.M()\n sage: all(M(Phi[A]).star_involution() == M(Phi[A].star_involution())\n ....: for A in OrderedSetPartitions(4))\n True\n '
Phi = self.parent()
OSPs = Phi.basis().keys()
return Phi._from_dict({OSPs(A.complement().reversed()): c for (A, c) in self}, remove_zeros=False)
Phi = StronglyFiner
|
class WQSymBases(Category_realization_of_parent):
'\n The category of bases of `WQSym`.\n '
def __init__(self, base, graded):
'\n Initialize ``self``.\n\n INPUT:\n\n - ``base`` -- an instance of `WQSym`\n - ``graded`` -- boolean; if the basis is graded or filtered\n\n TESTS::\n\n sage: from sage.combinat.chas.wqsym import WQSymBases\n sage: WQSym = algebras.WQSym(ZZ)\n sage: bases = WQSymBases(WQSym, True)\n sage: WQSym.M() in bases\n True\n '
self._graded = graded
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.chas.wqsym import WQSymBases\n sage: WQSym = algebras.WQSym(ZZ)\n sage: WQSymBases(WQSym, True)\n Category of graded bases of Word Quasi-symmetric functions over Integer Ring\n sage: WQSymBases(WQSym, False)\n Category of filtered bases of Word Quasi-symmetric functions over Integer Ring\n '
if self._graded:
type_str = 'graded'
else:
type_str = 'filtered'
return 'Category of {} bases of {}'.format(type_str, self.base())
def super_categories(self):
'\n The super categories of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.chas.wqsym import WQSymBases\n sage: WQSym = algebras.WQSym(ZZ)\n sage: bases = WQSymBases(WQSym, True)\n sage: bases.super_categories()\n [Category of realizations of Word 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\n sage: bases = WQSymBases(WQSym, False)\n sage: bases.super_categories()\n [Category of realizations of Word 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 Join of Category of filtered connected Hopf algebras with basis over Integer Ring\n and Category of graded algebras over Integer Ring\n and Category of graded coalgebras over Integer Ring]\n '
R = self.base().base_ring()
cat = HopfAlgebras(R).Graded().WithBasis()
if self._graded:
cat = cat.Graded()
else:
cat = cat.Filtered()
return [self.base().Realizations(), HopfAlgebras(R).Graded().Realizations(), cat.Connected()]
class ParentMethods():
def _repr_(self):
'\n Text representation of this basis of `WQSym`.\n\n EXAMPLES::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: WQSym.M()\n Word Quasi-symmetric functions over Integer Ring in the Monomial 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`` -- an ordered set partition\n\n EXAMPLES::\n\n sage: M = algebras.WQSym(QQ).M()\n sage: M[1, 2, 1] # pass a word\n M[{1, 3}, {2}]\n sage: _ == M[[1, 2, 1]] == M[Word([1,2,1])]\n True\n sage: M[[1, 2, 3]]\n M[{1}, {2}, {3}]\n\n sage: M[[[1, 2, 3]]] # pass an ordered set partition\n M[{1, 2, 3}]\n sage: _ == M[[1,2,3],] == M[OrderedSetPartition([[1,2,3]])]\n True\n sage: M[[1,3],[2]]\n M[{1, 3}, {2}]\n\n TESTS::\n\n sage: M[[]]\n M[]\n sage: M[1, 2, 1] == M[Word([2,3,2])] == M[Word('aca')]\n True\n sage: M[[[1,2]]] == M[1,1] == M[1/1,2/2] == M[2/1,2/1] == M['aa']\n True\n sage: M[1] == M[1,] == M[Word([1])] == M[OrderedSetPartition([[1]])] == M[[1],]\n True\n "
if (p in ZZ):
p = [ZZ(p)]
if all(((s in ZZ) for s in p)):
return self.monomial(self._indices.from_finite_word([ZZ(s) for s in p]))
if all((isinstance(s, str) for s in p)):
return self.monomial(self._indices.from_finite_word(p))
try:
return self.monomial(self._indices(p))
except TypeError:
raise ValueError(('cannot convert %s into an element of %s' % (p, self._indices)))
def is_field(self, proof=True):
'\n Return whether ``self`` is a field.\n\n EXAMPLES::\n\n sage: M = algebras.WQSym(QQ).M()\n sage: M.is_field()\n False\n '
return False
def is_commutative(self):
'\n Return whether ``self`` is commutative.\n\n EXAMPLES::\n\n sage: M = algebras.WQSym(ZZ).M()\n sage: M.is_commutative()\n False\n '
return self.base_ring().is_zero()
def one_basis(self):
'\n Return the index of the unit.\n\n EXAMPLES::\n\n sage: A = algebras.WQSym(QQ).M()\n sage: A.one_basis()\n []\n '
OSP = self.basis().keys()
return OSP([])
def degree_on_basis(self, t):
'\n Return the degree of an ordered set partition in\n the algebra of word quasi-symmetric functions.\n\n This is the sum of the sizes of the blocks of the\n ordered set partition.\n\n EXAMPLES::\n\n sage: A = algebras.WQSym(QQ).M()\n sage: u = OrderedSetPartition([[2,1],])\n sage: A.degree_on_basis(u)\n 2\n sage: u = OrderedSetPartition([[2], [1]])\n sage: A.degree_on_basis(u)\n 2\n '
return sum((len(part) for part in t))
class ElementMethods():
def algebraic_complement(self):
"\n Return the image of the element ``self`` of `WQSym`\n under the algebraic complement involution.\n\n If `u = (u_1, u_2, \\ldots, u_n)` is a packed word\n that contains the letters `1, 2, \\ldots, k` and no\n others, then the *complement* of `u` is defined to\n be the packed word\n `\\overline{u} := (k+1 - u_1, k+1 - u_2, \\ldots, k+1 - u_n)`.\n\n The algebraic complement involution is defined as the\n linear map `WQSym \\to WQSym` that sends each basis\n element `\\mathbf{M}_u` of the monomial basis of `WQSym`\n to the basis element `\\mathbf{M}_{\\overline{u}}`.\n This is a graded algebra automorphism and a coalgebra\n anti-automorphism of `WQSym`.\n Denoting by `\\overline{f}` the image of an element\n `f \\in WQSym` under the algebraic complement involution,\n it can be shown that every packed word `u` satisfies\n\n .. MATH::\n\n \\overline{\\mathbf{M}_u} = \\mathbf{M}_{\\overline{u}},\n \\qquad \\overline{X_u} = X_{\\overline{u}},\n\n where standard notations for classical bases of `WQSym`\n are being used (that is, `\\mathbf{M}` for the monomial\n basis, and `X` for the characteristic basis).\n\n This can be restated in terms of ordered set partitions:\n For any ordered set partition `R = (R_1, R_2, \\ldots, R_k)`,\n let `R^r` denote the ordered set partition\n `(R_k, R_{k-1}, \\ldots, R_1)`; this is known as\n the *reversal* of `R`. Then,\n\n .. MATH::\n\n \\overline{\\mathbf{M}_A} = \\mathbf{M}_{A^r}, \\qquad\n \\overline{X_A} = X_{A^r}\n\n for any ordered set partition `A`.\n\n The formula describing algebraic complements on the Q basis\n (:class:`WordQuasiSymmetricFunctions.StronglyCoarser`)\n is more complicated, and requires some definitions.\n We define a partial order `\\leq` on the set of all ordered\n set partitions as follows: `A \\leq B` if and only if\n `A` is strongly finer than `B` (see\n :meth:`~sage.combinat.set_partition_ordered.OrderedSetPartition.is_strongly_finer`\n for a definition of this).\n The *length* `\\ell(R)` of an ordered set partition `R` shall\n be defined as the number of parts of `R`.\n Use the notation `Q` for the Q basis.\n For any ordered set partition `A` of `[n]`, we have\n\n .. MATH::\n\n \\overline{Q_A} = \\sum_P c_{A, P} Q_P,\n\n where the sum is over all ordered set partitions `P` of\n `[n]`, and where the coefficient `c_{A, P}` is defined\n as follows:\n\n * If there exists an ordered set partition `R` satisfying\n `R \\leq P` and `A \\leq R^r`, then this `R` is unique,\n and `c_{A, P} = \\left(-1\\right)^{\\ell(R) - \\ell(P)}`.\n\n * If there exists no such `R`, then `c_{A, P} = 0`.\n\n The formula describing algebraic complements on the `\\Phi`\n basis (:class:`WordQuasiSymmetricFunctions.StronglyFiner`)\n is identical to the above formula for the Q basis, except\n that the `\\leq` sign has to be replaced by `\\geq` in the\n definition of the coefficients `c_{A, P}`. In fact, both\n formulas are particular cases of a general formula for\n involutions:\n Assume that `V` is an (additive) abelian group, and that\n `I` is a poset. For each `i \\in I`, let `M_i` be an element\n of `V`. Also, let `\\omega` be an involution of the set `I`\n (not necessarily order-preserving or order-reversing),\n and let `\\omega'` be an involutive group endomorphism of\n `V` such that each `i \\in I` satisfies\n `\\omega'(M_i) = M_{\\omega(i)}`.\n For each `i \\in I`, let `F_i = \\sum_{j \\geq i} M_j`,\n where we assume that the sum is finite.\n Then, each `i \\in I` satisfies\n\n .. MATH::\n\n \\omega'(F_i)\n = \\sum_j \\sum_{\\substack{k \\leq j; \\\\ \\omega(k) \\geq i}}\n \\mu(k, j) F_j,\n\n where `\\mu` denotes the Möbius function. This formula becomes\n particularly useful when the `k` satisfying `k \\leq j`\n and `\\omega(k) \\geq i` is unique (if it exists).\n In our situation, `V` is `WQSym`, and `I` is the set of\n ordered set partitions equipped either with the `\\leq` partial\n order defined above or with its opposite order.\n The `M_i` is the `\\mathbf{M}_A`, whereas the `F_i` is either\n `Q_i` or `\\Phi_i`.\n\n If we denote the star involution\n (:meth:`~sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.star_involution`)\n of the quasisymmetric functions by `f \\mapsto f^{\\ast}`,\n and if we let `\\pi` be the canonical projection\n `WQSym \\to QSym`, then each `f \\in WQSym` satisfies\n `\\pi(\\overline{f}) = (\\pi(f))^{\\ast}`.\n\n .. SEEALSO::\n\n :meth:`coalgebraic_complement`, :meth:`star_involution`\n\n EXAMPLES:\n\n Recall that the index set for the bases of `WQSym` is\n given by ordered set partitions, not packed words.\n Translated into the language of ordered set partitions,\n the algebraic complement involution acts on the\n Monomial basis by reversing the ordered set partition.\n In other words, we have\n\n .. MATH::\n\n \\overline{\\mathbf{M}_{(P_1, P_2, \\ldots, P_k)}}\n = \\mathbf{M}_{(P_k, P_{k-1}, \\ldots, P_1)}\n\n for any standard ordered set partition\n `(P_1, P_2, \\ldots, P_k)`. Let us check this in practice::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: M = WQSym.M()\n sage: M[[1,3],[2]].algebraic_complement()\n M[{2}, {1, 3}]\n sage: M[[1,4],[2,5],[3,6]].algebraic_complement()\n M[{3, 6}, {2, 5}, {1, 4}]\n sage: (3*M[[1]] - 4*M[[]] + 5*M[[1],[2]]).algebraic_complement()\n -4*M[] + 3*M[{1}] + 5*M[{2}, {1}]\n sage: X = WQSym.X()\n sage: X[[1,3],[2]].algebraic_complement()\n X[{2}, {1, 3}]\n sage: C = WQSym.C()\n sage: C[[1,3],[2]].algebraic_complement()\n -C[{1, 2, 3}] - C[{1, 3}, {2}] + C[{2}, {1, 3}]\n sage: Q = WQSym.Q()\n sage: Q[[1,2],[5,6],[3,4]].algebraic_complement()\n Q[{3, 4}, {1, 2, 5, 6}] + Q[{3, 4}, {5, 6}, {1, 2}] - Q[{3, 4, 5, 6}, {1, 2}]\n sage: Phi = WQSym.Phi()\n sage: Phi[[2], [1,3]].algebraic_complement()\n -Phi[{1}, {3}, {2}] + Phi[{1, 3}, {2}] + Phi[{3}, {1}, {2}]\n\n The algebraic complement involution intertwines the antipode\n and the inverse of the antipode::\n\n sage: all( M(I).antipode().algebraic_complement().antipode() # long time\n ....: == M(I).algebraic_complement()\n ....: for I in OrderedSetPartitions(4) )\n True\n\n Testing the `\\pi(\\overline{f}) = (\\pi(f))^{\\ast}` relation::\n\n sage: all( M[I].algebraic_complement().to_quasisymmetric_function()\n ....: == M[I].to_quasisymmetric_function().star_involution()\n ....: for I in OrderedSetPartitions(4) )\n True\n\n .. TODO::\n\n Check further commutative squares.\n "
parent = self.parent()
M = parent.realization_of().M()
dct = {I.reversed(): coeff for (I, coeff) in M(self)}
return parent(M._from_dict(dct, remove_zeros=False))
def coalgebraic_complement(self):
'\n Return the image of the element ``self`` of `WQSym`\n under the coalgebraic complement involution.\n\n If `u = (u_1, u_2, \\ldots, u_n)` is a packed word,\n then the *reversal* of `u` is defined to be the\n packed word `(u_n, u_{n-1}, \\ldots, u_1)`.\n This reversal is denoted by `u^r`.\n\n The coalgebraic complement involution is defined as the\n linear map `WQSym \\to WQSym` that sends each basis\n element `\\mathbf{M}_u` of the monomial basis of `WQSym`\n to the basis element `\\mathbf{M}_{u^r}`.\n This is a graded coalgebra automorphism and an algebra\n anti-automorphism of `WQSym`.\n Denoting by `f^r` the image of an element `f \\in WQSym`\n under the coalgebraic complement involution,\n it can be shown that every packed word `u` satisfies\n\n .. MATH::\n\n (\\mathbf{M}_u)^r = \\mathbf{M}_{u^r}, \\qquad\n (X_u)^r = X_{u^r},\n\n where standard notations for classical bases of `WQSym`\n are being used (that is, `\\mathbf{M}` for the monomial\n basis, and `X` for the characteristic basis).\n\n This can be restated in terms of ordered set partitions:\n For any ordered set partition `R` of `[n]`, let\n `\\overline{R}` denote the complement of `R` (defined in\n :meth:`~sage.combinat.set_partition_ordered.OrderedSetPartition.complement`).\n Then,\n\n .. MATH::\n\n (\\mathbf{M}_A)^r = \\mathbf{M}_{\\overline{A}}, \\qquad\n (X_A)^r = X_{\\overline{A}}\n\n for any ordered set partition `A`.\n\n Recall that `WQSym` is a subring of the ring of all\n bounded-degree noncommutative power series in countably many\n indeterminates. The latter ring has an obvious continuous\n algebra anti-endomorphism which sends each letter `x_i` to\n `x_i` (and thus sends each monomial\n `x_{i_1} x_{i_2} \\cdots x_{i_n}` to\n `x_{i_n} x_{i_{n-1}} \\cdots x_{i_1}`).\n This anti-endomorphism is actually an involution.\n The coalgebraic complement involution is simply the\n restriction of this involution to the subring `WQSym`.\n\n The formula describing coalgebraic complements on the Q basis\n (:class:`WordQuasiSymmetricFunctions.StronglyCoarser`)\n is more complicated, and requires some definitions.\n We define a partial order `\\leq` on the set of all ordered\n set partitions as follows: `A \\leq B` if and only if\n `A` is strongly finer than `B` (see\n :meth:`~sage.combinat.set_partition_ordered.OrderedSetPartition.is_strongly_finer`\n for a definition of this).\n The *length* `\\ell(R)` of an ordered set partition `R` shall\n be defined as the number of parts of `R`.\n Use the notation `Q` for the Q basis.\n For any ordered set partition `A` of `[n]`, we have\n\n .. MATH::\n\n (Q_A)^r = \\sum_P c_{A, P} Q_P ,\n\n where the sum is over all ordered set partitions `P` of\n `[n]`, and where the coefficient `c_{A, P}` is defined\n as follows:\n\n * If there exists an ordered set partition `R` satisfying\n `R \\leq P` and `A \\leq \\overline{R}`, then this `R` is\n unique,\n and `c_{A, P} = \\left(-1\\right)^{\\ell(R) - \\ell(P)}`.\n\n * If there exists no such `R`, then `c_{A, P} = 0`.\n\n The formula describing coalgebraic complements on the `\\Phi`\n basis (:class:`WordQuasiSymmetricFunctions.StronglyFiner`)\n is identical to the above formula for the Q basis, except\n that the `\\leq` sign has to be replaced by `\\geq` in the\n definition of the coefficients `c_{A, P}`. In fact, both\n formulas are particular cases of the general formula for\n involutions described in the documentation of\n :meth:`algebraic_complement`.\n\n If we let `\\pi` be the canonical projection\n `WQSym \\to QSym`, then each `f \\in WQSym` satisfies\n `\\pi(f^r) = \\pi(f)`.\n\n .. SEEALSO::\n\n :meth:`algebraic_complement`, :meth:`star_involution`\n\n EXAMPLES:\n\n Recall that the index set for the bases of `WQSym` is\n given by ordered set partitions, not packed words.\n Translated into the language of ordered set partitions,\n the coalgebraic complement involution acts on the\n Monomial basis by complementing the ordered set partition.\n In other words, we have\n\n .. MATH::\n\n (\\mathbf{M}_A)^r = \\mathbf{M}_{\\overline{A}}\n\n for any standard ordered set partition `P`.\n Let us check this in practice::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: M = WQSym.M()\n sage: M[[1,3],[2]].coalgebraic_complement()\n M[{1, 3}, {2}]\n sage: M[[1,2],[3]].coalgebraic_complement()\n M[{2, 3}, {1}]\n sage: M[[1], [4], [2,3]].coalgebraic_complement()\n M[{4}, {1}, {2, 3}]\n sage: M[[1,4],[2,5],[3,6]].coalgebraic_complement()\n M[{3, 6}, {2, 5}, {1, 4}]\n sage: (3*M[[1]] - 4*M[[]] + 5*M[[1],[2]]).coalgebraic_complement()\n -4*M[] + 3*M[{1}] + 5*M[{2}, {1}]\n sage: X = WQSym.X()\n sage: X[[1,3],[2]].coalgebraic_complement()\n X[{1, 3}, {2}]\n sage: C = WQSym.C()\n sage: C[[1,3],[2]].coalgebraic_complement()\n C[{1, 3}, {2}]\n sage: Q = WQSym.Q()\n sage: Q[[1,2],[5,6],[3,4]].coalgebraic_complement()\n Q[{1, 2, 5, 6}, {3, 4}] + Q[{5, 6}, {1, 2}, {3, 4}] - Q[{5, 6}, {1, 2, 3, 4}]\n sage: Phi = WQSym.Phi()\n sage: Phi[[2], [1,3]].coalgebraic_complement()\n -Phi[{2}, {1}, {3}] + Phi[{2}, {1, 3}] + Phi[{2}, {3}, {1}]\n\n The coalgebraic complement involution intertwines the antipode\n and the inverse of the antipode::\n\n sage: all( M(I).antipode().coalgebraic_complement().antipode() # long time\n ....: == M(I).coalgebraic_complement()\n ....: for I in OrderedSetPartitions(4) )\n True\n\n Testing the `\\pi(f^r) = \\pi(f)` relation above::\n\n sage: all( M[I].coalgebraic_complement().to_quasisymmetric_function()\n ....: == M[I].to_quasisymmetric_function()\n ....: for I in OrderedSetPartitions(4) )\n True\n\n .. TODO::\n\n Check further commutative squares.\n '
parent = self.parent()
M = parent.realization_of().M()
dct = {I.complement(): coeff for (I, coeff) in M(self)}
return parent(M._from_dict(dct, remove_zeros=False))
def star_involution(self):
'\n Return the image of the element ``self`` of `WQSym`\n under the star involution.\n\n The star involution is the composition of the\n algebraic complement involution\n (:meth:`algebraic_complement`) with the coalgebraic\n complement involution (:meth:`coalgebraic_complement`).\n The composition can be performed in either order, as the\n involutions commute.\n\n The star involution is a graded Hopf algebra\n anti-automorphism of `WQSym`.\n Let `f^{\\ast}` denote the image of an element\n `f \\in WQSym` under the star involution.\n Let `\\mathbf{M}`, `X`, `Q` and `\\Phi` stand for the\n monomial, characteristic, Q and Phi bases of `WQSym`.\n For any ordered set partition `A` of `[n]`, we let\n `A^{\\ast}` denote the complement\n (:meth:`~sage.combinat.set_partition_ordered.OrderedSetPartition.complement`)\n of the reversal\n (:meth:`~sage.combinat.set_partition_ordered.OrderedSetPartition.reversed`)\n of `A`. Then, for any ordered set partition `A` of `[n]`,\n we have\n\n .. MATH::\n\n (\\mathbf{M}_A)^{\\ast} = \\mathbf{M}_{A^{\\ast}}, \\qquad\n (X_A)^{\\ast} = X_{A^{\\ast}}, \\qquad\n (Q_A)^{\\ast} = Q_{A^{\\ast}}, \\qquad\n (\\Phi_A)^{\\ast} = \\Phi_{A^{\\ast}} .\n\n The star involution\n (:meth:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.star_involution`)\n on the ring of noncommutative symmetric functions is a\n restriction of the star involution on `WQSym`.\n\n If we denote the star involution\n (:meth:`~sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.star_involution`)\n of the quasisymmetric functions by `f \\mapsto f^{\\ast}`,\n and if we let `\\pi` be the canonical projection\n `WQSym \\to QSym`, then each `f \\in WQSym` satisfies\n `\\pi(f^{\\ast}) = (\\pi(f))^{\\ast}`.\n\n .. TODO::\n\n More commutative diagrams?\n FQSym and FSym need their own star_involution\n methods defined first.\n\n .. SEEALSO::\n\n :meth:`algebraic_complement`, :meth:`coalgebraic_complement`\n\n EXAMPLES:\n\n Keep in mind that the default input method for basis keys\n of `WQSym` is by entering an ordered set partition, not a\n packed word. Let us check the basis formulas for the\n star involution::\n\n sage: WQSym = algebras.WQSym(ZZ)\n sage: M = WQSym.M()\n sage: M[[1,3], [2,4,5]].star_involution()\n M[{1, 2, 4}, {3, 5}]\n sage: M[[1,3],[2]].star_involution()\n M[{2}, {1, 3}]\n sage: M[[1,4],[2,5],[3,6]].star_involution()\n M[{1, 4}, {2, 5}, {3, 6}]\n sage: (3*M[[1]] - 4*M[[]] + 5*M[[1],[2]]).star_involution()\n -4*M[] + 3*M[{1}] + 5*M[{1}, {2}]\n sage: X = WQSym.X()\n sage: X[[1,3],[2]].star_involution()\n X[{2}, {1, 3}]\n sage: C = WQSym.C()\n sage: C[[1,3],[2]].star_involution()\n -C[{1, 2, 3}] - C[{1, 3}, {2}] + C[{2}, {1, 3}]\n sage: Q = WQSym.Q()\n sage: Q[[1,3], [2,4,5]].star_involution()\n Q[{1, 2, 4}, {3, 5}]\n sage: Phi = WQSym.Phi()\n sage: Phi[[1,3], [2,4,5]].star_involution()\n Phi[{1, 2, 4}, {3, 5}]\n\n Testing the formulas for `(Q_A)^{\\ast}` and `(\\Phi_A)^{\\ast}`::\n\n sage: all(Q[A].star_involution() == Q[A.complement().reversed()] for A in OrderedSetPartitions(4))\n True\n sage: all(Phi[A].star_involution() == Phi[A.complement().reversed()] for A in OrderedSetPartitions(4))\n True\n\n The star involution commutes with the antipode::\n\n sage: all( M(I).antipode().star_involution() # long time\n ....: == M(I).star_involution().antipode()\n ....: for I in OrderedSetPartitions(4) )\n True\n\n Testing the `\\pi(f^{\\ast}) = (\\pi(f))^{\\ast}` relation::\n\n sage: all( M[I].star_involution().to_quasisymmetric_function()\n ....: == M[I].to_quasisymmetric_function().star_involution()\n ....: for I in OrderedSetPartitions(4) )\n True\n\n Testing the fact that the star involution on the\n noncommutative symmetric functions is a restriction of\n the star involution on `WQSym`::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: R = NCSF.R()\n sage: all(R[I].star_involution().to_fqsym().to_wqsym()\n ....: == R[I].to_fqsym().to_wqsym().star_involution()\n ....: for I in Compositions(4))\n True\n\n .. TODO::\n\n Check further commutative squares.\n '
parent = self.parent()
M = parent.realization_of().M()
dct = {I.reversed().complement(): coeff for (I, coeff) in M(self)}
return parent(M._from_dict(dct, remove_zeros=False))
def to_quasisymmetric_function(self):
'\n The projection of ``self`` to the ring `QSym` of\n quasisymmetric functions.\n\n There is a canonical projection `\\pi : WQSym \\to QSym`\n that sends every element `\\mathbf{M}_P` of the monomial\n basis of `WQSym` to the monomial quasisymmetric function\n `M_c`, where `c` is the composition whose parts are the\n sizes of the blocks of `P`.\n This `\\pi` is a ring homomorphism.\n\n OUTPUT:\n\n - an element of the quasisymmetric functions in the monomial basis\n\n EXAMPLES::\n\n sage: M = algebras.WQSym(QQ).M()\n sage: M[[1,3],[2]].to_quasisymmetric_function()\n M[2, 1]\n sage: (M[[1,3],[2]] + 3*M[[2,3],[1]] - M[[1,2,3],]).to_quasisymmetric_function()\n 4*M[2, 1] - M[3]\n sage: X, Y = M[[1,3],[2]], M[[1,2,3],]\n sage: X.to_quasisymmetric_function() * Y.to_quasisymmetric_function() == (X*Y).to_quasisymmetric_function()\n True\n\n sage: C = algebras.WQSym(QQ).C()\n sage: C[[2,3],[1,4]].to_quasisymmetric_function() == M(C[[2,3],[1,4]]).to_quasisymmetric_function()\n True\n\n sage: C2 = algebras.WQSym(GF(2)).C()\n sage: C2[[1,2],[3,4]].to_quasisymmetric_function()\n M[2, 2]\n sage: C2[[2,3],[1,4]].to_quasisymmetric_function()\n M[4]\n '
from sage.combinat.ncsf_qsym.qsym import QuasiSymmetricFunctions
M = QuasiSymmetricFunctions(self.parent().base_ring()).Monomial()
MW = self.parent().realization_of().M()
return M.sum_of_terms(((i.to_composition(), coeff) for (i, coeff) in MW(self)))
|
def cluster_interact(self, fig_size=1, circular=True, kind='seed'):
'\n Start an interactive window for cluster seed mutations.\n\n Only in *Jupyter notebook mode*.\n\n Not to be called directly. Use the :meth:`interact` methods\n of :class:`ClusterSeed` and :class:`ClusterQuiver` instead.\n\n INPUT:\n\n - ``fig_size`` -- (default: 1) factor by which the size of the\n plot is multiplied.\n\n - ``circular`` -- (default: ``True``) if ``True``, the circular plot\n is chosen, otherwise >>spring<< is used.\n\n - ``kind`` -- either ``"seed"`` (default) or ``"quiver"``\n\n TESTS::\n\n sage: S = ClusterSeed([\'A\',4]) # needs sage.graphs sage.modules\n sage: S.interact() # indirect doctest # needs sage.graphs sage.modules sage.symbolic\n ...VBox(children=...\n '
if (kind not in ['seed', 'quiver']):
raise ValueError('kind must be "seed" or "quiver"')
show_seq = widgets.Checkbox(value=True, description='Display mutation sequence')
show_vars = widgets.Checkbox(value=True, description='Display cluster variables')
show_matrix = widgets.Checkbox(value=True, description='Display B-matrix')
show_lastmutation = widgets.Checkbox(value=True, description='Show last mutation vertex')
mut_buttons = widgets.ToggleButtons(options=list(range(self._n)), style={'button_width': 'initial'}, description='Mutate at: ')
which_plot = widgets.Dropdown(options=['circular', 'spring'], value=('circular' if circular else 'spring'), description='Display style:')
out = widgets.Output()
seq = []
def print_data():
if show_seq.value:
pretty_print('Mutation sequence: ', seq)
if (show_vars.value and (kind == 'seed')):
pretty_print('Cluster variables:')
table = '\\begin{align*}\n'
for i in range(self._n):
table += ((('\tv_{%s} &= ' % i) + latex(self.cluster_variable(i))) + '\\\\ \\\\\n')
table += '\\end{align*}'
pretty_print(table)
if show_matrix.value:
pretty_print('B-Matrix: ', self._M)
def refresh(w):
k = mut_buttons.value
circular = bool((which_plot.value == 'circular'))
with out:
clear_output(wait=True)
if show_lastmutation.value:
self.show(fig_size=fig_size, circular=circular, mark=k)
else:
self.show(fig_size=fig_size, circular=circular)
print_data()
def do_mutation(*args, **kwds):
k = mut_buttons.value
circular = bool((which_plot.value == 'circular'))
self.mutate(k)
if (seq and (seq[(- 1)] == k)):
seq.pop()
else:
seq.append(k)
with out:
clear_output(wait=True)
if show_lastmutation.value:
self.show(fig_size=fig_size, circular=circular, mark=k)
else:
self.show(fig_size=fig_size, circular=circular)
print_data()
mut_buttons.on_msg(do_mutation)
show_seq.observe(refresh, 'value')
if (kind == 'seed'):
show_vars.observe(refresh, 'value')
show_matrix.observe(refresh, 'value')
show_lastmutation.observe(refresh, 'value')
which_plot.observe(refresh, 'value')
mut_buttons.on_widget_constructed(refresh)
if (kind == 'seed'):
top = widgets.HBox([show_seq, show_vars])
else:
top = widgets.HBox([show_seq])
return widgets.VBox([which_plot, top, widgets.HBox([show_matrix, show_lastmutation]), mut_buttons, out])
|
def _principal_part(mat):
'\n Return the principal part of a matrix.\n\n INPUT:\n\n - ``mat`` - a matrix with at least as many rows as columns\n\n OUTPUT:\n\n The top square part of the matrix ``mat``.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _principal_part\n sage: M = Matrix([[1,2],[3,4],[5,6]]); M # needs sage.modules\n [1 2]\n [3 4]\n [5 6]\n sage: _principal_part(M) # needs sage.modules\n [1 2]\n [3 4]\n '
(n, m) = (mat.ncols(), (mat.nrows() - mat.ncols()))
if (m < 0):
raise ValueError('the input matrix has more columns than rows')
elif (m == 0):
return mat
else:
return mat.submatrix(0, 0, n, n)
|
def _digraph_mutate(dg, k, frozen=None):
"\n Return a digraph obtained from ``dg`` by mutating at vertex ``k``.\n\n Vertices can be labelled by anything, and frozen vertices must\n be explicitly given.\n\n INPUT:\n\n - ``dg`` -- a digraph with integral edge labels with ``n+m`` vertices\n - ``k`` -- the vertex at which ``dg`` is mutated\n - ``frozen`` -- the list of frozen vertices (default is the empty list)\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _digraph_mutate\n sage: from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver\n sage: dg = ClusterQuiver(['A',4]).digraph() # needs sage.modules\n sage: dg.edges(sort=True) # needs sage.modules\n [(0, 1, (1, -1)), (2, 1, (1, -1)), (2, 3, (1, -1))]\n sage: _digraph_mutate(dg,2).edges(sort=True) # needs sage.modules\n [(0, 1, (1, -1)), (1, 2, (1, -1)), (3, 2, (1, -1))]\n\n TESTS::\n\n sage: dg = DiGraph([('a','b',(1,-1)),('c','a',(1,-1))])\n sage: _digraph_mutate(dg,'a').edges(sort=True)\n [('a', 'c', (1, -1)), ('b', 'a', (1, -1)), ('c', 'b', (1, -1))]\n sage: _digraph_mutate(dg,'a',frozen=['b','c']).edges(sort=True)\n [('a', 'c', (1, -1)), ('b', 'a', (1, -1))]\n\n sage: dg = DiGraph([('a','b',(2,-2)),('c','a',(2,-2)),('b','c',(2,-2))])\n sage: _digraph_mutate(dg,'a').edges(sort=True)\n [('a', 'c', (2, -2)), ('b', 'a', (2, -2)), ('c', 'b', (2, -2))]\n "
if (frozen is None):
frozen = []
edge_it = dg.incoming_edge_iterator(dg, True)
edges = {(v1, v2): label for (v1, v2, label) in edge_it}
edge_it = dg.incoming_edge_iterator([k], True)
in_edges = [(v1, v2, label) for (v1, v2, label) in edge_it]
edge_it = dg.outgoing_edge_iterator([k], True)
out_edges = [(v1, v2, label) for (v1, v2, label) in edge_it]
in_edges_new = [(v2, v1, ((- label[1]), (- label[0]))) for (v1, v2, label) in in_edges]
out_edges_new = [(v2, v1, ((- label[1]), (- label[0]))) for (v1, v2, label) in out_edges]
diag_edges_new = []
diag_edges_del = []
for (v1, v2, label1) in in_edges:
(l11, l12) = label1
for (w1, w2, label2) in out_edges:
if ((v1 in frozen) and (w2 in frozen)):
continue
(l21, l22) = label2
if ((v1, w2) in edges):
diag_edges_del.append((v1, w2))
(a, b) = edges[(v1, w2)]
(a, b) = ((a + (l11 * l21)), (b - (l12 * l22)))
diag_edges_new.append((v1, w2, (a, b)))
elif ((w2, v1) in edges):
diag_edges_del.append((w2, v1))
(a, b) = edges[(w2, v1)]
(a, b) = ((b + (l11 * l21)), (a - (l12 * l22)))
if (a < 0):
diag_edges_new.append((w2, v1, (b, a)))
elif (a > 0):
diag_edges_new.append((v1, w2, (a, b)))
else:
(a, b) = ((l11 * l21), ((- l12) * l22))
diag_edges_new.append((v1, w2, (a, b)))
del_edges = [tuple(ed[:2]) for ed in (in_edges + out_edges)]
del_edges += diag_edges_del
new_edges = (in_edges_new + out_edges_new)
new_edges += diag_edges_new
new_edges += [(v1, v2, edges[(v1, v2)]) for (v1, v2) in edges if ((v1, v2) not in del_edges)]
dg_new = DiGraph()
dg_new.add_vertices(list(dg))
for (v1, v2, label) in new_edges:
dg_new.add_edge(v1, v2, label)
return dg_new
|
def _matrix_to_digraph(M):
'\n Return the digraph obtained from the matrix ``M``.\n\n In order to generate a quiver, we assume that ``M`` is skew-symmetrizable.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _matrix_to_digraph\n sage: _matrix_to_digraph(matrix(3,[0,1,0,-1,0,-1,0,1,0])) # needs sage.modules\n Digraph on 3 vertices\n '
n = M.ncols()
dg = DiGraph(sparse=True)
for (i, j) in M.nonzero_positions():
if (i >= n):
(a, b) = (M[(i, j)], (- M[(i, j)]))
else:
(a, b) = (M[(i, j)], M[(j, i)])
if (a > 0):
dg._backend.add_edge(i, j, (a, b), True)
elif (i >= n):
dg._backend.add_edge(j, i, ((- a), (- b)), True)
for i in range(M.nrows()):
if (i not in dg):
dg.add_vertex(i)
return dg
|
def _dg_canonical_form(dg, frozen=None):
"\n Turn the digraph ``dg`` into its canonical form, and return the\n corresponding isomorphism and the vertex orbits of the automorphism group.\n\n The labels of ``dg`` are assumed to be integers between `0` and `n + m - 1`.\n\n The canonical form has the following additional property: the frozen\n vertices are the final labels.\n\n .. WARNING:: The input ``dg`` is modified.\n\n INPUT:\n\n - ``dg`` -- a directed graph having edge labels (a, b) with a > 0\n\n - ``frozen`` -- list (optional, default []) of frozen vertices\n\n OUTPUT:\n\n - dictionary {original label: canonical label}\n\n - list of orbits of mutable vertices (using canonical labels)\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _dg_canonical_form\n sage: dg = ClusterQuiver(['B',4]).digraph(); dg.edges(sort=True) # needs sage.modules\n [(0, 1, (1, -1)), (2, 1, (1, -1)), (2, 3, (1, -2))]\n sage: _dg_canonical_form(dg); dg.edges(sort=True) # needs sage.modules\n ({0: 0, 1: 3, 2: 1, 3: 2}, [[0], [3], [1], [2]])\n [(0, 3, (1, -1)), (1, 2, (1, -2)), (1, 3, (1, -1))]\n\n TESTS::\n\n sage: dg2 = ClusterQuiver(DiGraph({0:[1,2]})).digraph() # needs sage.modules\n sage: _dg_canonical_form(dg2); dg2.edges(sort=True) # needs sage.modules\n ({0: 0, 1: 1, 2: 2}, [[0], [1, 2]])\n [(0, 1, (1, -1)), (0, 2, (1, -1))]\n\n sage: dg2 = ClusterQuiver(DiGraph({0:[1,2]})).digraph() # needs sage.modules\n sage: _dg_canonical_form(dg2, frozen=[0]); dg2.edges(sort=True) # needs sage.modules\n ({0: 2, 1: 0, 2: 1}, [[2], [0, 1]])\n [(2, 0, (1, -1)), (2, 1, (1, -1))]\n\n sage: dg3 = ClusterQuiver(DiGraph({0:[1,2],1:[3]})).digraph() # needs sage.modules\n sage: _dg_canonical_form(dg3, frozen=[0,3]); dg3.edges(sort=True) # needs sage.modules\n ({0: 2, 1: 1, 2: 0, 3: 3}, [[2], [1], [0], [3]])\n [(1, 3, (1, -1)), (2, 0, (1, -1)), (2, 1, (1, -1))]\n\n sage: dg3 = ClusterQuiver(DiGraph({2:[1,3],1:[0],3:[4]})).digraph() # needs sage.modules\n sage: _dg_canonical_form(dg3, frozen=[4,0]); dg3.edges(sort=True) # needs sage.modules\n ({0: 4, 1: 1, 2: 0, 3: 2, 4: 3}, [[4, 3], [1, 2], [0]])\n [(0, 1, (1, -1)), (0, 2, (1, -1)), (1, 4, (1, -1)), (2, 3, (1, -1))]\n "
vertices = list(dg)
n_plus_m = dg.order()
if (frozen is not None):
partition = [[v for v in vertices if (v not in frozen)], frozen]
else:
frozen = []
partition = [vertices]
(partition_add, edges) = _graph_without_edge_labels(dg, vertices)
partition += partition_add
(automorphism_group, _, iso) = search_tree(dg, partition=partition, lab=True, dig=True, certificate=True)
orbits = get_orbits(automorphism_group, n_plus_m)
orbits = [[iso[i] for i in orbit] for orbit in orbits]
removed = []
for v in iso:
if (v not in vertices):
removed.append(v)
(v1, _, _) = next(dg._backend.iterator_in_edges([v], True))
(_, w2, _) = next(dg._backend.iterator_out_edges([v], True))
dg._backend.del_vertex(v)
add_index = True
index = 0
while add_index:
l = partition_add[index]
if (v in l):
dg._backend.add_edge(v1, w2, edges[index], True)
add_index = False
index += 1
for v in removed:
del iso[v]
dg._backend.relabel(iso, True)
return (iso, orbits)
|
def _mutation_class_iter(dg, n, m, depth=infinity, return_dig6=False, show_depth=False, up_to_equivalence=True, sink_source=False):
"\n Return an iterator for mutation class of dg with respect to several parameters.\n\n .. NOTE:: assuming that the frozen vertices start at vertex n.\n\n INPUT:\n\n - ``dg`` -- a digraph with n+m vertices\n - ``depth`` -- a positive integer or infinity specifying (roughly) how many steps away from the initial seed to mutate\n - ``return_dig6`` -- indicates whether to convert digraph data to dig6 string data\n - ``show_depth`` -- if True, indicates that a running count of the depth is to be displayed\n - ``up_to_equivalence`` -- if True, only one digraph for each graph-isomorphism class is recorded\n - ``sink_source`` -- if True, only mutations at sinks or sources are applied\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _mutation_class_iter\n sage: from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver\n sage: dg = ClusterQuiver(['A',[1,2],1]).digraph()\n sage: itt = _mutation_class_iter(dg, 3,0)\n sage: next(itt)[0].edges(sort=True)\n [(0, 1, (1, -1)), (0, 2, (1, -1)), (1, 2, (1, -1))]\n sage: next(itt)[0].edges(sort=True)\n [(0, 2, (1, -1)), (1, 0, (2, -2)), (2, 1, (1, -1))]\n "
mlist = list(range(n, (n + m)))
timer = time.time()
depth_counter = 0
if up_to_equivalence:
(iso, orbits) = _dg_canonical_form(dg, mlist)
iso_inv = dict(((iso[a], a) for a in iso))
dig6 = _digraph_to_dig6(dg, hashable=True)
dig6s = {}
if up_to_equivalence:
orbits = [orbit[0] for orbit in orbits]
dig6s[dig6] = [orbits, [], iso_inv]
else:
dig6s[dig6] = [list(range(n)), []]
if return_dig6:
(yield (dig6, []))
else:
(yield (dg, []))
gets_bigger = True
if show_depth:
timer2 = time.time()
dc = str(depth_counter)
dc += (' ' * (5 - len(dc)))
nr = str(len(dig6s))
nr += (' ' * (10 - len(nr)))
print(('Depth: %s found: %s Time: %.2f s' % (dc, nr, (timer2 - timer))))
while (gets_bigger and (depth_counter < depth)):
gets_bigger = False
for key in list(dig6s):
mutation_indices = [i for i in dig6s[key][0] if (i < n)]
if mutation_indices:
dg = _dig6_to_digraph(key)
while mutation_indices:
i = mutation_indices.pop()
if ((not sink_source) or _dg_is_sink_source(dg, i)):
dg_new = _digraph_mutate(dg, i, frozen=mlist)
if up_to_equivalence:
(iso, orbits) = _dg_canonical_form(dg_new, mlist)
i_new = iso[i]
iso_inv = dict(((iso[a], a) for a in iso))
else:
i_new = i
dig6_new = _digraph_to_dig6(dg_new, hashable=True)
if (dig6_new in dig6s):
if (i_new in dig6s[dig6_new][0]):
dig6s[dig6_new][0].remove(i_new)
else:
gets_bigger = True
if up_to_equivalence:
orbits = [orbit[0] for orbit in orbits if (i_new not in orbit)]
iso_history = dict(((a, dig6s[key][2][iso_inv[a]]) for a in iso))
i_history = iso_history[i_new]
history = (dig6s[key][1] + [i_history])
dig6s[dig6_new] = [orbits, history, iso_history]
else:
orbits = list(range(n))
del orbits[i_new]
history = (dig6s[key][1] + [i_new])
dig6s[dig6_new] = [orbits, history]
if return_dig6:
(yield (dig6_new, history))
else:
(yield (dg_new, history))
depth_counter += 1
if (show_depth and gets_bigger):
timer2 = time.time()
dc = str(depth_counter)
dc += (' ' * (5 - len(dc)))
nr = str(len(dig6s))
nr += (' ' * (10 - len(nr)))
print(('Depth: %s found: %s Time: %.2f s' % (dc, nr, (timer2 - timer))))
|
def _digraph_to_dig6(dg, hashable=False):
"\n Return the dig6 and edge data of the digraph dg.\n\n INPUT:\n\n - ``dg`` -- a digraph\n - ``hashable`` -- (Boolean; optional; default:False) if ``True``, the edge labels are turned into a dict.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _digraph_to_dig6\n sage: from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver\n sage: dg = ClusterQuiver(['A',4]).digraph() # needs sage.modules\n sage: _digraph_to_dig6(dg) # needs sage.modules\n ('COD?', {})\n "
dig6 = dg.dig6_string()
D = {}
for E in dg._backend.iterator_in_edges(dg, True):
if (E[2] != (1, (- 1))):
D[(E[0], E[1])] = E[2]
if hashable:
D = tuple(sorted(D.items()))
return (dig6, D)
|
def _dig6_to_digraph(dig6):
"\n Return the digraph obtained from the dig6 and edge data.\n\n INPUT:\n\n - ``dig6`` -- a pair ``(dig6, edges)`` where ``dig6`` is a string encoding a digraph and ``edges`` is a dict or tuple encoding edges\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _digraph_to_dig6\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _dig6_to_digraph\n sage: from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver\n sage: dg = ClusterQuiver(['A',4]).digraph()\n sage: data = _digraph_to_dig6(dg)\n sage: _dig6_to_digraph(data)\n Digraph on 4 vertices\n sage: _dig6_to_digraph(data).edges(sort=True)\n [(0, 1, (1, -1)), (2, 1, (1, -1)), (2, 3, (1, -1))]\n "
(dig6, edges) = dig6
dg = DiGraph(dig6)
if (not isinstance(edges, dict)):
edges = dict(edges)
for edge in dg._backend.iterator_in_edges(dg, False):
if (edge in edges):
dg.set_edge_label(edge[0], edge[1], edges[edge])
else:
dg.set_edge_label(edge[0], edge[1], (1, (- 1)))
return dg
|
def _dig6_to_matrix(dig6):
"\n Return the matrix obtained from the dig6 and edge data.\n\n INPUT:\n\n - ``dig6`` -- a pair ``(dig6, edges)`` where ``dig6`` is a string\n encoding a digraph and ``edges`` is a dict or tuple encoding edges\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _digraph_to_dig6, _dig6_to_matrix\n sage: from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver\n sage: dg = ClusterQuiver(['A',4]).digraph() # needs sage.modules\n sage: data = _digraph_to_dig6(dg) # needs sage.modules\n sage: _dig6_to_matrix(data) # needs sage.modules\n [ 0 1 0 0]\n [-1 0 -1 0]\n [ 0 1 0 1]\n [ 0 0 -1 0]\n "
dg = _dig6_to_digraph(dig6)
return _edge_list_to_matrix(dg.edges(sort=True), list(range(dg.order())), [])
|
def _dg_is_sink_source(dg, v):
"\n Return True iff the digraph dg has a sink or a source at vertex v.\n\n INPUT:\n\n - ``dg`` -- a digraph\n - ``v`` -- a vertex of dg\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _dg_is_sink_source\n sage: from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver\n sage: dg = ClusterQuiver(['A',[1,2],1]).digraph()\n sage: _dg_is_sink_source(dg, 0)\n True\n sage: _dg_is_sink_source(dg, 1)\n True\n sage: _dg_is_sink_source(dg, 2)\n False\n "
in_edges = [edge for edge in dg._backend.iterator_in_edges([v], True)]
out_edges = [edge for edge in dg._backend.iterator_out_edges([v], True)]
return (not (in_edges and out_edges))
|
def _graph_without_edge_labels(dg, vertices):
"\n Expand the graph, by introducing new vertices in the middle of edges.\n Return the corresponding partition of the new vertices.\n\n There is one new vertex for each edge with label not equal to ``(1,-1)``.\n These vertices are numbered starting from the smallest available integer.\n\n Each edge having a non-trivial label is replaced by two consecutive edges,\n passing through one new vertex.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _graph_without_edge_labels\n sage: from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver\n sage: dg = ClusterQuiver(['B',4]).digraph(); dg.edges(sort=True) # needs sage.modules\n [(0, 1, (1, -1)), (2, 1, (1, -1)), (2, 3, (1, -2))]\n sage: _graph_without_edge_labels(dg, range(4)); dg.edges(sort=True) # needs sage.modules\n ([[4]], ((1, -2),))\n [(0, 1, (1, -1)), (2, 1, (1, -1)), (2, 4, (1, -1)), (4, 3, (1, -1))]\n "
vertices = list(vertices)
edges = dg.edge_iterator(labels=True)
edge_labels = tuple(sorted(set((label for (_, _, label) in edges if (label != (1, (- 1)))))))
edge_partition = [[] for _ in edge_labels]
i = 0
while (i in vertices):
i += 1
for (u, v, label) in dg.edge_iterator(vertices=vertices, labels=True):
if (label != (1, (- 1))):
index = edge_labels.index(label)
edge_partition[index].append(i)
dg._backend.add_edge(u, i, (1, (- 1)), True)
dg._backend.add_edge(i, v, (1, (- 1)), True)
dg._backend.del_edge(u, v, label, True)
i += 1
while (i in vertices):
i += 1
return (edge_partition, edge_labels)
|
def _has_two_cycles(dg):
"\n Return True if the input digraph has a 2-cycle and False otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _has_two_cycles\n sage: _has_two_cycles(DiGraph([[0,1],[1,0]]))\n True\n sage: from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver\n sage: _has_two_cycles(ClusterQuiver(['A',3]).digraph()) # needs sage.modules\n False\n "
edge_set = dg.edges(sort=True, labels=False)
for (v, w) in edge_set:
if ((w, v) in edge_set):
return True
return False
|
def _is_valid_digraph_edge_set(edges, frozen=0):
"\n Return True if the input data is the edge set of a digraph for a quiver (no loops, no 2-cycles, edge-labels of the specified format), and returns False otherwise.\n\n INPUT:\n\n - ``frozen`` -- (integer; default:0) The number of frozen vertices.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _is_valid_digraph_edge_set\n sage: _is_valid_digraph_edge_set( [[0,1,'a'],[2,3,(1,-1)]] )\n The given digraph has edge labels which are not integral or integral 2-tuples.\n False\n sage: _is_valid_digraph_edge_set( [[0,1,None],[2,3,(1,-1)]] )\n True\n sage: _is_valid_digraph_edge_set( [[0,1,'a'],[2,3,(1,-1)],[3,2,(1,-1)]] )\n The given digraph or edge list contains oriented 2-cycles.\n False\n "
try:
dg = DiGraph()
dg.allow_multiple_edges(True)
dg.add_edges(edges)
if dg.has_loops():
print('The given digraph or edge list contains loops')
return False
if _has_two_cycles(dg):
print('The given digraph or edge list contains oriented 2-cycles.')
return False
if (not all((((i is None) or ((i in ZZ) and (i > 0)) or (isinstance(i, tuple) and (len(i) == 2) and (i[0] in ZZ) and (i[1] in ZZ))) for i in dg.edge_labels()))):
print('The given digraph has edge labels which are not integral or integral 2-tuples.')
return False
if dg.has_multiple_edges():
for e in set(dg.multiple_edges(labels=False)):
if (not all((((i is None) or ((i in ZZ) and (i > 0))) for i in dg.edge_label(e[0], e[1])))):
print('The given digraph or edge list contains multiple edges with non-integral labels.')
return False
n = (dg.order() - frozen)
if (n < 0):
print('The number of frozen variables is larger than the number of vertices.')
return False
if any(((e[0] >= n) for e in dg.edges(sort=True, labels=False))):
print('The given digraph or edge list contains edges within the frozen vertices.')
return False
return True
except Exception:
print('Could not even build a digraph from the input data.')
return False
|
def is_mutation_finite(M, nr_of_checks=None):
"\n Use a non-deterministic method by random mutations in various\n directions. Can result in a wrong answer.\n\n .. WARNING::\n\n This method modifies the input matrix ``M``!\n\n INPUT:\n\n - ``nr_of_checks`` -- (default: ``None``) number of mutations applied. Standard is 500*(number of vertices of self).\n\n ALGORITHM:\n\n A quiver is mutation infinite if and only if every edge label (a,-b) satisfy a*b > 4.\n Thus, we apply random mutations in random directions\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_type import is_mutation_finite\n\n sage: Q = ClusterQuiver(['A',10]) # needs sage.modules\n sage: M = Q.b_matrix() # needs sage.modules\n sage: is_mutation_finite(M) # needs sage.modules\n (True, None)\n\n sage: # needs sage.modules\n sage: Q = ClusterQuiver([(0,1),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(2,9)])\n sage: M = Q.b_matrix()\n sage: is_mutation_finite(M) # random\n (False, [9, 6, 9, 8, 9, 4, 0, 4, 5, 2, 1, 0, 1, 0, 7, 1, 9, 2, 5, 7, 8, 6, 3, 0, 2, 5, 4, 2, 6, 9, 2, 7, 3, 5, 3, 7, 9, 5, 9, 0, 2, 7, 9, 2, 4, 2, 1, 6, 9, 4, 3, 5, 0, 8, 2, 9, 5, 3, 7, 0, 1, 8, 3, 7, 2, 7, 3, 4, 8, 0, 4, 9, 5, 2, 8, 4, 8, 1, 7, 8, 9, 1, 5, 0, 8, 7, 4, 8, 9, 8, 0, 7, 4, 7, 1, 2, 8, 6, 1, 3, 9, 3, 9, 1, 3, 2, 4, 9, 5, 1, 2, 9, 4, 8, 5, 3, 4, 6, 8, 9, 2, 5, 9, 4, 6, 2, 1, 4, 9, 6, 0, 9, 8, 0, 4, 7, 9, 2, 1, 6])\n\n Check that :trac:`19495` is fixed::\n\n sage: dg = DiGraph(); dg.add_vertex(0); S = ClusterSeed(dg); S # needs sage.modules\n A seed for a cluster algebra of rank 1\n sage: S.is_mutation_finite() # needs sage.modules\n True\n "
import random
n = M.ncols()
if (n <= 2):
return (True, None)
if (nr_of_checks is None):
nr_of_checks = (1000 * n)
k = random.randint(0, (n - 1))
path = []
for i in range(nr_of_checks):
next_k = random.randint(0, (n - 2))
if (next_k >= k):
next_k += 1
k = next_k
M.mutate(k)
path.append(k)
for (i, j) in M.nonzero_positions():
if ((i < j) and ((M[(i, j)] * M[(j, i)]) < (- 4))):
return (False, path)
return (True, None)
|
def _triangles(dg):
"\n Return a list of all oriented triangles in the digraph ``dg``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _triangles\n sage: Q = ClusterQuiver(['A',3])\n sage: _triangles(Q.digraph())\n []\n sage: Q.mutate([0,1])\n sage: _triangles(Q.digraph())\n [([(2, 0), (0, 1), (1, 2)], True)]\n sage: Q2 = ClusterQuiver(['A',[1,2],1])\n sage: _triangles(Q2.digraph())\n [([(1, 2), (1, 0), (2, 0)], False)]\n sage: Q2.mutate(2)\n sage: _triangles(Q2.digraph())\n [([(1, 0), (0, 2), (2, 1)], True)]\n "
E = dg.edges(sort=True, labels=False)
V = list(dg)
trians = []
flat_trians = []
for e in E:
(v1, v2) = e
for v in V:
if (v not in e):
if ((v, v1) in E):
if ((v2, v) in E):
flat_trian = sorted([v, v1, v2])
if (flat_trian not in flat_trians):
flat_trians.append(flat_trian)
trians.append(([(v, v1), (v1, v2), (v2, v)], True))
elif ((v, v2) in E):
flat_trian = sorted([v, v1, v2])
if (flat_trian not in flat_trians):
flat_trians.append(flat_trian)
trians.append(([(v, v1), (v1, v2), (v, v2)], False))
if ((v1, v) in E):
if ((v2, v) in E):
flat_trian = sorted([v, v1, v2])
if (flat_trian not in flat_trians):
flat_trians.append(flat_trian)
trians.append(([(v1, v), (v1, v2), (v2, v)], False))
elif ((v, v2) in E):
flat_trian = sorted([v, v1, v2])
if (flat_trian not in flat_trians):
flat_trians.append(flat_trian)
trians.append(([(v1, v), (v1, v2), (v, v2)], False))
return trians
|
def _all_induced_cycles_iter(dg):
"\n Return an iterator for all induced oriented cycles of length\n greater than or equal to 4 in the digraph ``dg``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _all_induced_cycles_iter\n sage: Q = ClusterQuiver(['A',[6,0],1]); Q\n Quiver on 6 vertices of type ['D', 6]\n sage: next(_all_induced_cycles_iter(Q.digraph()))\n ([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)], True)\n sage: Q.mutate(0)\n sage: next(_all_induced_cycles_iter(Q.digraph()))\n ([(1, 2), (2, 3), (3, 4), (4, 5), (5, 1)], True)\n sage: Q2 = ClusterQuiver(['A',[2,3],1])\n sage: next(_all_induced_cycles_iter(Q2.digraph()))\n ([(1, 0), (1, 2), (3, 2), (3, 4), (4, 0)], False)\n "
dg_new = DiGraph(dg)
E = dg_new.edges(sort=True)
for (v1, v2, label) in E:
dg_new.add_edge((v2, v1, label))
induced_sets = []
cycle_iter = dg_new.all_cycles_iterator(simple=True)
for cycle in cycle_iter:
if (len(cycle) > 3):
cycle_set = set(cycle)
if (not any((cycle_set.issuperset(induced_set) for induced_set in induced_sets))):
induced_sets.append(cycle_set)
if (len(cycle) > 4):
sg = dg.subgraph(cycle)
is_oriented = True
V = list(sg)
while (is_oriented and V):
v = V.pop()
if (not (sg.in_degree(v) == 1)):
is_oriented = False
(yield (sg.edges(sort=True, labels=False), is_oriented))
|
def _false_return(s=False):
"\n Return 'unknown'.\n\n Written for potential debugging purposes.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _false_return\n sage: _false_return()\n 'unknown'\n "
return 'unknown'
|
def _reset_dg(dg, vertices, dict_in_out, del_vertices):
"\n Delete the specified vertices (del_vertices) from the DiGraph dg,\n and the lists vertices and dict_in_out.\n\n Note that vertices and dict_in_out are the vertices of dg and a\n dictionary of in- and out-degrees that depend on the digraph\n ``dg`` but they are passed through as arguments so the function\n can change their values.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _reset_dg\n sage: dg = ClusterQuiver(['A',[2,2],1]).digraph(); dg\n Digraph on 4 vertices\n sage: vertices = list(dg)\n sage: dict_in_out = {}\n sage: for v in vertices: dict_in_out[v] = (dg.in_degree(v), dg.out_degree(v), dg.degree(v))\n sage: _reset_dg(dg,vertices, dict_in_out, [1])\n sage: dg\n Digraph on 3 vertices\n sage: vertices\n [0, 2, 3]\n sage: dict_in_out\n {0: (1, 0, 1), 2: (1, 0, 1), 3: (0, 2, 2)}\n "
del_vertices = list(set(del_vertices))
for v in del_vertices:
if (v in dg):
dg.delete_vertex(v)
else:
print(v)
print(dg.edges(sort=True))
vertices.remove(v)
del dict_in_out[v]
for v in vertices:
dict_in_out[v] = (dg.in_degree(v), dg.out_degree(v), dg.degree(v))
|
def _check_special_BC_cases(dg, n, check_letter_list, check_twist_list, hope_letter_list, conn_vert_list=False):
"\n Test if dg (on at most `n` vertices) is a quiver of type `A` or\n `D` (as given in hope_letter_list) with conn_vert_list (if\n given) as connecting vertices.\n\n Since this is supposed to be run on a ``dg`` coming from a larger\n quiver where vertices have already been removed (outside of the\n connecting vertices), this program therefore recognizes the type\n of the larger quiver as an `n`-vertex quiver of letter on\n ``check_letter_list`` and twist on ``check_twist_list``. This\n method is utilized in _connected_mutation_type to test for types\n BC, BB, CC, BD, or CD.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _check_special_BC_cases\n sage: dg = DiGraph(1)\n sage: _check_special_BC_cases(dg, 3, ['BC'], [1], ['A'], [[0]])\n ['BC', 2, 1]\n sage: dg = DiGraph(2); dg.add_edge([0,1])\n sage: _check_special_BC_cases(dg, 4, ['BC'], [1], ['A'], [[0]])\n ['BC', 3, 1]\n sage: dg = DiGraph(2); dg.add_edge([0,1])\n sage: _check_special_BC_cases(dg, 4, ['BB'], [1], ['A'], [[0,1]])\n ['BB', 3, 1]\n sage: _check_special_BC_cases(dg, 4, ['C', 'CD'], [None, None], ['A', 'D'], [ [], [0] ])\n ['C', 4]\n sage: dg.add_edges([[1, 2], [1, 3]])\n sage: _check_special_BC_cases(dg, 4, ['C', 'CD'], [None, None], ['A', 'D'], [ [], [0] ])\n ['CD', 3, 1]\n "
if (not dg.is_connected()):
return 'unknown'
if conn_vert_list:
mut_type = _connected_mutation_type_AAtildeD(dg, ret_conn_vert=True)
if (not (mut_type == 'unknown')):
(mut_type, conn_verts) = mut_type
else:
mut_type = _connected_mutation_type_AAtildeD(dg, ret_conn_vert=False)
conn_verts = []
if (not (mut_type == 'unknown')):
for i in range(len(check_letter_list)):
check_letter = check_letter_list[i]
check_twist = check_twist_list[i]
hope_letter = hope_letter_list[i]
if conn_vert_list:
conn_vert = set(conn_vert_list[i])
else:
conn_vert = set()
if ((hope_letter == 'D') and (mut_type._letter == 'A') and (mut_type._rank == 3) and (not mut_type._twist)):
hope_letter = 'A'
if conn_vert_list:
conn_verts = list(set(dg).difference(conn_verts))
if ((mut_type._letter == hope_letter) and (not mut_type._twist) and conn_vert.issubset(conn_verts)):
if (len(check_letter) > 1):
check_twist = 1
if check_twist:
n -= 1
return QuiverMutationType([check_letter, n, check_twist])
return 'unknown'
|
def _connected_mutation_type(dg):
"\n Assuming that ``dg`` is a connected digraph, checks the mutation\n type of ``dg`` as a valued quiver.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _connected_mutation_type\n sage: from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver\n sage: dg = ClusterQuiver(['A',3]).digraph(); _connected_mutation_type( dg )\n ['A', 3]\n sage: dg = ClusterQuiver(['D',7]).digraph(); _connected_mutation_type( dg )\n ['D', 7]\n sage: dg = ClusterQuiver(['BC',4,1]).digraph(); _connected_mutation_type( dg )\n ['BC', 4, 1]\n "
dg = DiGraph(dg)
n = dg.order()
edges = dg.edges(sort=True)
vertices = list(dg)
exc_labels = []
exc_labels41 = []
double_edges = []
dg.allow_multiple_edges(True)
for edge in edges:
label = edge[2]
if (label not in [(1, (- 1)), (2, (- 2)), (1, (- 2)), (2, (- 1)), (4, (- 1)), (1, (- 4))]):
return _false_return(2)
elif (label == (2, (- 2))):
dg.set_edge_label(edge[0], edge[1], 1)
dg.add_edge(edge[0], edge[1], 1)
double_edges.append(edge)
if (len(double_edges) > 1):
return _false_return()
elif (label == (1, (- 1))):
dg.set_edge_label(edge[0], edge[1], 1)
elif (label in [(2, (- 1)), (1, (- 2))]):
exc_labels.append(edge)
elif (label in [(1, (- 4)), (4, (- 1))]):
exc_labels41.append(edge)
dict_in_out = {}
for v in vertices:
dict_in_out[v] = (dg.in_degree(v), dg.out_degree(v), dg.degree(v))
if (((len(exc_labels) + len(exc_labels41)) + len(double_edges)) > 4):
return _false_return()
if exc_labels41:
if ((len(exc_labels41) == 1) and (dict_in_out[exc_labels41[0][0]][2] == dict_in_out[exc_labels41[0][1]][2] == 1)):
return QuiverMutationType(['BC', 1, 1])
if ((len(exc_labels41) == 1) and (len(exc_labels) == 2)):
bool2 = ((exc_labels41[0][2] == (4, (- 1))) and (exc_labels[0][2] == exc_labels[1][2] == (1, (- 2))))
bool3 = ((exc_labels41[0][2] == (1, (- 4))) and (exc_labels[0][2] == exc_labels[1][2] == (2, (- 1))))
if (bool2 or bool3):
(v1, v2, label) = exc_labels41[0]
(label1, label2) = exc_labels
if ((label1[1] == label2[0]) and (label2[1] == v1) and (v2 == label1[0]) and (dict_in_out[v1][2] == dict_in_out[v2][2] == 2)):
_reset_dg(dg, vertices, dict_in_out, [v1, v2])
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'], [[label1[1]]])
elif ((label1[0] == label2[1]) and (label1[1] == v1) and (v2 == label2[0]) and (dict_in_out[v1][2] == dict_in_out[v2][2] == 2)):
_reset_dg(dg, vertices, dict_in_out, [v1, v2])
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'], [[label1[0]]])
else:
return _false_return()
else:
return _false_return()
else:
return _false_return()
if (len(exc_labels) == 4):
exc_labels12 = [labl for labl in exc_labels if (labl[2] == (1, (- 2)))]
exc_labels21 = [labl for labl in exc_labels if (labl[2] == (2, (- 1)))]
if ((len(exc_labels12) != 2) or (len(exc_labels21) != 2)):
return _false_return()
label121 = exc_labels12[0]
label122 = exc_labels12[1]
label211 = exc_labels21[0]
label212 = exc_labels21[1]
if ((label211[1] == label121[0]) and (label212[1] == label122[0])):
pass
elif ((label212[1] == label121[0]) and (label211[1] == label122[0])):
(label211, label212) = (label212, label211)
elif ((label121[1] == label211[0]) and (label122[1] == label212[0])):
pass
elif ((label122[1] == label211[0]) and (label121[1] == label212[0])):
(label211, label212) = (label212, label211)
elif ((label121[1] == label211[0]) and (label212[1] == label122[0])):
pass
elif ((label121[1] == label212[0]) and (label211[1] == label122[0])):
(label211, label212) = (label212, label211)
elif ((label122[1] == label211[0]) and (label212[1] == label121[0])):
(label121, label122) = (label122, label121)
elif ((label122[1] == label212[0]) and (label211[1] == label121[0])):
pass
else:
return _false_return()
bool1 = (dg.has_edge(label121[1], label211[0], 1) and (dict_in_out[label211[1]][0] == dict_in_out[label211[1]][1] == 1))
bool2 = (dg.has_edge(label122[1], label212[0], 1) and (dict_in_out[label212[1]][0] == dict_in_out[label212[1]][1] == 1))
bool12 = (not ((label121[1] == label122[1]) and (label211[0] == label212[0])))
bool3 = (dg.has_edge(label211[1], label121[0], 1) and (dict_in_out[label121[1]][0] == dict_in_out[label121[1]][1] == 1))
bool4 = (dg.has_edge(label212[1], label122[0], 1) and (dict_in_out[label122[1]][0] == dict_in_out[label122[1]][1] == 1))
bool34 = (not ((label211[1] == label212[1]) and (label121[0] == label122[0])))
bool5 = (dg.has_edge(label211[1], label121[0], 1) and (dict_in_out[label121[1]][0] == dict_in_out[label121[1]][1] == 1))
bool6 = (dg.has_edge(label122[1], label212[0], 1) and (dict_in_out[label212[1]][0] == dict_in_out[label212[1]][1] == 1))
bool56 = (not ((label211[1] == label122[1]) and (label121[0] == label212[0])))
bool7 = (dg.has_edge(label212[1], label122[0], 1) and (dict_in_out[label122[1]][0] == dict_in_out[label122[1]][1] == 1))
bool8 = (dg.has_edge(label121[1], label211[0], 1) and (dict_in_out[label211[1]][0] == dict_in_out[label211[1]][1] == 1))
bool78 = (not ((label212[1] == label121[1]) and (label122[0] == label211[0])))
nb1 = (len(set(dg.neighbors(label121[1])).intersection(dg.neighbors(label211[0]))) <= 1)
nb2 = (len(set(dg.neighbors(label122[1])).intersection(dg.neighbors(label212[0]))) <= 1)
nb3 = (len(set(dg.neighbors(label211[1])).intersection(dg.neighbors(label121[0]))) <= 1)
nb4 = (len(set(dg.neighbors(label212[1])).intersection(dg.neighbors(label122[0]))) <= 1)
if (bool1 and bool2 and bool12 and nb1 and nb2):
(v1, v2) = (label211[1], label212[1])
_reset_dg(dg, vertices, dict_in_out, [v1, v2])
return _check_special_BC_cases(dg, n, ['CC'], [1], ['A'])
if (bool3 and bool4 and bool34 and nb3 and nb4):
(v1, v2) = (label121[1], label122[1])
_reset_dg(dg, vertices, dict_in_out, [v1, v2])
return _check_special_BC_cases(dg, n, ['BB'], [1], ['A'])
elif (bool5 and bool6 and bool56 and nb2 and nb3):
(v1, v2) = (label121[1], label212[1])
_reset_dg(dg, vertices, dict_in_out, [v1, v2])
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'])
elif (bool7 and bool8 and bool78 and nb1 and nb4):
(v1, v2) = (label122[1], label211[1])
_reset_dg(dg, vertices, dict_in_out, [v1, v2])
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'])
else:
return _false_return()
elif (len(exc_labels) == 3):
exc_labels12 = [labl for labl in exc_labels if (labl[2] == (1, (- 2)))]
exc_labels21 = [labl for labl in exc_labels if (labl[2] == (2, (- 1)))]
if ((exc_labels12 == []) or (exc_labels21 == [])):
return _false_return()
if (len(exc_labels12) == 2):
(label1, label2) = exc_labels12
label3 = exc_labels21[0]
if ((dict_in_out[label2[0]][2] == 1) or (dict_in_out[label2[1]][2] == 1)):
(label1, label2) = (label2, label1)
if (dict_in_out[label1[0]][2] == 1):
if ((label2[1] == label3[0]) and (dict_in_out[label2[1]][2] == 2) and dg.has_edge(label3[1], label2[0], 1)):
(v1, v2) = (label3[1], label2[0])
_reset_dg(dg, vertices, dict_in_out, [label2[1]])
if (len(set(dg.neighbors_out(v2)).intersection(dg.neighbors_in(v1))) > 0):
return _false_return()
elif (len(set(dg.neighbors_out(v1)).intersection(dg.neighbors_in(v2))) > 0):
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'], [[v1, v2]])
else:
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'])
elif ((label3[1] == label2[0]) and (dict_in_out[label3[1]][2] == 2) and dg.has_edge(label2[1], label3[0], 1)):
(v1, v2) = (label2[1], label3[0])
_reset_dg(dg, vertices, dict_in_out, [label3[1]])
if (len(set(dg.neighbors_out(v2)).intersection(dg.neighbors_in(v1))) > 0):
return _false_return()
elif (len(set(dg.neighbors_out(v1)).intersection(dg.neighbors_in(v2))) > 0):
return _check_special_BC_cases(dg, n, ['CC'], [1], ['A'], [[v1, v2]])
else:
return _check_special_BC_cases(dg, n, ['CC'], [1], ['A'])
else:
return _false_return()
elif (dict_in_out[label1[1]][2] == 1):
if ((label3[1] == label2[0]) and (dict_in_out[label3[1]][2] == 2) and dg.has_edge(label2[1], label3[0], 1)):
(v1, v2) = (label2[1], label3[0])
_reset_dg(dg, vertices, dict_in_out, [label3[1]])
if (len(set(dg.neighbors_out(v2)).intersection(dg.neighbors_in(v1))) > 0):
return _false_return()
elif (len(set(dg.neighbors_out(v1)).intersection(dg.neighbors_in(v2))) > 0):
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'], [[v1, v2]])
else:
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'])
elif ((label2[1] == label3[0]) and (dict_in_out[label2[1]][2] == 2) and dg.has_edge(label3[1], label2[0], 1)):
(v1, v2) = (label3[1], label2[0])
_reset_dg(dg, vertices, dict_in_out, [label2[1]])
if (len(set(dg.neighbors_out(v2)).intersection(dg.neighbors_in(v1))) > 0):
return _false_return()
elif (len(set(dg.neighbors_out(v1)).intersection(dg.neighbors_in(v2))) > 0):
return _check_special_BC_cases(dg, n, ['BB'], [1], ['A'], [[v1, v2]])
else:
return _check_special_BC_cases(dg, n, ['BB'], [1], ['A'])
else:
return _false_return()
elif ((label1[1] == label2[1] == label3[0]) and (dict_in_out[label1[1]][2] == 3) and dg.has_edge(label3[1], label1[0], 1) and dg.has_edge(label3[1], label2[0], 1) and (dict_in_out[label2[0]][2] == dict_in_out[label1[0]][2] == 2)):
_reset_dg(dg, vertices, dict_in_out, [label1[1]])
return _check_special_BC_cases(dg, n, ['BD'], [1], ['D'])
elif ((label1[0] == label2[0] == label3[1]) and (dict_in_out[label1[0]][2] == 3) and dg.has_edge(label1[1], label3[0], 1) and dg.has_edge(label2[1], label3[0], 1) and (dict_in_out[label2[1]][2] == dict_in_out[label1[1]][2] == 2)):
_reset_dg(dg, vertices, dict_in_out, [label1[0]])
return _check_special_BC_cases(dg, n, ['CD'], [1], ['D'])
else:
return _false_return()
elif (len(exc_labels21) == 2):
(label1, label2) = exc_labels21
label3 = exc_labels12[0]
if ((dict_in_out[label2[0]][2] == 1) or (dict_in_out[label2[1]][2] == 1)):
(label1, label2) = (label2, label1)
if (dict_in_out[label1[1]][2] == 1):
if ((label2[1] == label3[0]) and (dict_in_out[label2[1]][2] == 2) and dg.has_edge(label3[1], label2[0], 1)):
(v1, v2) = (label3[1], label2[0])
_reset_dg(dg, vertices, dict_in_out, [label2[1]])
if (len(set(dg.neighbors_out(v2)).intersection(dg.neighbors_in(v1))) > 0):
return _false_return()
elif (len(set(dg.neighbors_out(v1)).intersection(dg.neighbors_in(v2))) > 0):
return _check_special_BC_cases(dg, n, ['CC'], [1], ['A'], [[v1, v2]])
else:
return _check_special_BC_cases(dg, n, ['CC'], [1], ['A'])
elif ((label3[1] == label2[0]) and (dict_in_out[label3[1]][2] == 2) and dg.has_edge(label2[1], label3[0], 1)):
(v1, v2) = (label2[1], label3[0])
_reset_dg(dg, vertices, dict_in_out, [label3[1]])
if (len(set(dg.neighbors_out(v2)).intersection(dg.neighbors_in(v1))) > 0):
return _false_return()
elif (len(set(dg.neighbors_out(v1)).intersection(dg.neighbors_in(v2))) > 0):
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'], [[v1, v2]])
else:
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'])
else:
return _false_return()
elif (dict_in_out[label1[0]][2] == 1):
if ((label3[1] == label2[0]) and (dict_in_out[label3[1]][2] == 2) and dg.has_edge(label2[1], label3[0], 1)):
(v1, v2) = (label2[1], label3[0])
_reset_dg(dg, vertices, dict_in_out, [label3[1]])
if (len(set(dg.neighbors_out(v2)).intersection(dg.neighbors_in(v1))) > 0):
return _false_return()
elif (len(set(dg.neighbors_out(v1)).intersection(dg.neighbors_in(v2))) > 0):
return _check_special_BC_cases(dg, n, ['BB'], [1], ['A'], [[v1, v2]])
else:
return _check_special_BC_cases(dg, n, ['BB'], [1], ['A'])
elif ((label2[1] == label3[0]) and (dict_in_out[label2[1]][2] == 2) and dg.has_edge(label3[1], label2[0], 1)):
(v1, v2) = (label3[1], label2[0])
_reset_dg(dg, vertices, dict_in_out, [label2[1]])
if (len(set(dg.neighbors_out(v2)).intersection(dg.neighbors_in(v1))) > 0):
return _false_return()
elif (len(set(dg.neighbors_out(v1)).intersection(dg.neighbors_in(v2))) > 0):
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'], [[v1, v2]])
else:
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'])
else:
return _false_return()
elif ((label1[0] == label2[0] == label3[1]) and (dict_in_out[label1[0]][2] == 3) and dg.has_edge(label1[1], label3[0], 1) and (dict_in_out[label1[1]][2] == 2) and dg.has_edge(label2[1], label3[0], 1) and (dict_in_out[label2[1]][2] == 2)):
_reset_dg(dg, vertices, dict_in_out, [label3[1]])
return _check_special_BC_cases(dg, n, ['BD'], [1], ['D'])
elif ((label1[1] == label2[1] == label3[0]) and (dict_in_out[label3[0]][2] == 3) and dg.has_edge(label3[1], label1[0], 1) and (dict_in_out[label1[0]][2] == 2) and dg.has_edge(label3[1], label2[0], 1) and (dict_in_out[label2[0]][2] == 2)):
_reset_dg(dg, vertices, dict_in_out, [label3[0]])
return _check_special_BC_cases(dg, n, ['CD'], [1], ['D'])
else:
return _false_return()
elif (len(exc_labels) == 2):
(label1, label2) = exc_labels
if (label1[1] == label2[0]):
pass
elif (label2[1] == label1[0]):
(label1, label2) = (label2, label1)
else:
if ((label2[2] == (1, (- 2))) and (label1[2] == (2, (- 1)))):
(label1, label2) = (label2, label1)
if ((label1[2] == (1, (- 2))) and (label2[2] == (2, (- 1)))):
if ((label1[1] == label2[1]) and (dict_in_out[label1[1]][2] == 2) and (dict_in_out[label1[0]][2] == 1) and (dict_in_out[label2[0]][2] == 1)):
return QuiverMutationType(['BC', 2, 1])
elif ((label1[0] == label2[0]) and (dict_in_out[label1[0]][2] == 2) and (dict_in_out[label1[1]][2] == 1) and (dict_in_out[label2[1]][2] == 1)):
return QuiverMutationType(['BC', 2, 1])
(v11, v12, label1) = label1
(v21, v22, label2) = label2
if (dict_in_out[v11][2] == 1):
in_out1 = 'out'
elif (dict_in_out[v12][2] == 1):
in_out1 = 'in'
else:
return _false_return()
if (dict_in_out[v21][2] == 1):
in_out2 = 'out'
elif (dict_in_out[v22][2] == 1):
in_out2 = 'in'
else:
return _false_return()
if (label1 == label2):
if (in_out1 == in_out2 == 'in'):
if (label1 == (1, (- 2))):
return _check_special_BC_cases(dg, n, ['BB'], [1], ['A'])
else:
return _check_special_BC_cases(dg, n, ['CC'], [1], ['A'])
elif (in_out1 == in_out2 == 'out'):
if (label1 == (1, (- 2))):
return _check_special_BC_cases(dg, n, ['CC'], [1], ['A'])
else:
return _check_special_BC_cases(dg, n, ['BB'], [1], ['A'])
else:
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'])
elif (in_out1 == in_out2):
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'])
elif (label1 == (1, (- 2))):
if (in_out1 == 'in'):
return _check_special_BC_cases(dg, n, ['BB'], [1], ['A'])
else:
return _check_special_BC_cases(dg, n, ['CC'], [1], ['A'])
elif (in_out1 == 'in'):
return _check_special_BC_cases(dg, n, ['CC'], [1], ['A'])
else:
return _check_special_BC_cases(dg, n, ['BB'], [1], ['A'])
(v1, v, label1) = label1
(v, v2, label2) = label2
if dg.has_multiple_edges():
if all(((edge == (v2, v1, 1)) for edge in dg.multiple_edges())):
if (dict_in_out[v2][2] == dict_in_out[v1][2] == 3):
_reset_dg(dg, vertices, dict_in_out, [v1, v2])
if ((label1 == (1, (- 2))) and (label2 == (2, (- 1)))):
return _check_special_BC_cases(dg, n, ['CC'], [1], ['A'], [[v]])
elif ((label1 == (2, (- 1))) and (label2 == (1, (- 2)))):
return _check_special_BC_cases(dg, n, ['BB'], [1], ['A'], [[v]])
else:
return _false_return()
elif (dict_in_out[v][0] == dict_in_out[v][1] == 1):
dg.remove_multiple_edges()
dg = DiGraph(dg)
_reset_dg(dg, vertices, dict_in_out, [v])
if ((dict_in_out[v1][0] == dict_in_out[v1][1] == dict_in_out[v2][0] == dict_in_out[v2][1] == 1) and (next(dg.neighbor_out_iterator(v1)) == next(dg.neighbor_in_iterator(v2)))):
if ((label1 == (2, (- 1))) and (label2 == (1, (- 2)))):
return _check_special_BC_cases(dg, n, ['CD'], [1], ['A'])
elif ((label1 == (1, (- 2))) and (label2 == (2, (- 1)))):
return _check_special_BC_cases(dg, n, ['BD'], [1], ['A'])
else:
return _false_return()
else:
return _false_return()
else:
return _false_return()
elif ((not (dict_in_out[v][0] == 1)) or (not (dict_in_out[v][1] == 1))):
return _false_return()
elif dg.has_edge(v2, v1, 1):
nr_same_neighbors = len(set(dg.neighbors_out(v1)).intersection(dg.neighbors_in(v2)))
nr_other_neighbors = len(set(dg.neighbors_out(v2)).intersection(dg.neighbors_in(v1)))
nr_contained_cycles = len([cycle for (cycle, is_oriented) in _all_induced_cycles_iter(dg) if ((v1 in flatten(cycle)) and (v2 in flatten(cycle)))])
if (((nr_same_neighbors + nr_other_neighbors) + nr_contained_cycles) > 2):
return _false_return()
if ((label1 == (2, (- 1))) and (label2 == (1, (- 2)))):
if ((n == 4) and ((nr_same_neighbors == 2) or (nr_other_neighbors == 1))):
return QuiverMutationType(['CD', (n - 1), 1])
if ((nr_same_neighbors + nr_other_neighbors) > 1):
mt_tmp = _check_special_BC_cases(dg, n, ['C', 'CD'], [None, None], ['A', 'D'], [[], [v]])
else:
_reset_dg(dg, vertices, dict_in_out, [v])
mt_tmp = _check_special_BC_cases(dg, n, ['C', 'CD'], [None, None], ['A', 'D'])
if (mt_tmp == 'unknown'):
dg.delete_edges([[v2, v1], [v1, v], [v, v2]])
dg.add_edges([[v1, v2, 1], [v, v1, 1], [v2, v, 1]])
if ((nr_same_neighbors + nr_other_neighbors) > 1):
return _check_special_BC_cases(dg, n, ['CD'], [None], ['D'], [[v]])
else:
return _check_special_BC_cases(dg, n, ['CD'], [None], ['D'])
else:
return mt_tmp
elif ((label1 == (1, (- 2))) and (label2 == (2, (- 1)))):
if ((n == 4) and ((nr_same_neighbors == 2) or (nr_other_neighbors == 1))):
return QuiverMutationType(['BD', (n - 1), 1])
if ((nr_same_neighbors + nr_other_neighbors) > 1):
mt_tmp = _check_special_BC_cases(dg, n, ['B', 'BD'], [None, None], ['A', 'D'], [[], [v]])
else:
_reset_dg(dg, vertices, dict_in_out, [v])
mt_tmp = _check_special_BC_cases(dg, n, ['B', 'BD'], [None, None], ['A', 'D'])
if (mt_tmp == 'unknown'):
dg.delete_edges([[v2, v1], [v1, v], [v, v2]])
dg.add_edges([[v1, v2, 1], [v, v1, 1], [v2, v, 1]])
if ((nr_same_neighbors + nr_other_neighbors) > 1):
return _check_special_BC_cases(dg, n, ['BD'], [None], ['D'], [[v]])
else:
return _check_special_BC_cases(dg, n, ['BD'], [None], ['D'])
else:
return mt_tmp
else:
return _false_return()
elif ((dict_in_out[v1][2] == 1) and (dict_in_out[v2][2] == 1)):
if ((label1 == (1, (- 2))) and (label2 == (1, (- 2)))):
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'])
elif ((label1 == (2, (- 1))) and (label2 == (2, (- 1)))):
return _check_special_BC_cases(dg, n, ['BC'], [1], ['A'])
elif ((label1 == (1, (- 2))) and (label2 == (2, (- 1)))):
return _check_special_BC_cases(dg, n, ['CC'], [1], ['A'])
elif ((label1 == (2, (- 1))) and (label2 == (1, (- 2)))):
return _check_special_BC_cases(dg, n, ['BB'], [1], ['A'])
else:
return _false_return()
elif ((dict_in_out[v][0] == dict_in_out[v][1] == 1) and (dict_in_out[v1][0] == dict_in_out[v1][1] == 1) and (dict_in_out[v2][0] == dict_in_out[v2][1] == 1)):
_reset_dg(dg, vertices, dict_in_out, [v])
if ((n == 4) and ((label1, label2) == ((2, (- 1)), (1, (- 2))))):
return _check_special_BC_cases(dg, n, ['CD'], [1], ['A'])
elif ((n > 4) and ((label1, label2) == ((2, (- 1)), (1, (- 2))))):
return _check_special_BC_cases(dg, n, ['CD'], [1], ['D'])
elif ((n == 4) and ((label1, label2) == ((1, (- 2)), (2, (- 1))))):
return _check_special_BC_cases(dg, n, ['BD'], [1], ['A'])
elif ((n > 4) and ((label1, label2) == ((1, (- 2)), (2, (- 1))))):
return _check_special_BC_cases(dg, n, ['BD'], [1], ['D'])
else:
return _false_return()
else:
return _false_return()
elif (len(exc_labels) == 1):
label = exc_labels[0]
v_out = label[0]
v_in = label[1]
label = label[2]
if (label == (1, (- 2))):
if ((dict_in_out[v_in][0] == 1) and (dict_in_out[v_in][1] == 0)):
return _check_special_BC_cases(dg, n, ['B', 'BD'], [None, 1], ['A', 'D'], [[v_in], [v_in]])
elif ((dict_in_out[v_out][0] == 0) and (dict_in_out[v_out][1] == 1)):
return _check_special_BC_cases(dg, n, ['C', 'CD'], [None, 1], ['A', 'D'], [[v_out], [v_out]])
else:
return _false_return()
elif (label == (2, (- 1))):
if ((dict_in_out[v_out][0] == 0) and (dict_in_out[v_out][1] == 1)):
return _check_special_BC_cases(dg, n, ['B', 'BD'], [None, 1], ['A', 'D'], [[v_out], [v_out]])
elif ((dict_in_out[v_in][0] == 1) and (dict_in_out[v_in][1] == 0)):
return _check_special_BC_cases(dg, n, ['C', 'CD'], [None, 1], ['A', 'D'], [[v_in], [v_in]])
else:
return _false_return()
return _connected_mutation_type_AAtildeD(dg)
|
def _connected_mutation_type_AAtildeD(dg, ret_conn_vert=False):
"\n Return mutation type of ClusterQuiver(dg) for DiGraph dg if it is\n of type finite A, affine A, or finite D.\n\n For all other types (including affine D), outputs 'unknown'\n\n See [BPRS2009]_ and [Vat2008]_ (by Vatne) for theoretical details.\n\n .. TODO::\n\n Improve this algorithm to also recognize affine D.\n\n INPUT:\n\n - ``ret_conn_vert`` -- boolean (default: ``False``). If ``True``,\n returns 'connecting vertices', technical information that is\n used in the algorithm.\n\n A brief description of the algorithm::\n\n Looks for a long_cycle (of length >= 4) in the digraph dg. If there is more than one than the mutation_type is 'unknown'.\n Otherwise, checks if each edge of long_cycle connects to a type A quiver. If so, then ClusterQuiver(dg) is of type D or affine A.\n\n If there is no long_cycle, then checks that there are no multiple edges, all triangles are oriented,\n no vertices of valence higher than 4, that vertices of valence 4 are incident to two oriented triangles,\n and that a vertex of valence 3 has exactly two incident arrows as part of an oriented triangle.\n All these checks ensures that ClusterQuiver(dg) is of type A except for three exceptions that are also checked.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _connected_mutation_type_AAtildeD\n sage: Q = ClusterQuiver(['A',[7,0],1]); Q.mutate([0,1,4])\n sage: _connected_mutation_type_AAtildeD(Q.digraph(),ret_conn_vert=True)\n [['D', 7], [0, 4]]\n sage: Q2 = ClusterQuiver(['A',[5,2],1]); Q2.mutate([4,5])\n sage: _connected_mutation_type_AAtildeD(Q2.digraph() )\n ['A', [2, 5], 1]\n sage: Q3 = ClusterQuiver(['E',6]); Q3.mutate([5,2,1])\n sage: _connected_mutation_type_AAtildeD(Q3.digraph(),ret_conn_vert=True)\n 'unknown'\n "
vertices = list(dg)
n = dg.order()
if (n > 3):
for v in vertices:
dead_neighbors = [v_n for v_n in dg.neighbors(v) if (dg.degree(v_n) == 1)]
if (len(dead_neighbors) >= 2):
dg_tmp = DiGraph(dg)
dg_tmp.delete_vertices(dead_neighbors[:2])
type_tmp = _connected_mutation_type_AAtildeD(dg_tmp, ret_conn_vert=True)
if (type_tmp == 'unknown'):
return _false_return()
if ((type_tmp[0].letter() == 'A') and type_tmp[0].is_finite()):
if (v in type_tmp[1]):
type_tmp[1].remove(v)
if (n == 4):
type_tmp[1].extend(dead_neighbors[:2])
if ret_conn_vert:
return [QuiverMutationType(['D', n]), type_tmp[1]]
else:
return QuiverMutationType(['D', n])
else:
return _false_return(3)
exception_graph1 = DiGraph()
exception_graph1.add_edges([(0, 1), (1, 2), (2, 3), (3, 0)])
exception_graph2 = DiGraph()
exception_graph2.add_edges([(0, 1), (1, 2), (0, 3), (3, 2), (2, 0)])
for c1 in Combinations([vertex for vertex in vertices if (dg.degree(vertex) == 2)], 2):
del_vertices = list(vertices)
del_vertices.remove(c1[0])
del_vertices.remove(c1[1])
for c2 in Combinations(del_vertices, 2):
comb = (c1 + c2)
sg = dg.subgraph(comb)
edges = sg.edges(sort=True, labels=False)
if (((c1[0], c1[1]) not in edges) and ((c1[1], c1[0]) not in edges) and sg.is_isomorphic(exception_graph1)):
dg_tmp = DiGraph(dg)
dg_tmp.delete_vertices(c1)
components = dg_tmp.connected_components(sort=False)
if (len(components) != 2):
return _false_return(4)
else:
dg_tmp1 = dg_tmp.subgraph(components[0])
type_tmp1 = _connected_mutation_type_AAtildeD(dg_tmp1, ret_conn_vert=True)
dg_tmp2 = dg_tmp.subgraph(components[1])
type_tmp2 = _connected_mutation_type_AAtildeD(dg_tmp2, ret_conn_vert=True)
if ((type_tmp1 == 'unknown') or (type_tmp2 == 'unknown')):
return _false_return()
type_tmp = []
type_tmp.append([type_tmp1[0], type_tmp2[0]])
type_tmp[0].sort(key=str)
type_tmp.append((type_tmp1[1] + type_tmp2[1]))
type_tmp[1].sort(key=str)
if (not set(c2).issubset(type_tmp[1])):
return _false_return(5)
if ((type_tmp[0][0].letter() == 'A') and type_tmp[0][0].is_finite() and (type_tmp[0][1].letter() == 'A') and type_tmp[0][1].is_finite()):
if ret_conn_vert:
type_tmp[1].extend(c1)
return [QuiverMutationType(['D', n]), type_tmp[1]]
else:
return QuiverMutationType(['D', n])
if sg.is_isomorphic(exception_graph2):
dg_tmp = DiGraph(dg)
dg_tmp.delete_vertices(c1)
if (tuple(c2) in dg_tmp.edges(sort=True, labels=False)):
dg_tmp.delete_edge(tuple(c2))
else:
c2.reverse()
dg_tmp.delete_edge(tuple(c2))
components = dg_tmp.connected_components(sort=False)
if (len(components) != 2):
return _false_return(7)
else:
dg_tmp1 = dg_tmp.subgraph(components[0])
type_tmp1 = _connected_mutation_type_AAtildeD(dg_tmp1, ret_conn_vert=True)
if (type_tmp1 == 'unknown'):
return _false_return()
dg_tmp2 = dg_tmp.subgraph(components[1])
type_tmp2 = _connected_mutation_type_AAtildeD(dg_tmp2, ret_conn_vert=True)
type_tmp = []
type_tmp.append([type_tmp1[0], type_tmp2[0]])
type_tmp[0].sort(key=str)
type_tmp.append((type_tmp1[1] + type_tmp2[1]))
type_tmp[1].sort(key=str)
if (type_tmp2 == 'unknown'):
return _false_return()
if ((not set(c2).issubset(type_tmp[1])) and (len(set(type_tmp[1]).intersection(c2)) == 1)):
return _false_return(5.5)
if ((type_tmp[0][0].letter() == 'A') and type_tmp[0][0].is_finite() and (type_tmp[0][1].letter() == 'A') and type_tmp[0][1].is_finite()):
if ret_conn_vert:
type_tmp[1].remove(c2[0])
type_tmp[1].remove(c2[1])
return [QuiverMutationType(['D', n]), type_tmp[1]]
else:
return QuiverMutationType(['D', n])
long_cycle = False
if dg.has_multiple_edges():
multiple_edges = dg.multiple_edges(labels=False)
if (len(multiple_edges) > 2):
return _false_return(14)
elif (len(multiple_edges) == 2):
long_cycle = [multiple_edges, ['A', (n - 1), 1]]
dict_in_out = {}
for v in vertices:
dict_in_out[v] = (dg.in_degree(v), dg.out_degree(v), dg.degree(v))
abs_deg = max([x[2] for x in list(dict_in_out.values())])
if (abs_deg > 4):
return _false_return(16)
else:
trians = _triangles(dg)
oriented_trians = [trian[0] for trian in trians if trian[1]]
unoriented_trians = [trian[0] for trian in trians if (not trian[1])]
oriented_trian_edges = []
for oriented_trian in oriented_trians:
oriented_trian_edges.extend(oriented_trian)
multiple_trian_edges = []
for edge in oriented_trian_edges:
count = oriented_trian_edges.count(edge)
if (count > 2):
return _false_return(17)
elif (count == 2):
multiple_trian_edges.append(edge)
multiple_trian_edges = list(set(multiple_trian_edges))
count = len(multiple_trian_edges)
if (count >= 4):
return _false_return(321)
elif (count > 1):
test_triangles = []
for edge in multiple_trian_edges:
test_triangles.append([tuple(trian) for trian in oriented_trians if (edge in trian)])
unique_triangle = set(test_triangles[0]).intersection(*test_triangles[1:])
if (len(unique_triangle) != 1):
return _false_return(19)
elif long_cycle:
return _false_return(20)
else:
unique_triangle = unique_triangle.pop()
long_cycle = [unique_triangle, QuiverMutationType(['D', n])]
elif ((count == 1) and (not dg.has_multiple_edges()) and (not (multiple_trian_edges[0] in dg.multiple_edges()))):
multiple_trian_edge = multiple_trian_edges[0]
neighbors = list(set(dg.neighbors(multiple_trian_edge[0])).intersection(dg.neighbors(multiple_trian_edge[1])))
if (dg.degree(neighbors[0]) == 2):
unique_triangle = [multiple_trian_edge, (multiple_trian_edge[1], neighbors[0]), (neighbors[0], multiple_trian_edge[0])]
elif (dg.degree(neighbors[1]) == 2):
unique_triangle = [multiple_trian_edge, (multiple_trian_edge[1], neighbors[1]), (neighbors[1], multiple_trian_edge[0])]
else:
return _false_return(201)
if long_cycle:
return _false_return(202)
else:
long_cycle = [unique_triangle, QuiverMutationType(['D', n])]
if unoriented_trians:
if (len(unoriented_trians) == 1):
if long_cycle:
return _false_return(21)
else:
long_cycle = [unoriented_trians[0], ['A', (n - 1), 1]]
else:
return _false_return(22)
for v in vertices:
w = dict_in_out[v]
if (w[2] == 4):
if (w[0] != 2):
return _false_return(23)
else:
in_neighbors = dg.neighbors_in(v)
out_neighbors = dg.neighbors_out(v)
if (len(out_neighbors) == 1):
out_neighbors.extend(out_neighbors)
if (len(in_neighbors) == 1):
in_neighbors.extend(in_neighbors)
if ((in_neighbors[0], v) not in oriented_trian_edges):
return _false_return(24)
elif ((in_neighbors[1], v) not in oriented_trian_edges):
return _false_return(25)
elif ((v, out_neighbors[0]) not in oriented_trian_edges):
return _false_return(26)
elif ((v, out_neighbors[1]) not in oriented_trian_edges):
return _false_return(27)
elif (w[2] == 3):
if (w[0] == 1):
in_neighbors = dg.neighbors_in(v)
out_neighbors = dg.neighbors_out(v)
if ((in_neighbors[0], v) not in oriented_trian_edges):
return _false_return(28)
elif (len(out_neighbors) == 1):
if ((v, out_neighbors[0]) not in oriented_trian_edges):
return _false_return(29)
else:
if (((v, out_neighbors[0]) in oriented_trian_edges) and ((v, out_neighbors[1]) in oriented_trian_edges)):
if (not long_cycle):
return _false_return(30)
if (not (long_cycle[1] == QuiverMutationType(['D', n]))):
return _false_return(31)
if (((v, out_neighbors[0]) not in long_cycle[0]) and ((v, out_neighbors[1]) not in long_cycle[0])):
return _false_return(32)
if (((v, out_neighbors[0]) not in oriented_trian_edges) and ((v, out_neighbors[1]) not in oriented_trian_edges)):
return _false_return(33)
elif (w[0] == 2):
in_neighbors = dg.neighbors_in(v)
out_neighbors = dg.neighbors_out(v)
if ((v, out_neighbors[0]) not in oriented_trian_edges):
return _false_return(34)
elif (len(in_neighbors) == 1):
if ((in_neighbors[0], v) not in oriented_trian_edges):
return _false_return(35)
else:
if (((in_neighbors[0], v) in oriented_trian_edges) and ((in_neighbors[1], v) in oriented_trian_edges)):
if (not long_cycle):
return _false_return(36)
if (not (long_cycle[1] == QuiverMutationType(['D', n]))):
return _false_return(37)
if (((in_neighbors[0], v) not in long_cycle[0]) and ((in_neighbors[1], v) not in long_cycle[0])):
return _false_return(38)
if (((in_neighbors[0], v) not in oriented_trian_edges) and ((in_neighbors[1], v) not in oriented_trian_edges)):
return _false_return(39)
else:
return _false_return(40)
for (cycle, is_oriented) in _all_induced_cycles_iter(dg):
if long_cycle:
return _false_return(41)
elif is_oriented:
long_cycle = [cycle, QuiverMutationType(['D', n])]
else:
long_cycle = [cycle, ['A', (n - 1), 1]]
if (not long_cycle):
long_cycle = [[], QuiverMutationType(['A', n])]
if ret_conn_vert:
connecting_vertices = []
o_trian_verts = flatten(oriented_trian_edges)
long_cycle_verts = flatten(long_cycle[0])
for v in vertices:
w = dict_in_out[v]
if (w[2] == 0):
connecting_vertices.append(v)
elif (w[2] == 1):
connecting_vertices.append(v)
elif ((w[0] == 1) and (w[1] == 1)):
if ((v in o_trian_verts) and (v not in long_cycle_verts)):
connecting_vertices.append(v)
if (isinstance(long_cycle[1], list) and (len(long_cycle[1]) == 3) and (long_cycle[1][0] == 'A') and (long_cycle[1][2] == 1)):
tmp = list(long_cycle[0])
e = tmp.pop()
cycle = [e]
v = e[1]
while tmp:
e = next((x for x in tmp if (v in x)))
if (v == e[0]):
cycle.append(e)
v = e[1]
else:
v = e[0]
tmp.remove(e)
tmp = list(cycle)
if (len(long_cycle[0]) == 2):
edge = long_cycle[0][0]
sg = DiGraph(dg)
sg.delete_vertices(edge)
connected_components = sg.connected_components(sort=False)
cycle = []
if connected_components:
cycle.append((edge[0], edge[1], (len(connected_components[0]) + 1)))
else:
cycle.append((edge[0], edge[1], 1))
else:
for edge in tmp:
sg = DiGraph(dg)
sg.delete_vertices(edge)
connected_components = sg.connected_components(sort=False)
if (len(connected_components) == 2):
if (len(set(connected_components[0]).intersection(set(long_cycle[0]).difference([edge]).pop())) > 0):
cycle.remove(edge)
cycle.append((edge[0], edge[1], (len(connected_components[1]) + 1)))
else:
cycle.remove(edge)
cycle.append((edge[0], edge[1], (len(connected_components[0]) + 1)))
else:
cycle.remove(edge)
cycle.append((edge[0], edge[1], 1))
r = sum((x[2] for x in cycle))
r = max(r, (n - r))
if ret_conn_vert:
return [QuiverMutationType(['A', [r, (n - r)], 1]), connecting_vertices]
else:
return QuiverMutationType(['A', [r, (n - r)], 1])
elif ret_conn_vert:
return [long_cycle[1], connecting_vertices]
else:
return long_cycle[1]
|
@cached_function
def load_data(n, user=True):
"\n Load a dict with keys being tuples representing exceptional\n QuiverMutationTypes, and with values being lists or sets\n containing all mutation equivalent quivers as dig6 data.\n\n We check\n\n - the data stored by the user (unless ``user=False`` was given)\n - and the data installed by the optional package ``database_mutation_class``.\n\n INPUT:\n\n - ``user`` -- boolean (default: ``True``) whether to look at user\n data. If not, only consider the optional package.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_type import load_data\n sage: load_data(2) # random - depends on the data the user has stored\n {('G', 2): [('AO', (((0, 1), (1, -3)),)), ('AO', (((0, 1), (3, -1)),))]}\n\n TESTS:\n\n We test data from the ``database_mutation_class`` optional package::\n\n sage: load_data(2, user=False) # optional - database_mutation_class\n {('G', 2): [('AO', (((0, 1), (1, -3)),)), ('AO', (((0, 1), (3, -1)),))]}\n sage: D = load_data(3, user=False) # optional - database_mutation_class\n sage: sorted(D.items()) # optional - database_mutation_class\n [(('G', 2, -1),\n [('BH?', (((1, 2), (1, -3)),)),\n ('BGO', (((2, 1), (3, -1)),)),\n ('BW?', (((0, 1), (3, -1)),)),\n ('BP?', (((0, 1), (1, -3)),)),\n ('BP_', (((0, 1), (1, -3)), ((2, 0), (3, -1)))),\n ('BP_', (((0, 1), (3, -1)), ((1, 2), (1, -3)), ((2, 0), (2, -2))))]),\n (('G', 2, 1),\n [('BH?', (((1, 2), (3, -1)),)),\n ('BGO', (((2, 1), (1, -3)),)),\n ('BW?', (((0, 1), (1, -3)),)),\n ('BP?', (((0, 1), (3, -1)),)),\n ('BKO', (((1, 0), (3, -1)), ((2, 1), (1, -3)))),\n ('BP_', (((0, 1), (2, -2)), ((1, 2), (1, -3)), ((2, 0), (3, -1))))])]\n "
from sage.env import DOT_SAGE, SAGE_SHARE
paths = [Path(SAGE_SHARE)]
if user:
paths.append(Path(DOT_SAGE))
data = {}
for path in paths:
file = ((path / 'cluster_algebra_quiver') / f'mutation_classes_{n}.dig6')
try:
with open(file, 'rb') as fobj:
data_new = pickle.load(fobj)
except (OSError, FileNotFoundError, pickle.UnpicklingError):
pass
else:
data.update(data_new)
return data
|
def _mutation_type_from_data(n, dig6, compute_if_necessary=True):
"\n Return the mutation type from the given dig6 data by looking into\n the precomputed mutation types\n\n Attention: it is assumed that dig6 is the dig6 data of the\n canonical form of the given quiver!\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _digraph_to_dig6\n sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _mutation_type_from_data\n sage: from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver\n sage: dg = ClusterQuiver(['F',4]).canonical_label().digraph()\n sage: dig6 = _digraph_to_dig6(dg,hashable=True); dig6\n ('CCo?', (((1, 3), (2, -1)),))\n sage: _mutation_type_from_data(4,dig6)\n ['F', 4]\n "
data = load_data(n)
if (compute_if_necessary and (data == {})):
from sage.combinat.cluster_algebra_quiver.quiver_mutation_type import save_quiver_data
save_quiver_data(n, up_to=False, types='Exceptional', verbose=False)
load_data.clear_cache()
data = load_data(n)
for mutation_type in data:
if (dig6 in data[mutation_type]):
return QuiverMutationType(mutation_type)
return 'unknown'
|
def _mutation_type_test(n):
"\n Tests all quivers (of the given types) of rank n to check that\n mutation_type() works.\n\n Affine type D does not return True since this test is not implemented.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _mutation_type_test\n\n sage: _mutation_type_test(2) # long time\n True ('A', (1, 1), 1)\n True ('A', 2)\n True ('B', 2)\n True ('BC', 1, 1)\n True ('G', 2)\n\n sage: _mutation_type_test(3) # long time\n True ('A', (2, 1), 1)\n True ('A', 3)\n True ('B', 3)\n True ('BB', 2, 1)\n True ('BC', 2, 1)\n True ('C', 3)\n True ('CC', 2, 1)\n True ('G', 2, -1)\n True ('G', 2, 1)\n\n sage: _mutation_type_test(4) # not tested\n True ('A', (2, 2), 1)\n True ('A', (3, 1), 1)\n True ('A', 4)\n True ('B', 4)\n True ('BB', 3, 1)\n True ('BC', 3, 1)\n True ('BD', 3, 1)\n True ('C', 4)\n True ('CC', 3, 1)\n True ('CD', 3, 1)\n True ('D', 4)\n True ('F', 4)\n True ('G', 2, (1, 1))\n True ('G', 2, (1, 3))\n True ('G', 2, (3, 3))\n\n sage: _mutation_type_test(5) # not tested\n True ('A', (3, 2), 1)\n True ('A', (4, 1), 1)\n True ('A', 5)\n True ('B', 5)\n True ('BB', 4, 1)\n True ('BC', 4, 1)\n True ('BD', 4, 1)\n True ('C', 5)\n True ('CC', 4, 1)\n True ('CD', 4, 1)\n False ('D', 4, 1)\n True ('D', 5)\n True ('F', 4, -1)\n True ('F', 4, 1)\n "
from sage.combinat.cluster_algebra_quiver.quiver_mutation_type import _construct_classical_mutation_classes
from sage.combinat.cluster_algebra_quiver.mutation_class import _dig6_to_digraph
from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver
data = _construct_classical_mutation_classes(n)
keys = data.keys()
for mutation_type in sorted(keys, key=str):
mt = QuiverMutationType(mutation_type)
print(all(((ClusterQuiver(_dig6_to_digraph(dig6)).mutation_type() == mt) for dig6 in data[mutation_type])), mutation_type)
from sage.combinat.cluster_algebra_quiver.quiver_mutation_type import _construct_exceptional_mutation_classes
data = _construct_exceptional_mutation_classes(n)
keys = data.keys()
for mutation_type in sorted(keys, key=str):
mt = QuiverMutationType(mutation_type)
print(all(((ClusterQuiver(_dig6_to_digraph(dig6)).mutation_type() == mt) for dig6 in data[mutation_type])), mutation_type)
|
def _random_tests(mt, k, mut_class=None, nr_mut=5):
"\n Provide random tests to find bugs in the mutation type methods.\n\n INPUT:\n\n - ``mt`` something that can be turned into a QuiverMutationType\n - ``k`` (integer) the number of tests performed for each quiver of rank ``n``\n - ``mut_class`` is given, this mutation class is used\n - ``nr_mut`` (integer, default:5) the number of mutations performed before\n testing\n\n The idea of this random test is to start with a mutation type\n and compute its mutation class (or have this class given). Now,\n every quiver in this mutation class is slightly changed in order\n to obtain a matrix of the same type or something very similar.\n Now, the new type is computed and checked if it stays stable for\n ``nr_mut``'s many mutations.\n\n TESTS::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _random_tests\n sage: _random_tests( ['A',3], 1) # needs sage.modules\n testing ['A', 3]\n "
from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver
from sage.combinat.cluster_algebra_quiver.mutation_class import _dig6_to_matrix, _matrix_to_digraph, _digraph_mutate, _edge_list_to_matrix
import random
if (mut_class is None):
mut_class = ClusterQuiver(mt).mutation_class(data_type='dig6')
print(('testing ' + str(mt)))
for dig6 in mut_class:
M_const = _dig6_to_matrix(dig6)
nz = [(i, j) for (i, j) in M_const.nonzero_positions() if (i > j)]
for i in range(k):
M = copy(M_const)
for (i, j) in nz:
(a, b) = (M[(i, j)], M[(j, i)])
skew_sym = False
while (not skew_sym):
ran = random.randint(1, 2)
if (ran == 1):
(M[(i, j)], M[(j, i)]) = ((- M[(j, i)]), (- M[(i, j)]))
elif (ran == 2):
ran2 = random.randint(1, 8)
if (ran2 == 1):
(c, d) = (1, (- 1))
elif (ran2 == 2):
(c, d) = (1, (- 2))
elif (ran2 == 3):
(c, d) = (2, (- 1))
elif (ran2 == 4):
(c, d) = (1, (- 3))
elif (ran2 == 5):
(c, d) = (3, (- 1))
elif (ran2 == 6):
(c, d) = (2, (- 2))
elif (ran2 == 7):
(c, d) = (1, (- 4))
elif (ran2 == 8):
(c, d) = (4, (- 1))
(M[(i, j)], M[(j, i)]) = (c, d)
if M.is_skew_symmetrizable(positive=True):
skew_sym = True
else:
(M[(i, j)], M[(j, i)]) = (a, b)
dg = _matrix_to_digraph(M)
mt = _connected_mutation_type(dg)
mut = (- 1)
for k in range(nr_mut):
mut_tmp = mut
while (mut == mut_tmp):
mut = random.randint(0, (dg.order() - 1))
dg_new = _digraph_mutate(dg, mut)
mt_new = _connected_mutation_type(dg_new)
if (mt != mt_new):
print('FOUND ERROR!')
print(_edge_list_to_matrix(dg.edges(sort=True), list(range(dg.order())), []))
print((((((('has mutation type ' + str(mt)) + ' while it has mutation type ') + str(mt_new)) + ' after mutating at ') + str(mut)) + ':'))
print(_edge_list_to_matrix(dg_new.edges(sort=True), list(range(dg.order())), []))
return (dg, dg_new)
else:
dg = dg_new
|
def _random_multi_tests(n, k, nr_mut=5):
"\n Provide multiple random tests to find bugs in the mutation type methods.\n\n INPUT:\n\n - ``n`` (integer) -- the rank of the mutation types to test\n - ``k`` (integer) -- the number of tests performed for each quiver of rank ``n``\n - ``nr_mut`` (integer, default:5) -- the number of mutations performed before testing\n\n TESTS::\n\n sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _random_multi_tests\n sage: _random_multi_tests(2,1) # not tested\n testing ('A', (1, 1), 1)\n testing ('A', 2)\n testing ('B', 2)\n testing ('BC', 1, 1)\n\n sage: _random_multi_tests(3,1) # not tested\n testing ('A', (2, 1), 1)\n testing ('A', 3)\n testing ('B', 3)\n testing ('BB', 2, 1)\n testing ('BC', 2, 1)\n testing ('C', 3)\n testing ('CC', 2, 1)\n\n sage: _random_multi_tests(4,1) # not tested\n testing ('A', (2, 2), 1)\n testing ('A', (3, 1), 1)\n testing ('A', 4)\n testing ('B', 4)\n testing ('BB', 3, 1)\n testing ('BC', 3, 1)\n testing ('BD', 3, 1)\n testing ('C', 4)\n testing ('CC', 3, 1)\n testing ('CD', 3, 1)\n testing ('D', 4)\n "
from sage.combinat.cluster_algebra_quiver.quiver_mutation_type import _construct_classical_mutation_classes
mutation_classes = _construct_classical_mutation_classes(n)
for mutation_type in sorted(mutation_classes, key=str):
_random_tests(mutation_type, k, mut_class=mutation_classes[mutation_type], nr_mut=nr_mut)
|
class ClusterQuiver(SageObject):
"\n The *quiver* associated to an *exchange matrix*.\n\n INPUT:\n\n - ``data`` -- can be any of the following::\n\n * :class:`QuiverMutationType`\n * :class:`str` -- a string representing a :class:`QuiverMutationType` or a common quiver type (see Examples)\n * :class:`ClusterQuiver`\n * :class:`Matrix` -- a skew-symmetrizable matrix\n * :class:`DiGraph` -- must be the input data for a quiver\n * List of edges -- must be the edge list of a digraph for a quiver\n\n - ``frozen`` -- (default: ``None``) sets the list of frozen variables\n if the input type is a :class:`DiGraph`, it is ignored otherwise\n\n - ``user_labels`` -- (default:``None``) sets the names of the labels for\n the vertices of the quiver if the input type is not a :class:`DiGraph`;\n otherwise it is ignored\n\n EXAMPLES:\n\n From a :class:`QuiverMutationType`::\n\n sage: Q = ClusterQuiver(['A',5]); Q\n Quiver on 5 vertices of type ['A', 5]\n\n sage: Q = ClusterQuiver(['B',2]); Q\n Quiver on 2 vertices of type ['B', 2]\n sage: Q2 = ClusterQuiver(['C',2]); Q2\n Quiver on 2 vertices of type ['B', 2]\n sage: MT = Q.mutation_type(); MT.standard_quiver() == Q\n True\n sage: MT = Q2.mutation_type(); MT.standard_quiver() == Q2\n False\n\n sage: Q = ClusterQuiver(['A',[2,5],1]); Q\n Quiver on 7 vertices of type ['A', [2, 5], 1]\n\n sage: Q = ClusterQuiver(['A', [5,0],1]); Q\n Quiver on 5 vertices of type ['D', 5]\n sage: Q.is_finite()\n True\n sage: Q.is_acyclic()\n False\n\n sage: Q = ClusterQuiver(['F', 4, [2,1]]); Q\n Quiver on 6 vertices of type ['F', 4, [1, 2]]\n sage: MT = Q.mutation_type(); MT.standard_quiver() == Q\n False\n sage: dg = Q.digraph(); Q.mutate([2,1,4,0,5,3])\n sage: dg2 = Q.digraph(); dg2.is_isomorphic(dg,edge_labels=True)\n False\n sage: dg2.is_isomorphic(MT.standard_quiver().digraph(),edge_labels=True)\n True\n\n sage: Q = ClusterQuiver(['G',2, (3,1)]); Q\n Quiver on 4 vertices of type ['G', 2, [1, 3]]\n sage: MT = Q.mutation_type(); MT.standard_quiver() == Q\n False\n\n sage: Q = ClusterQuiver(['GR',[3,6]]); Q\n Quiver on 4 vertices of type ['D', 4]\n sage: MT = Q.mutation_type(); MT.standard_quiver() == Q\n False\n\n sage: Q = ClusterQuiver(['GR',[3,7]]); Q\n Quiver on 6 vertices of type ['E', 6]\n\n sage: Q = ClusterQuiver(['TR',2]); Q\n Quiver on 3 vertices of type ['A', 3]\n sage: MT = Q.mutation_type(); MT.standard_quiver() == Q\n False\n sage: Q.mutate([1,0]); MT.standard_quiver() == Q\n True\n\n sage: Q = ClusterQuiver(['TR',3]); Q\n Quiver on 6 vertices of type ['D', 6]\n sage: MT = Q.mutation_type(); MT.standard_quiver() == Q\n False\n\n From a :class:`ClusterQuiver`::\n\n sage: Q = ClusterQuiver(['A',[2,5],1]); Q\n Quiver on 7 vertices of type ['A', [2, 5], 1]\n sage: T = ClusterQuiver( Q ); T\n Quiver on 7 vertices of type ['A', [2, 5], 1]\n\n From a Matrix::\n\n sage: Q = ClusterQuiver(['A',[2,5],1]); Q\n Quiver on 7 vertices of type ['A', [2, 5], 1]\n sage: T = ClusterQuiver( Q._M ); T\n Quiver on 7 vertices\n\n sage: Q = ClusterQuiver( matrix([[0,1,-1],[-1,0,1],[1,-1,0],[1,2,3]]) ); Q\n Quiver on 4 vertices with 1 frozen vertex\n\n sage: Q = ClusterQuiver( matrix([]) ); Q\n Quiver without vertices\n\n From a DiGraph::\n\n sage: Q = ClusterQuiver(['A',[2,5],1]); Q\n Quiver on 7 vertices of type ['A', [2, 5], 1]\n sage: T = ClusterQuiver( Q._digraph ); T\n Quiver on 7 vertices\n\n sage: Q = ClusterQuiver( DiGraph([[1,2],[2,3],[3,4],[4,1]]) ); Q\n Quiver on 4 vertices\n\n sage: Q = ClusterQuiver(DiGraph([['a', 'b'], ['b', 'c'], ['c', 'd'], ['d', 'e']]),\n ....: frozen=['c']); Q\n Quiver on 5 vertices with 1 frozen vertex\n sage: Q.mutation_type()\n [ ['A', 2], ['A', 2] ]\n sage: Q\n Quiver on 5 vertices of type [ ['A', 2], ['A', 2] ] with 1 frozen vertex\n\n From a List of edges::\n\n sage: Q = ClusterQuiver(['A',[2,5],1]); Q\n Quiver on 7 vertices of type ['A', [2, 5], 1]\n sage: T = ClusterQuiver( Q._digraph.edges(sort=True) ); T\n Quiver on 7 vertices\n\n sage: Q = ClusterQuiver([[1, 2], [2, 3], [3, 4], [4, 1]]); Q\n Quiver on 4 vertices\n\n TESTS::\n\n sage: Q = ClusterQuiver(DiGraph([[1,1]]))\n Traceback (most recent call last):\n ...\n ValueError: cannot add edge from 1 to 1 in graph without loops\n\n sage: Q = ClusterQuiver([[1,1]])\n Traceback (most recent call last):\n ...\n ValueError: cannot add edge from 1 to 1 in graph without loops\n\n sage: Q = ClusterQuiver(DiGraph([[1, 0],[0,1]]))\n Traceback (most recent call last):\n ...\n ValueError: the input DiGraph contains two-cycles\n\n sage: Q = ClusterQuiver('whatever')\n Traceback (most recent call last):\n ...\n ValueError: the input data was not recognized\n "
def __init__(self, data, frozen=None, user_labels=None):
"\n TESTS::\n\n sage: Q = ClusterQuiver(['A',4])\n sage: TestSuite(Q).run()\n "
from sage.combinat.cluster_algebra_quiver.cluster_seed import ClusterSeed
from sage.structure.element import is_Matrix
if isinstance(user_labels, list):
user_labels = [(tuple(x) if isinstance(x, list) else x) for x in user_labels]
elif isinstance(user_labels, dict):
values = [(tuple(user_labels[x]) if isinstance(user_labels[x], list) else user_labels[x]) for x in user_labels]
user_labels = {key: val for (key, val) in zip(user_labels.keys(), values)}
if (type(data) in [QuiverMutationType_Irreducible, QuiverMutationType_Reducible]):
if (frozen is not None):
print('The input specifies a mutation type, so the additional parameter frozen is ignored. Use set_frozen to freeze vertices.')
mutation_type = data
self.__init__(mutation_type.standard_quiver())
if user_labels:
self.relabel(user_labels)
self._nlist = list(user_labels)
elif (isinstance(data, (list, tuple)) and (isinstance(data[0], str) or all(((isinstance(comp, (list, tuple)) and isinstance(comp[0], str)) for comp in data)))):
if (frozen is not None):
print('The input specifies a mutation type, so the additional parameter frozen is ignored. Use set_frozen to freeze vertices.')
mutation_type = QuiverMutationType(data)
if ((len(data) == 2) and isinstance(data[0], str)):
if ((data[0] == 'TR') or (data[0] == 'GR') or ((data[0] == 'C') and (data[1] == 2))):
if (data[1] in ZZ):
quiv = ClusterQuiver(QuiverMutationType_Irreducible(data[0], data[1])._digraph)
quiv._mutation_type = mutation_type
self.__init__(quiv)
elif isinstance(data[1], list):
quiv = ClusterQuiver(QuiverMutationType_Irreducible(data[0], tuple(data[1]))._digraph)
quiv._mutation_type = mutation_type
self.__init__(quiv)
else:
self.__init__(mutation_type.standard_quiver())
elif ((len(data) == 3) and isinstance(data[0], str)):
if (((data[0] == 'F') and (data[1] == 4) and (data[2] == [2, 1])) or ((data[0] == 'G') and (data[1] == 2) and (data[2] == [3, 1]))):
quiv = ClusterQuiver(QuiverMutationType_Irreducible(data[0], data[1], tuple(data[2]))._digraph)
quiv._mutation_type = mutation_type
self.__init__(quiv)
elif (((data[0] == 'F') and (data[1] == 4) and (data[2] == (2, 1))) or ((data[0] == 'G') and (data[1] == 2) and (data[2] == (3, 1)))):
quiv = ClusterQuiver(QuiverMutationType_Irreducible(data[0], data[1], data[2])._digraph)
quiv._mutation_type = mutation_type
self.__init__(quiv)
elif ((data[0] == 'A') and isinstance(data[1], list) and (data[2] == 1)):
if ((len(data[1]) == 2) and (min(data[1]) == 0)):
quiv = ClusterQuiver(QuiverMutationType_Irreducible(data[0], tuple(data[1]), data[2])._digraph)
quiv._mutation_type = mutation_type
self.__init__(quiv)
else:
self.__init__(mutation_type.standard_quiver())
elif ((data[0] == 'A') and isinstance(data[1], tuple) and (data[2] == 1)):
if ((len(data[1]) == 2) and (min(data[1]) == 0)):
quiv = ClusterQuiver(QuiverMutationType_Irreducible(data[0], data[1], data[2])._digraph)
quiv._mutation_type = mutation_type
self.__init__(quiv)
else:
self.__init__(mutation_type.standard_quiver())
else:
self.__init__(mutation_type.standard_quiver())
else:
self.__init__(mutation_type.standard_quiver())
if user_labels:
if isinstance(user_labels, dict):
self._nlist = list(user_labels.keys())
else:
self._nlist = user_labels
self.relabel(self._nlist)
elif isinstance(data, ClusterSeed):
self.__init__(data.quiver())
elif isinstance(data, ClusterQuiver):
if (frozen is not None):
print('The input data is a quiver, therefore the additional parameter frozen is ignored. Use set_frozen to freeze vertices.')
self._M = copy(data._M)
self._M.set_immutable()
self._n = data._n
self._m = data._m
self._mlist = list(data._mlist)
self._nlist = list(data._nlist)
self._digraph = copy(data._digraph)
self._vertex_dictionary = data._vertex_dictionary
self._mutation_type = data._mutation_type
self._description = data._description
elif is_Matrix(data):
if (not _principal_part(data).is_skew_symmetrizable(positive=True)):
raise ValueError('The principal part of the matrix data must be skew-symmetrizable.')
if (frozen is not None):
print('The input data is a matrix, therefore the additional parameter frozen is ignored. Frozen vertices read off accordingly if the matrix is not square.')
self._M = copy(data).sparse_matrix()
self._M.set_immutable()
self._n = n = self._M.ncols()
self._m = m = (self._M.nrows() - self._n)
self._digraph = _matrix_to_digraph(self._M)
self._vertex_dictionary = {}
self._mutation_type = None
if user_labels:
if isinstance(user_labels, dict):
self._nlist = list(user_labels.keys())[0:n]
self._mlist = list(user_labels.keys())[n:(n + m)]
elif isinstance(user_labels, list):
self._nlist = user_labels[0:n]
self._mlist = user_labels[n:(n + m)]
self._digraph.relabel((self._nlist + self._mlist))
else:
self._mlist = list(range(n, (n + m)))
self._nlist = list(range(n))
if ((n + m) == 0):
self._description = 'Quiver without vertices'
elif ((n + m) == 1):
self._description = 'Quiver on 1 vertex'
else:
self._description = ('Quiver on %d vertices' % (n + m))
elif isinstance(data, DiGraph):
if (frozen is None):
frozen = []
if (not isinstance(frozen, (list, tuple))):
raise ValueError("'frozen' must be a list of vertices")
frozen = set(frozen)
if (not frozen.issubset(data.vertex_iterator())):
raise ValueError('frozen elements must be vertices')
mlist = self._mlist = list(frozen)
m = self._m = len(mlist)
try:
nlist = sorted((x for x in data if (x not in frozen)))
except TypeError:
nlist = sorted([x for x in data if (x not in frozen)], key=str)
self._nlist = nlist
n = self._n = len(nlist)
labelDict = {x: i for (i, x) in enumerate((nlist + mlist))}
dg = copy(data)
if data.has_loops():
raise ValueError('the input DiGraph contains a loop')
edges = set(data.edge_iterator(labels=False))
if any((((b, a) in edges) for (a, b) in edges)):
raise ValueError('the input DiGraph contains two-cycles')
dg_labelling = False
if (not (set(dg.vertex_iterator()) == set(range((n + m))))):
dg_labelling = (nlist + mlist)
dg.relabel(labelDict)
multiple_edges = dg.multiple_edges()
if multiple_edges:
multi_edges = {}
for (v1, v2, label) in multiple_edges:
if (label not in ZZ):
raise ValueError('the input DiGraph contains multiple edges labeled by non-integers')
elif ((v1, v2) in multi_edges):
multi_edges[(v1, v2)] += label
else:
multi_edges[(v1, v2)] = label
dg.delete_edge(v1, v2)
dg.add_edges([(v1, v2, multi_edges[(v1, v2)]) for (v1, v2) in multi_edges])
for edge in dg.edge_iterator():
if ((edge[0] >= n) and (edge[1] >= n)):
raise ValueError('the input digraph contains edges within the frozen vertices')
if (edge[2] is None):
dg.set_edge_label(edge[0], edge[1], (1, (- 1)))
edge = (edge[0], edge[1], (1, (- 1)))
elif (edge[2] in ZZ):
dg.set_edge_label(edge[0], edge[1], (edge[2], (- edge[2])))
edge = (edge[0], edge[1], (edge[2], (- edge[2])))
elif (isinstance(edge[2], list) and (len(edge[2]) != 2)):
raise ValueError('the input digraph contains an edge with the wrong type of list as a label')
elif (isinstance(edge[2], list) and (len(edge[2]) == 2)):
dg.set_edge_label(edge[0], edge[1], (edge[2][0], edge[2][1]))
edge = (edge[0], edge[1], (edge[2][0], edge[2][1]))
elif (((edge[0] >= n) or (edge[1] >= n)) and (not (edge[2][0] == (- edge[2][1])))):
raise ValueError('the input digraph contains an edge to or from a frozen vertex which is not skew-symmetric')
if (edge[2][0] < 0):
raise ValueError('the input digraph contains an edge of the form (a,-b) with negative a')
M = _edge_list_to_matrix(dg.edge_iterator(), list(range(n)), list(range(n, (n + m))))
if (not _principal_part(M).is_skew_symmetrizable(positive=True)):
raise ValueError('the input digraph must be skew-symmetrizable')
self._digraph = dg
self._vertex_dictionary = {}
if (dg_labelling is not False):
self.relabel(dg_labelling)
self._M = M
self._M.set_immutable()
if ((n + m) == 0):
self._description = 'Quiver without vertices'
elif ((n + m) == 1):
self._description = ('Quiver on %d vertex' % (n + m))
else:
self._description = ('Quiver on %d vertices' % (n + m))
self._mutation_type = None
elif (isinstance(data, (list, EdgesView)) and all((isinstance(x, (list, tuple)) for x in data))):
dg = DiGraph(data)
self.__init__(data=dg, frozen=frozen)
else:
raise ValueError('the input data was not recognized')
if self._m:
from sage.misc.stopgap import stopgap
stopgap('Having frozen nodes is known to produce wrong answers', 22381)
def __eq__(self, other):
"\n Return ``True`` if ``self`` and ``other`` represent the same quiver.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',5])\n sage: T = Q.mutate( 2, inplace=False )\n sage: Q.__eq__( T )\n False\n sage: T.mutate( 2 )\n sage: Q.__eq__( T )\n True\n "
return (isinstance(other, ClusterQuiver) and (self._M == other._M))
def __hash__(self):
"\n Return a hash of ``self``.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',5])\n sage: hash(Q) # indirect doctest\n 7654921743699262111 # 64-bit\n -1264862561 # 32-bit\n "
return hash(self._M)
def _repr_(self):
'\n Return the description of ``self``.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver([\'A\',5])\n sage: Q._repr_()\n "Quiver on 5 vertices of type [\'A\', 5]"\n '
name = self._description
if self._mutation_type:
if isinstance(self._mutation_type, str):
name += (' of ' + self._mutation_type)
else:
name += (' of type ' + str(self._mutation_type))
if (self._m == 1):
name += (' with %s frozen vertex' % self._m)
elif (self._m > 1):
name += (' with %s frozen vertices' % self._m)
return name
def plot(self, circular=True, center=(0, 0), directed=True, mark=None, save_pos=False, greens=[]):
"\n Return the plot of the underlying digraph of ``self``.\n\n INPUT:\n\n - ``circular`` -- (default: ``True``) if ``True``, the circular plot\n is chosen, otherwise >>spring<< is used.\n - ``center`` -- (default:(0,0)) sets the center of the circular plot,\n otherwise it is ignored.\n - ``directed`` -- (default: ``True``) if ``True``, the directed\n version is shown, otherwise the undirected.\n - ``mark`` -- (default: ``None``) if set to i, the vertex i is\n highlighted.\n - ``save_pos`` -- (default: ``False``) if ``True``, the positions\n of the vertices are saved.\n - ``greens`` -- (default: []) if set to a list, will display the green\n vertices as green\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',5])\n sage: Q.plot() # needs sage.plot sage.symbolic\n Graphics object consisting of 15 graphics primitives\n sage: Q.plot(circular=True) # needs sage.plot sage.symbolic\n Graphics object consisting of 15 graphics primitives\n sage: Q.plot(circular=True, mark=1) # needs sage.plot sage.symbolic\n Graphics object consisting of 15 graphics primitives\n "
from sage.plot.colors import rainbow
from sage.graphs.graph_generators import GraphGenerators
from sage.symbolic.constants import e, pi
from sage.rings.cc import CC
from sage.rings.imaginary_unit import I
graphs = GraphGenerators()
def _graphs_concentric_circles(n, m):
g1 = graphs.CycleGraph(n).get_pos()
g2 = graphs.CycleGraph(m).get_pos()
for i in g2:
z = (CC(g2[i]) * (e ** (((- pi) * I) / (2 * m))))
g2[i] = (z.real_part(), z.imag_part())
for i in range(m):
g1[(n + i)] = [(2 * g2[i][0]), (2 * g2[i][1])]
return g1
(n, m) = (self._n, self._m)
nlist = copy(self._nlist)
mlist = copy(self._mlist)
colors = rainbow(11)
color_dict = {colors[0]: [], colors[1]: [], colors[6]: [], colors[5]: []}
if directed:
dg = DiGraph(self._digraph)
else:
dg = Graph(self._digraph)
for edge in dg.edges(sort=True):
(v1, v2, (a, b)) = edge
if ((v1 in nlist) and (v2 in nlist)):
if ((a, b) == (1, (- 1))):
color_dict[colors[0]].append((v1, v2))
else:
color_dict[colors[6]].append((v1, v2))
elif ((a, b) == (1, (- 1))):
color_dict[colors[1]].append((v1, v2))
else:
color_dict[colors[5]].append((v1, v2))
if (a == (- b)):
if (a == 1):
dg.set_edge_label(v1, v2, '')
else:
dg.set_edge_label(v1, v2, a)
if (mark is not None):
if (mark in nlist):
nlist.remove(mark)
partition = (nlist, mlist, [mark])
elif (mark in mlist):
mlist.remove(mark)
partition = (nlist, mlist, [mark])
else:
raise ValueError('The given mark is not a vertex of self.')
else:
for i in greens:
if (i in nlist):
nlist.remove(i)
else:
mlist.remove(i)
partition = (nlist, mlist, greens)
vertex_color_dict = {'tomato': partition[0], 'lightblue': partition[1], 'lightgreen': partition[2]}
options = {'graph_border': True, 'edge_colors': color_dict, 'vertex_colors': vertex_color_dict, 'edge_labels': True, 'vertex_labels': True}
if circular:
pp = _graphs_concentric_circles(n, m)
options['pos'] = {}
for v in pp:
if (v in self._vertex_dictionary):
vkey = self._vertex_dictionary[v]
else:
vkey = v
options['pos'][vkey] = ((pp[v][0] + center[0]), (pp[v][1] + center[1]))
return dg.plot(**options)
def show(self, fig_size=1, circular=False, directed=True, mark=None, save_pos=False, greens=[]):
"\n Show the plot of the underlying digraph of ``self``.\n\n INPUT:\n\n - ``fig_size`` -- (default: 1) factor by which the size of the plot\n is multiplied.\n - ``circular`` -- (default: False) if True, the circular plot is\n chosen, otherwise >>spring<< is used.\n - ``directed`` -- (default: True) if True, the directed version is\n shown, otherwise the undirected.\n - ``mark`` -- (default: None) if set to i, the vertex i is highlighted.\n - ``save_pos`` -- (default:False) if True, the positions of the\n vertices are saved.\n - ``greens`` -- (default:[]) if set to a list, will display the green\n vertices as green\n\n TESTS::\n\n sage: Q = ClusterQuiver(['A',5])\n sage: Q.show() # long time\n "
(n, m) = (self._n, self._m)
plot = self.plot(circular=circular, directed=directed, mark=mark, save_pos=save_pos, greens=greens)
if circular:
plot.show(figsize=[((((fig_size * 3) * (n + m)) / 4) + 1), ((((fig_size * 3) * (n + m)) / 4) + 1)])
else:
plot.show(figsize=[((fig_size * n) + 1), ((fig_size * n) + 1)])
def interact(self, fig_size=1, circular=True):
"\n Start an interactive window for cluster quiver mutations.\n\n Only in *Jupyter notebook mode*.\n\n INPUT:\n\n - ``fig_size`` -- (default: 1) factor by which the size of the\n plot is multiplied.\n\n - ``circular`` -- (default: ``True``) if ``True``, the circular plot\n is chosen, otherwise >>spring<< is used.\n\n TESTS::\n\n sage: S = ClusterQuiver(['A',4])\n sage: S.interact() # needs sage.plot sage.symbolic\n ...VBox(children=...\n "
return cluster_interact(self, fig_size, circular, kind='quiver')
def save_image(self, filename, circular=False):
'\n Save the plot of the underlying digraph of ``self``.\n\n INPUT:\n\n - ``filename`` -- the filename the image is saved to.\n - ``circular`` -- (default: False) if True, the circular plot is chosen, otherwise >>spring<< is used.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver([\'F\',4,[1,2]])\n sage: import tempfile\n sage: with tempfile.NamedTemporaryFile(suffix=".png") as f: # needs sage.plot sage.symbolic\n ....: Q.save_image(f.name)\n '
graph_plot = self.plot(circular=circular)
graph_plot.save(filename=filename)
def qmu_save(self, filename=None):
'\n Save ``self`` in a ``.qmu`` file.\n\n This file can then be opened in Bernhard Keller\'s Quiver Applet.\n\n See https://webusers.imj-prg.fr/~bernhard.keller/quivermutation/\n\n INPUT:\n\n - ``filename`` -- the filename the image is saved to.\n\n If a filename is not specified, the default name is\n ``from_sage.qmu`` in the current sage directory.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver([\'F\',4,[1,2]])\n sage: import tempfile\n sage: with tempfile.NamedTemporaryFile(suffix=".qmu") as f: # needs sage.plot sage.symbolic\n ....: Q.qmu_save(f.name)\n\n Make sure we can save quivers with `m != n` frozen variables, see :trac:`14851`::\n\n sage: S = ClusterSeed([\'A\',3])\n sage: T1 = S.principal_extension()\n sage: Q = T1.quiver()\n sage: import tempfile\n sage: with tempfile.NamedTemporaryFile(suffix=".qmu") as f: # needs sage.plot sage.symbolic\n ....: Q.qmu_save(f.name)\n '
M = self.b_matrix()
if self.m():
from sage.matrix.constructor import Matrix
from sage.matrix.constructor import block_matrix
M1 = M.matrix_from_rows(list(range(self.n())))
M2 = M.matrix_from_rows(list(range(self.n(), (self.n() + self.m()))))
M3 = Matrix(self.m(), self.m())
M = block_matrix([[M1, (- M2.transpose())], [M2, M3]])
dg = self.digraph()
dg.plot(save_pos=True)
PP = dg.get_pos()
m = M.ncols()
if (filename is None):
filename = 'from_sage.qmu'
try:
self._default_filename = filename
except AttributeError:
pass
if (filename[(- 4):] != '.qmu'):
filename += '.qmu'
string = []
string.append('//Number of points')
string.append(str(m))
string.append('//Vertex radius')
string.append('9')
string.append('//Labels shown')
string.append('1')
string.append('//Matrix')
string.append(((str(m) + ' ') + str(m)))
for i in range(m):
string.append(' '.join((str(M[(i, j)]) for j in range(m))))
string.append('//Points')
for i in range(m):
(x, y) = PP[i]
txt = ((('9 ' + str((100 * x))) + ' ') + str((100 * y)))
if (i >= self.n()):
txt += ' 1'
string.append(txt)
string.append('//Historycounter')
string.append('-1')
string.append('//History')
string.append('')
string.append('//Cluster is null')
string = '\n'.join(string)
with open(filename, 'w') as myfile:
myfile.write(string)
def b_matrix(self):
"\n Return the b-matrix of ``self``.\n\n EXAMPLES::\n\n sage: ClusterQuiver(['A',4]).b_matrix()\n [ 0 1 0 0]\n [-1 0 -1 0]\n [ 0 1 0 1]\n [ 0 0 -1 0]\n\n sage: ClusterQuiver(['B',4]).b_matrix()\n [ 0 1 0 0]\n [-1 0 -1 0]\n [ 0 1 0 1]\n [ 0 0 -2 0]\n\n sage: ClusterQuiver(['D',4]).b_matrix()\n [ 0 1 0 0]\n [-1 0 -1 -1]\n [ 0 1 0 0]\n [ 0 1 0 0]\n\n sage: ClusterQuiver(QuiverMutationType([['A',2],['B',2]])).b_matrix()\n [ 0 1 0 0]\n [-1 0 0 0]\n [ 0 0 0 1]\n [ 0 0 -2 0]\n "
return copy(self._M)
def digraph(self):
"\n Return the underlying digraph of ``self``.\n\n EXAMPLES::\n\n sage: ClusterQuiver(['A',1]).digraph()\n Digraph on 1 vertex\n sage: list(ClusterQuiver(['A',1]).digraph())\n [0]\n sage: ClusterQuiver(['A',1]).digraph().edges(sort=True)\n []\n\n sage: ClusterQuiver(['A',4]).digraph()\n Digraph on 4 vertices\n sage: ClusterQuiver(['A',4]).digraph().edges(sort=True)\n [(0, 1, (1, -1)), (2, 1, (1, -1)), (2, 3, (1, -1))]\n\n sage: ClusterQuiver(['B',4]).digraph()\n Digraph on 4 vertices\n sage: ClusterQuiver(['A',4]).digraph().edges(sort=True)\n [(0, 1, (1, -1)), (2, 1, (1, -1)), (2, 3, (1, -1))]\n\n sage: ClusterQuiver(QuiverMutationType([['A',2],['B',2]])).digraph()\n Digraph on 4 vertices\n\n sage: ClusterQuiver(QuiverMutationType([['A',2],['B',2]])).digraph().edges(sort=True)\n [(0, 1, (1, -1)), (2, 3, (1, -2))]\n\n sage: ClusterQuiver(['C', 4], user_labels = ['x', 'y', 'z', 'w']).digraph().edges(sort=True)\n [('x', 'y', (1, -1)), ('z', 'w', (2, -1)), ('z', 'y', (1, -1))]\n "
return copy(self._digraph)
def mutation_type(self):
"\n Return the mutation type of ``self``.\n\n Return the mutation_type of each connected component of self if it can be determined,\n otherwise, the mutation type of this component is set to be unknown.\n\n The mutation types of the components are ordered by vertex labels.\n\n If you do many type recognitions, you should consider to save\n exceptional mutation types using\n :meth:`~sage.combinat.cluster_algebra_quiver.quiver_mutation_type.save_quiver_data`\n\n WARNING:\n\n - All finite types can be detected,\n - All affine types can be detected, EXCEPT affine type D (the algorithm is not yet implemented)\n - All exceptional types can be detected.\n\n EXAMPLES::\n\n sage: ClusterQuiver(['A',4]).mutation_type()\n ['A', 4]\n sage: ClusterQuiver(['A',(3,1),1]).mutation_type()\n ['A', [1, 3], 1]\n sage: ClusterQuiver(['C',2]).mutation_type()\n ['B', 2]\n sage: ClusterQuiver(['B',4,1]).mutation_type()\n ['BD', 4, 1]\n\n finite types::\n\n sage: Q = ClusterQuiver(['A',5])\n sage: Q._mutation_type = None\n sage: Q.mutation_type()\n ['A', 5]\n\n sage: Q = ClusterQuiver([(0,1),(1,2),(2,3),(3,4)])\n sage: Q.mutation_type()\n ['A', 5]\n\n sage: Q = ClusterQuiver(DiGraph([['a', 'b'], ['c', 'b'], ['c', 'd'], ['e', 'd']]),\n ....: frozen=['c'])\n sage: Q.mutation_type()\n [ ['A', 2], ['A', 2] ]\n\n affine types::\n\n sage: Q = ClusterQuiver(['E',8,[1,1]]); Q\n Quiver on 10 vertices of type ['E', 8, [1, 1]]\n sage: Q._mutation_type = None; Q\n Quiver on 10 vertices\n sage: Q.mutation_type() # long time\n ['E', 8, [1, 1]]\n\n the not yet working affine type D (unless user has saved small classical quiver data)::\n\n sage: Q = ClusterQuiver(['D',4,1])\n sage: Q._mutation_type = None\n sage: Q.mutation_type() # todo: not implemented\n ['D', 4, 1]\n\n the exceptional types::\n\n sage: Q = ClusterQuiver(['X',6])\n sage: Q._mutation_type = None\n sage: Q.mutation_type() # long time\n ['X', 6]\n\n examples from page 8 of [Ke2008]_::\n\n sage: dg = DiGraph(); dg.add_edges([(9,0),(9,4),(4,6),(6,7),(7,8),(8,3),(3,5),(5,6),(8,1),(2,3)])\n sage: ClusterQuiver( dg ).mutation_type() # long time\n ['E', 8, [1, 1]]\n\n sage: dg = DiGraph( { 0:[3], 1:[0,4], 2:[0,6], 3:[1,2,7], 4:[3,8], 5:[2], 6:[3,5], 7:[4,6], 8:[7] } )\n sage: ClusterQuiver( dg ).mutation_type() # long time\n ['E', 8, 1]\n\n sage: dg = DiGraph( { 0:[3,9], 1:[0,4], 2:[0,6], 3:[1,2,7], 4:[3,8], 5:[2], 6:[3,5], 7:[4,6], 8:[7], 9:[1] } )\n sage: ClusterQuiver( dg ).mutation_type() # long time\n ['E', 8, [1, 1]]\n\n infinite types::\n\n sage: Q = ClusterQuiver(['GR',[4,9]])\n sage: Q._mutation_type = None\n sage: Q.mutation_type()\n 'undetermined infinite mutation type'\n\n reducible types::\n\n sage: Q = ClusterQuiver([['A', 3], ['B', 3]])\n sage: Q._mutation_type = None\n sage: Q.mutation_type()\n [ ['A', 3], ['B', 3] ]\n\n sage: Q = ClusterQuiver([['A', 3], ['T', [4,4,4]]])\n sage: Q._mutation_type = None\n sage: Q.mutation_type()\n [['A', 3], 'undetermined infinite mutation type']\n\n sage: Q = ClusterQuiver([['A', 3], ['B', 3], ['T', [4,4,4]]])\n sage: Q._mutation_type = None\n sage: Q.mutation_type()\n [['A', 3], ['B', 3], 'undetermined infinite mutation type']\n\n sage: Q = ClusterQuiver([[0,1,2],[1,2,2],[2,0,2],[3,4,1],[4,5,1]])\n sage: Q.mutation_type()\n ['undetermined finite mutation type', ['A', 3]]\n\n TESTS::\n\n sage: Q = ClusterQuiver(matrix([[0, 3], [-1, 0], [1, 0], [0, 1]]))\n sage: Q.mutation_type()\n ['G', 2]\n sage: Q = ClusterQuiver(matrix([[0, -1, -1, 1, 0], [1, 0, 1, 0, 1], [1, -1, 0, -1, 0], [-1, 0, 1, 0, 1], [0, -1, 0, -1, 0], [0, 1, 0, -1, -1], [0, 1, -1, 0, 0]]))\n sage: Q.mutation_type()\n 'undetermined infinite mutation type'\n "
if (self._mutation_type is None):
if (self._m > 0):
dg = self._digraph.subgraph(self._nlist)
else:
dg = self._digraph
mutation_type = []
connected_components = sorted(dg.connected_components(sort=False))
for component in connected_components:
dg_component = dg.subgraph(component)
dg_component.relabel()
_dg_canonical_form(dg_component)
dig6 = _digraph_to_dig6(dg_component, hashable=True)
M = _dig6_to_matrix(dig6)
(is_finite, path) = is_mutation_finite(M)
if (is_finite is False):
mut_type_part = 'undetermined infinite mutation type'
else:
mut_type_part = _mutation_type_from_data(dg_component.order(), dig6, compute_if_necessary=False)
if (mut_type_part == 'unknown'):
mut_type_part = _connected_mutation_type(dg_component)
if (mut_type_part == 'unknown'):
mut_type_part = _mutation_type_from_data(dg_component.order(), dig6, compute_if_necessary=True)
if (mut_type_part == 'unknown'):
mut_type_part = 'undetermined finite mutation type'
mutation_type.append(mut_type_part)
if (len(mutation_type) == 0):
mutation_type = None
elif (len(mutation_type) == 1):
mutation_type = mutation_type[0]
elif (len(mutation_type) > 1):
if any((isinstance(mut_type_part, str) for mut_type_part in mutation_type)):
pass
else:
mutation_type = QuiverMutationType(mutation_type)
self._mutation_type = mutation_type
return self._mutation_type
def n(self):
"\n Return the number of free vertices of ``self``.\n\n EXAMPLES::\n\n sage: ClusterQuiver(['A',4]).n()\n 4\n sage: ClusterQuiver(['A',(3,1),1]).n()\n 4\n sage: ClusterQuiver(['B',4]).n()\n 4\n sage: ClusterQuiver(['B',4,1]).n()\n 5\n "
return self._n
def m(self):
"\n Return the number of frozen vertices of ``self``.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',4])\n sage: Q.m()\n 0\n\n sage: T = ClusterQuiver(Q.digraph().edges(sort=True), frozen=[3])\n sage: T.n()\n 3\n sage: T.m()\n 1\n "
return self._m
def free_vertices(self):
"\n Return the list of free vertices of ``self``.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(DiGraph([['a', 'b'], ['c', 'b'], ['c', 'd'], ['e', 'd']]),\n ....: frozen=['b', 'd'])\n sage: Q.free_vertices()\n ['a', 'c', 'e']\n "
return self._nlist
def frozen_vertices(self):
"\n Return the list of frozen vertices of ``self``.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(DiGraph([['a', 'b'], ['c', 'b'], ['c', 'd'], ['e', 'd']]),\n ....: frozen=['b', 'd'])\n sage: sorted(Q.frozen_vertices())\n ['b', 'd']\n "
return self._mlist
def canonical_label(self, certificate=False):
"\n Return the canonical labelling of ``self``.\n\n See :meth:`sage.graphs.generic_graph.GenericGraph.canonical_label`.\n\n INPUT:\n\n - ``certificate`` -- boolean (default: False) if True, the dictionary\n from ``self.vertices()`` to the vertices of the returned quiver\n is returned as well.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',4]); Q.digraph().edges(sort=True)\n [(0, 1, (1, -1)), (2, 1, (1, -1)), (2, 3, (1, -1))]\n\n sage: T = Q.canonical_label(); T.digraph().edges(sort=True)\n [(0, 3, (1, -1)), (1, 2, (1, -1)), (1, 3, (1, -1))]\n\n sage: T, iso = Q.canonical_label(certificate=True)\n sage: T.digraph().edges(sort=True); iso\n [(0, 3, (1, -1)), (1, 2, (1, -1)), (1, 3, (1, -1))]\n {0: 0, 1: 3, 2: 1, 3: 2}\n\n sage: Q = ClusterQuiver(QuiverMutationType([['B',2],['A',1]])); Q\n Quiver on 3 vertices of type [ ['B', 2], ['A', 1] ]\n\n sage: Q.canonical_label()\n Quiver on 3 vertices of type [ ['A', 1], ['B', 2] ]\n\n sage: Q.canonical_label(certificate=True)\n (Quiver on 3 vertices of type [ ['A', 1], ['B', 2] ], {0: 1, 1: 2, 2: 0})\n "
dg = copy(self._digraph)
(iso, _) = _dg_canonical_form(dg, frozen=self._mlist)
frozen = [iso[i] for i in self._mlist]
Q = ClusterQuiver(dg, frozen=frozen)
if self._mutation_type:
if dg.is_connected():
Q._mutation_type = self._mutation_type
else:
CC = sorted(self._digraph.connected_components(sort=False))
CC_new = sorted(zip([sorted((iso[i] for i in L)) for L in CC], range(len(CC))))
comp_iso = [L[1] for L in CC_new]
Q._mutation_type = []
for i in range(len(CC_new)):
Q._mutation_type.append(copy(self._mutation_type.irreducible_components()[comp_iso[i]]))
Q._mutation_type = QuiverMutationType(Q._mutation_type)
if certificate:
return (Q, iso)
else:
return Q
def is_acyclic(self):
"\n Return true if ``self`` is acyclic.\n\n EXAMPLES::\n\n sage: ClusterQuiver(['A',4]).is_acyclic()\n True\n\n sage: ClusterQuiver(['A',[2,1],1]).is_acyclic()\n True\n\n sage: ClusterQuiver([[0,1],[1,2],[2,0]]).is_acyclic()\n False\n "
return self._digraph.is_directed_acyclic()
def is_bipartite(self, return_bipartition=False):
"\n Return ``True`` if ``self`` is bipartite.\n\n EXAMPLES::\n\n sage: ClusterQuiver(['A',[3,3],1]).is_bipartite()\n True\n\n sage: ClusterQuiver(['A',[4,3],1]).is_bipartite()\n False\n "
dg = copy(self._digraph)
dg.delete_vertices(list(range(self._n, (self._n + self._m))))
if any(((dg.in_degree(i) and dg.out_degree(i)) for i in dg)):
return False
if (not return_bipartition):
return True
return dg.to_undirected().bipartite_sets()
def exchangeable_part(self):
"\n Return the restriction to the principal part (i.e. exchangeable part) of ``self``, the subquiver obtained by deleting the frozen vertices of ``self``.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',4])\n sage: T = ClusterQuiver(Q.digraph().edges(sort=True), frozen=[3])\n sage: T.digraph().edges(sort=True)\n [(0, 1, (1, -1)), (2, 1, (1, -1)), (2, 3, (1, -1))]\n\n sage: T.exchangeable_part().digraph().edges(sort=True)\n [(0, 1, (1, -1)), (2, 1, (1, -1))]\n\n sage: Q2 = Q.principal_extension()\n sage: Q3 = Q2.principal_extension()\n sage: Q2.exchangeable_part() == Q3.exchangeable_part()\n True\n "
dg = DiGraph(self._digraph)
dg.delete_vertices(list(range(self._n, (self._n + self._m))))
Q = ClusterQuiver(dg)
Q._mutation_type = self._mutation_type
return Q
def principal_extension(self, inplace=False):
"\n Return the principal extension of ``self``, adding n frozen vertices to any previously frozen vertices. I.e., the quiver obtained by adding an outgoing edge to every mutable vertex of ``self``.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',2]); Q\n Quiver on 2 vertices of type ['A', 2]\n sage: T = Q.principal_extension(); T\n Quiver on 4 vertices of type ['A', 2] with 2 frozen vertices\n sage: T2 = T.principal_extension(); T2\n Quiver on 6 vertices of type ['A', 2] with 4 frozen vertices\n sage: Q.digraph().edges(sort=True)\n [(0, 1, (1, -1))]\n sage: T.digraph().edges(sort=True)\n [(0, 1, (1, -1)), (2, 0, (1, -1)), (3, 1, (1, -1))]\n sage: T2.digraph().edges(sort=True)\n [(0, 1, (1, -1)), (2, 0, (1, -1)), (3, 1, (1, -1)), (4, 0, (1, -1)), (5, 1, (1, -1))]\n "
dg = DiGraph(self._digraph)
dg.add_edges([(((self._n + self._m) + i), i) for i in range(self._n)])
Q = ClusterQuiver(dg, frozen=list(range(self._n, ((self._n + self._m) + self._n))))
Q._mutation_type = self._mutation_type
if inplace:
self.__init__(Q)
else:
return Q
def first_sink(self):
"\n Return the first vertex of ``self`` that is a sink.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',5])\n sage: Q.mutate([1,2,4,3,2])\n sage: Q.first_sink()\n 0\n "
sinks = self.digraph().sinks()
if sinks:
return sinks[0]
return None
def sinks(self):
"\n Return all vertices of ``self`` that are sinks.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',5])\n sage: Q.mutate([1,2,4,3,2])\n sage: Q.sinks()\n [0, 2]\n\n sage: Q = ClusterQuiver(['A',5])\n sage: Q.mutate([2,1,3,4,2])\n sage: Q.sinks()\n [3]\n "
return self.digraph().sinks()
def first_source(self):
"\n Return the first vertex of ``self`` that is a source\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',5])\n sage: Q.mutate([2,1,3,4,2])\n sage: Q.first_source()\n 1\n "
sources = self.digraph().sources()
if sources:
return sources[0]
return None
def sources(self):
"\n Return all vertices of ``self`` that are sources.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',5])\n sage: Q.mutate([1,2,4,3,2])\n sage: Q.sources()\n []\n\n sage: Q = ClusterQuiver(['A',5])\n sage: Q.mutate([2,1,3,4,2])\n sage: Q.sources()\n [1]\n "
return self.digraph().sources()
def mutate(self, data, inplace=True):
"\n Mutates ``self`` at a sequence of vertices.\n\n INPUT:\n\n - ``sequence`` -- a vertex of ``self``, an iterator of vertices of ``self``,\n a function which takes in the ClusterQuiver and returns a vertex or an iterator of vertices,\n or a string of the parameter wanting to be called on ClusterQuiver that will return a vertex or\n an iterator of vertices.\n - ``inplace`` -- (default: True) if False, the result is returned, otherwise ``self`` is modified.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',4]); Q.b_matrix()\n [ 0 1 0 0]\n [-1 0 -1 0]\n [ 0 1 0 1]\n [ 0 0 -1 0]\n\n sage: Q.mutate(0); Q.b_matrix()\n [ 0 -1 0 0]\n [ 1 0 -1 0]\n [ 0 1 0 1]\n [ 0 0 -1 0]\n\n sage: T = Q.mutate(0, inplace=False); T\n Quiver on 4 vertices of type ['A', 4]\n\n sage: Q.mutate(0)\n sage: Q == T\n True\n\n sage: Q.mutate([0,1,0])\n sage: Q.b_matrix()\n [ 0 -1 1 0]\n [ 1 0 0 0]\n [-1 0 0 1]\n [ 0 0 -1 0]\n\n sage: Q = ClusterQuiver(QuiverMutationType([['A',1],['A',3]]))\n sage: Q.b_matrix()\n [ 0 0 0 0]\n [ 0 0 1 0]\n [ 0 -1 0 -1]\n [ 0 0 1 0]\n\n sage: T = Q.mutate(0,inplace=False)\n sage: Q == T\n True\n\n sage: Q = ClusterQuiver(['A',3]); Q.b_matrix()\n [ 0 1 0]\n [-1 0 -1]\n [ 0 1 0]\n sage: Q.mutate('first_sink'); Q.b_matrix()\n [ 0 -1 0]\n [ 1 0 1]\n [ 0 -1 0]\n sage: Q.mutate('first_source'); Q.b_matrix()\n [ 0 1 0]\n [-1 0 -1]\n [ 0 1 0]\n\n sage: dg = DiGraph()\n sage: dg.add_vertices(['a','b','c','d','e'])\n sage: dg.add_edges([['a','b'], ['b','c'], ['c','d'], ['d','e']])\n sage: Q2 = ClusterQuiver(dg, frozen=['c']); Q2.b_matrix()\n [ 0 1 0 0]\n [-1 0 0 0]\n [ 0 0 0 1]\n [ 0 0 -1 0]\n [ 0 -1 1 0]\n sage: Q2.mutate('a'); Q2.b_matrix()\n [ 0 -1 0 0]\n [ 1 0 0 0]\n [ 0 0 0 1]\n [ 0 0 -1 0]\n [ 0 -1 1 0]\n\n sage: dg = DiGraph([['a', 'b'], ['b', 'c']], format='list_of_edges')\n sage: Q = ClusterQuiver(dg);Q\n Quiver on 3 vertices\n sage: Q.mutate(['a','b'],inplace=False).digraph().edges(sort=True)\n [('a', 'b', (1, -1)), ('c', 'b', (1, -1))]\n\n TESTS::\n\n sage: Q = ClusterQuiver(['A',4]); Q.mutate(0,1)\n Traceback (most recent call last):\n ...\n ValueError: The second parameter must be boolean. To mutate at a sequence of length 2, input it as a list.\n\n sage: Q = ClusterQuiver(['A',4]); Q.mutate(0,0)\n Traceback (most recent call last):\n ...\n ValueError: The second parameter must be boolean. To mutate at a sequence of length 2, input it as a list.\n "
dg = self._digraph
V = nlist = self._nlist
mlist = self._mlist
if isinstance(data, str):
if (data not in V):
data = getattr(self, data)()
if callable(data):
data = data(self)
if (data is None):
raise ValueError('Not mutating: No vertices given.')
if (data in V):
seq = [data]
else:
seq = data
if isinstance(seq, tuple):
seq = list(seq)
if (not isinstance(seq, list)):
raise ValueError('The quiver can only be mutated at a vertex or at a sequence of vertices')
if (not isinstance(inplace, bool)):
raise ValueError('The second parameter must be boolean. To mutate at a sequence of length 2, input it as a list.')
if any(((v not in V) for v in seq)):
v = next((v for v in seq if (v not in V)))
raise ValueError(('The quiver cannot be mutated at the vertex %s' % v))
for v in seq:
dg = _digraph_mutate(dg, v, frozen=mlist)
if inplace:
self._M = _edge_list_to_matrix(dg.edge_iterator(), nlist, mlist)
self._M.set_immutable()
self._digraph = dg
else:
Q = ClusterQuiver(dg, frozen=mlist)
Q._mutation_type = self._mutation_type
return Q
def mutation_sequence(self, sequence, show_sequence=False, fig_size=1.2):
"\n Return a list containing the sequence of quivers obtained from ``self`` by a sequence of mutations on vertices.\n\n INPUT:\n\n - ``sequence`` -- a list or tuple of vertices of ``self``.\n - ``show_sequence`` -- (default: ``False``) if ``True``, a png containing the mutation sequence is shown.\n - ``fig_size`` -- (default: 1.2) factor by which the size of the sequence is expanded.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',4])\n sage: seq = Q.mutation_sequence([0,1]); seq\n [Quiver on 4 vertices of type ['A', 4],\n Quiver on 4 vertices of type ['A', 4],\n Quiver on 4 vertices of type ['A', 4]]\n sage: [T.b_matrix() for T in seq]\n [\n [ 0 1 0 0] [ 0 -1 0 0] [ 0 1 -1 0]\n [-1 0 -1 0] [ 1 0 -1 0] [-1 0 1 0]\n [ 0 1 0 1] [ 0 1 0 1] [ 1 -1 0 1]\n [ 0 0 -1 0], [ 0 0 -1 0], [ 0 0 -1 0]\n ]\n "
n = self._n
m = self._m
if (m == 0):
width_factor = 3
fig_size = (((fig_size * 2) * n) / 3)
else:
width_factor = 6
fig_size = (((fig_size * 4) * n) / 3)
V = list(range(n))
if isinstance(sequence, tuple):
sequence = list(sequence)
if (not isinstance(sequence, list)):
raise ValueError('The quiver can only be mutated at a vertex or at a sequence of vertices')
if any(((v not in V) for v in sequence)):
v = next((v for v in sequence if (v not in V)))
raise ValueError(('The quiver can only be mutated at the vertex %s' % v))
quiver = copy(self)
quiver_sequence = []
quiver_sequence.append(copy(quiver))
for v in sequence:
quiver.mutate(v)
quiver_sequence.append(copy(quiver))
if show_sequence:
from sage.plot.plot import Graphics
from sage.plot.text import text
def _plot_arrow(v, k, center=(0, 0)):
return ((text('$\\longleftrightarrow$', (center[0], center[1]), fontsize=25) + text((('$\\mu_' + str(v)) + '$'), (center[0], (center[1] + 0.15)), fontsize=15)) + text((('$' + str(k)) + '$'), (center[0], (center[1] - 0.2)), fontsize=15))
plot_sequence = [quiver_sequence[i].plot(circular=True, center=((i * width_factor), 0)) for i in range(len(quiver_sequence))]
arrow_sequence = [_plot_arrow(sequence[i], (i + 1), center=(((i + 0.5) * width_factor), 0)) for i in range(len(sequence))]
sequence = []
for i in range(len(plot_sequence)):
if (i < len(arrow_sequence)):
sequence.append((plot_sequence[i] + arrow_sequence[i]))
else:
sequence.append(plot_sequence[i])
plot_obj = Graphics()
for elem in sequence:
plot_obj += elem
plot_obj.show(axes=False, figsize=[(fig_size * len(quiver_sequence)), fig_size])
return quiver_sequence
def reorient(self, data):
"\n Reorient ``self`` with respect to the given total order, or\n with respect to an iterator of edges in ``self`` to be\n reverted.\n\n .. WARNING::\n\n This operation might change the mutation type of ``self``.\n\n INPUT:\n\n - ``data`` -- an iterator defining a total order on\n ``self.vertices()``, or an iterator of edges in ``self`` to\n be reoriented.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',(2,3),1])\n sage: Q.mutation_type()\n ['A', [2, 3], 1]\n\n sage: Q.reorient([(0,1),(1,2),(2,3),(3,4)])\n sage: Q.mutation_type()\n ['D', 5]\n\n sage: Q.reorient([0,1,2,3,4])\n sage: Q.mutation_type()\n ['A', [1, 4], 1]\n\n TESTS::\n\n sage: Q = ClusterQuiver(['A',2])\n sage: Q.reorient([])\n Traceback (most recent call last):\n ...\n ValueError: empty input\n sage: Q.reorient([3,4])\n Traceback (most recent call last):\n ...\n ValueError: not a total order on the vertices of the quiver or\n a list of edges to be oriented\n "
if (not data):
raise ValueError('empty input')
first = data[0]
if (set(data) == set(range((self._n + self._m)))):
dg_new = DiGraph()
for edge in self._digraph.edges(sort=True):
if (data.index(edge[0]) < data.index(edge[1])):
dg_new.add_edge(edge[0], edge[1], edge[2])
else:
dg_new.add_edge(edge[1], edge[0], edge[2])
self._digraph = dg_new
self._M = _edge_list_to_matrix(dg_new.edges(sort=True), self._nlist, self._mlist)
self._M.set_immutable()
self._mutation_type = None
elif (isinstance(first, (list, tuple)) and (len(first) == 2)):
edges = self._digraph.edges(sort=True, labels=False)
for edge in data:
if ((edge[1], edge[0]) in edges):
label = self._digraph.edge_label(edge[1], edge[0])
self._digraph.delete_edge(edge[1], edge[0])
self._digraph.add_edge(edge[0], edge[1], label)
self._M = _edge_list_to_matrix(self._digraph.edges(sort=True), self._nlist, self._mlist)
self._M.set_immutable()
self._mutation_type = None
else:
raise ValueError('not a total order on the vertices of the quiver or a list of edges to be oriented')
def mutation_class_iter(self, depth=infinity, show_depth=False, return_paths=False, data_type='quiver', up_to_equivalence=True, sink_source=False):
'\n Return an iterator for the mutation class of ``self`` together with certain constraints.\n\n INPUT:\n\n - ``depth`` -- (default: infinity) integer, only quivers with distance at most depth from self are returned.\n - ``show_depth`` -- (default: False) if True, the actual depth of the mutation is shown.\n - ``return_paths`` -- (default: False) if True, a shortest path of mutation sequences from self to the given quiver is returned as well.\n - ``data_type`` -- (default: "quiver") can be one of the following::\n\n * "quiver"\n * "matrix"\n * "digraph"\n * "dig6"\n * "path"\n\n - ``up_to_equivalence`` -- (default: True) if True, only one quiver for each graph-isomorphism class is recorded.\n - ``sink_source`` -- (default: False) if True, only mutations at sinks and sources are applied.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver([\'A\',3])\n sage: it = Q.mutation_class_iter()\n sage: for T in it: print(T)\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n\n sage: it = Q.mutation_class_iter(depth=1)\n sage: for T in it: print(T)\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n\n sage: it = Q.mutation_class_iter(show_depth=True)\n sage: for T in it: pass\n Depth: 0 found: 1 Time: ... s\n Depth: 1 found: 3 Time: ... s\n Depth: 2 found: 4 Time: ... s\n\n sage: it = Q.mutation_class_iter(return_paths=True)\n sage: for T in it: print(T)\n (Quiver on 3 vertices of type [\'A\', 3], [])\n (Quiver on 3 vertices of type [\'A\', 3], [1])\n (Quiver on 3 vertices of type [\'A\', 3], [0])\n (Quiver on 3 vertices of type [\'A\', 3], [0, 1])\n\n sage: it = Q.mutation_class_iter(up_to_equivalence=False)\n sage: for T in it: print(T)\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n\n sage: it = Q.mutation_class_iter(return_paths=True,up_to_equivalence=False)\n sage: mutation_class = list(it)\n sage: len(mutation_class)\n 14\n sage: mutation_class[0]\n (Quiver on 3 vertices of type [\'A\', 3], [])\n\n sage: Q = ClusterQuiver([\'A\',3])\n sage: it = Q.mutation_class_iter(data_type=\'path\')\n sage: for T in it: print(T)\n []\n [1]\n [0]\n [0, 1]\n\n sage: Q = ClusterQuiver([\'A\',3])\n sage: it = Q.mutation_class_iter(return_paths=True,data_type=\'matrix\')\n sage: next(it)\n (\n [ 0 0 1]\n [ 0 0 1]\n [-1 -1 0], []\n )\n\n sage: dg = DiGraph([[\'a\', \'b\'], [\'b\', \'c\']], format=\'list_of_edges\')\n sage: S = ClusterQuiver(dg, frozen=[\'b\'])\n sage: S.mutation_class()\n [Quiver on 3 vertices with 1 frozen vertex,\n Quiver on 3 vertices with 1 frozen vertex,\n Quiver on 3 vertices with 1 frozen vertex]\n '
if (data_type == 'path'):
return_paths = False
if (data_type == 'dig6'):
return_dig6 = True
else:
return_dig6 = False
dg = ClusterQuiver(self._M).digraph()
frozen = list(range(self._n, (self._n + self._m)))
MC_iter = _mutation_class_iter(dg, self._n, self._m, depth=depth, return_dig6=return_dig6, show_depth=show_depth, up_to_equivalence=up_to_equivalence, sink_source=sink_source)
for data in MC_iter:
if (data_type == 'quiver'):
next_element = ClusterQuiver(data[0], frozen=frozen)
next_element._mutation_type = self._mutation_type
elif (data_type == 'matrix'):
next_element = ClusterQuiver(data[0], frozen=frozen)._M
elif (data_type == 'digraph'):
next_element = data[0]
elif (data_type == 'dig6'):
next_element = data[0]
elif (data_type == 'path'):
next_element = data[1]
else:
raise ValueError('the parameter for data_type was not recognized')
if return_paths:
(yield (next_element, data[1]))
else:
(yield next_element)
def mutation_class(self, depth=infinity, show_depth=False, return_paths=False, data_type='quiver', up_to_equivalence=True, sink_source=False):
'\n Return the mutation class of ``self`` together with certain constraints.\n\n INPUT:\n\n - ``depth`` -- (default: ``infinity`) integer, only seeds with\n distance at most depth from ``self`` are returned\n - ``show_depth`` -- (default: ``False``) if ``True``, the actual depth\n of the mutation is shown\n - ``return_paths`` -- (default: ``False``) if ``True``, a shortest\n path of mutation sequences from self to the given quiver is\n returned as well\n - ``data_type`` -- (default: ``"quiver"``) can be one of\n the following:\n\n * ``"quiver"`` -- the quiver is returned\n * ``"dig6"`` -- the dig6-data is returned\n * ``"path"`` -- shortest paths of mutation sequences from\n ``self`` are returned\n\n - ``sink_source`` -- (default: ``False``) if ``True``, only mutations\n at sinks and sources are applied\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver([\'A\',3])\n sage: Ts = Q.mutation_class()\n sage: for T in Ts: print(T)\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n\n sage: Ts = Q.mutation_class(depth=1)\n sage: for T in Ts: print(T)\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n\n sage: Ts = Q.mutation_class(show_depth=True)\n Depth: 0 found: 1 Time: ... s\n Depth: 1 found: 3 Time: ... s\n Depth: 2 found: 4 Time: ... s\n\n sage: Ts = Q.mutation_class(return_paths=True)\n sage: for T in Ts: print(T)\n (Quiver on 3 vertices of type [\'A\', 3], [])\n (Quiver on 3 vertices of type [\'A\', 3], [1])\n (Quiver on 3 vertices of type [\'A\', 3], [0])\n (Quiver on 3 vertices of type [\'A\', 3], [0, 1])\n\n sage: Ts = Q.mutation_class(up_to_equivalence=False)\n sage: for T in Ts: print(T)\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n Quiver on 3 vertices of type [\'A\', 3]\n\n sage: Ts = Q.mutation_class(return_paths=True,up_to_equivalence=False)\n sage: len(Ts)\n 14\n sage: Ts[0]\n (Quiver on 3 vertices of type [\'A\', 3], [])\n\n sage: Ts = Q.mutation_class(show_depth=True)\n Depth: 0 found: 1 Time: ... s\n Depth: 1 found: 3 Time: ... s\n Depth: 2 found: 4 Time: ... s\n\n sage: Ts = Q.mutation_class(show_depth=True, up_to_equivalence=False)\n Depth: 0 found: 1 Time: ... s\n Depth: 1 found: 4 Time: ... s\n Depth: 2 found: 6 Time: ... s\n Depth: 3 found: 10 Time: ... s\n Depth: 4 found: 14 Time: ... s\n\n TESTS::\n\n sage: all(len(ClusterQuiver([\'A\',n]).mutation_class())\n ....: == ClusterQuiver([\'A\',n]).mutation_type().class_size()\n ....: for n in [2..6])\n True\n\n sage: all(len(ClusterQuiver([\'B\',n]).mutation_class())\n ....: == ClusterQuiver([\'B\',n]).mutation_type().class_size()\n ....: for n in [2..6])\n True\n '
if ((depth is infinity) and (not self.is_mutation_finite())):
raise ValueError('the mutation class can - for infinite mutation types - only be computed up to a given depth')
return [Q for Q in self.mutation_class_iter(depth=depth, show_depth=show_depth, return_paths=return_paths, data_type=data_type, up_to_equivalence=up_to_equivalence, sink_source=sink_source)]
def is_finite(self):
"\n Return ``True`` if ``self`` is of finite type.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',3])\n sage: Q.is_finite()\n True\n sage: Q = ClusterQuiver(['A',[2,2],1])\n sage: Q.is_finite()\n False\n sage: Q = ClusterQuiver([['A',3],['B',3]])\n sage: Q.is_finite()\n True\n sage: Q = ClusterQuiver(['T',[4,4,4]])\n sage: Q.is_finite()\n False\n sage: Q = ClusterQuiver([['A',3],['T',[4,4,4]]])\n sage: Q.is_finite()\n False\n sage: Q = ClusterQuiver([['A',3],['T',[2,2,3]]])\n sage: Q.is_finite()\n True\n sage: Q = ClusterQuiver([['A',3],['D',5]])\n sage: Q.is_finite()\n True\n sage: Q = ClusterQuiver([['A',3],['D',5,1]])\n sage: Q.is_finite()\n False\n\n sage: Q = ClusterQuiver([[0,1,2],[1,2,2],[2,0,2]])\n sage: Q.is_finite()\n False\n\n sage: Q = ClusterQuiver([[0,1,2],[1,2,2],[2,0,2],[3,4,1],[4,5,1]])\n sage: Q.is_finite()\n False\n "
mt = self.mutation_type()
return ((type(mt) in [QuiverMutationType_Irreducible, QuiverMutationType_Reducible]) and mt.is_finite())
def is_mutation_finite(self, nr_of_checks=None, return_path=False):
"\n Uses a non-deterministic method by random mutations in various directions. Can result in a wrong answer.\n\n INPUT:\n\n - ``nr_of_checks`` -- (default: None) number of mutations applied. Standard is 500*(number of vertices of self).\n - ``return_path`` -- (default: False) if True, in case of self not being mutation finite, a path from self to a quiver with an edge label (a,-b) and a*b > 4 is returned.\n\n ALGORITHM:\n\n A quiver is mutation infinite if and only if every edge label (a,-b) satisfy a*b > 4.\n Thus, we apply random mutations in random directions\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',10])\n sage: Q._mutation_type = None\n sage: Q.is_mutation_finite()\n True\n\n sage: Q = ClusterQuiver([(0,1),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(2,9)])\n sage: Q.is_mutation_finite()\n False\n "
if (self._n <= 2):
is_finite = True
path = None
elif ((not return_path) and (self._mutation_type == 'undetermined infinite mutation type')):
is_finite = False
elif ((type(self._mutation_type) in [QuiverMutationType_Irreducible, QuiverMutationType_Reducible]) and self._mutation_type.is_mutation_finite()):
is_finite = True
path = None
elif ((not return_path) and (type(self._mutation_type) in [QuiverMutationType_Irreducible, QuiverMutationType_Reducible]) and (not self._mutation_type.is_mutation_finite())):
is_finite = False
else:
dig6 = _digraph_to_dig6(self.digraph())
M = _dig6_to_matrix(dig6)
(is_finite, path) = is_mutation_finite(M, nr_of_checks=nr_of_checks)
if return_path:
return (is_finite, path)
else:
return is_finite
def number_of_edges(self):
"\n Return the total number of edges on the quiver\n\n Note: This only works with non-valued quivers. If used on a\n non-valued quiver then the positive value is taken to be the number of edges added\n\n OUTPUT:\n\n An integer of the number of edges.\n\n EXAMPLES::\n\n sage: S = ClusterQuiver(['A',4]); S.number_of_edges()\n 3\n\n sage: S = ClusterQuiver(['B',4]); S.number_of_edges()\n 3\n "
digraph_edges = self.digraph().edges(sort=True)
total_edges = 0
for edge in digraph_edges:
total_edges += edge[2][0]
return total_edges
def relabel(self, relabelling, inplace=True):
"\n Return the quiver after doing a relabelling\n\n Will relabel the vertices of the quiver\n\n INPUT:\n\n - ``relabelling`` -- Dictionary of labels to move around\n - ``inplace`` -- (default:True) if True, will return a duplicate of the quiver\n\n EXAMPLES::\n\n sage: S = ClusterQuiver(['A',4]).relabel({1:'5',2:'go'})\n "
if inplace:
quiver = self
else:
quiver = ClusterQuiver(self)
old_vertices = list(quiver.digraph())
digraph_labels = {}
dict_labels = {}
if isinstance(relabelling, list):
digraph_labels = {old_vertices[i]: relabelling[i] for i in range(len(relabelling))}
dict_labels = {range(len(relabelling))[i]: relabelling[i] for i in range(len(relabelling))}
elif isinstance(relabelling, dict):
for key in relabelling:
val = relabelling[key]
if (key in old_vertices):
digraph_labels[key] = val
loc = [i for (i, x) in enumerate(old_vertices) if (x == key)][0]
dict_labels[loc] = val
elif (isinstance(key, int) and (len(old_vertices) > key)):
digraph_labels[old_vertices[key]] = val
dict_labels[key] = val
quiver._digraph.relabel(digraph_labels)
quiver._vertex_dictionary = dict_labels
return quiver
def poincare_semistable(self, theta, d):
"\n Return the Poincaré polynomial of the moduli space of semi-stable\n representations of dimension vector `d`.\n\n INPUT:\n\n - ``theta`` -- stability weight, as list or vector of rationals\n - ``d`` -- dimension vector, as list or vector of coprime integers\n\n The semi-stability is taken with respect to the slope function\n\n .. MATH::\n\n \\mu(d) = \\theta(d) / \\operatorname{dim}(d)\n\n where `d` is a dimension vector.\n\n This uses the matrix-inversion algorithm from [Rei2002]_.\n\n EXAMPLES::\n\n sage: Q = ClusterQuiver(['A',2])\n sage: Q.poincare_semistable([1,0],[1,0])\n 1\n sage: Q.poincare_semistable([1,0],[1,1])\n 1\n\n sage: K2 = ClusterQuiver(matrix([[0,2],[-2,0]]))\n sage: theta = (1, 0)\n sage: K2.poincare_semistable(theta, [1,0])\n 1\n sage: K2.poincare_semistable(theta, [1,1])\n v^2 + 1\n sage: K2.poincare_semistable(theta, [1,2])\n 1\n sage: K2.poincare_semistable(theta, [1,3])\n 0\n\n sage: K3 = ClusterQuiver(matrix([[0,3],[-3,0]]))\n sage: theta = (1, 0)\n sage: K3.poincare_semistable(theta, (2,3))\n v^12 + v^10 + 3*v^8 + 3*v^6 + 3*v^4 + v^2 + 1\n sage: K3.poincare_semistable(theta, (3,4))(1)\n 68\n\n TESTS::\n\n sage: Q = ClusterQuiver(['A',2])\n sage: Q.poincare_semistable([1,0],[2,2])\n Traceback (most recent call last):\n ...\n ValueError: dimension vector d is not coprime\n\n sage: Q = ClusterQuiver(['A',3])\n sage: Q.poincare_semistable([1,1,0],[2,3,4])\n 0\n\n REFERENCES:\n\n .. [Rei2002] Markus Reineke, *The Harder-Narasimhan system in quantum\n groups and cohomology of quiver moduli*, :arxiv:`math/0204059`\n "
if (gcd([x for x in d if x]) != 1):
raise ValueError('dimension vector d is not coprime')
d = vector(ZZ, d)
theta = vector(theta)
n = self.n()
b_mat = self.b_matrix()
Eu = matrix(ZZ, n, n, (lambda i, j: ((- b_mat[(i, j)]) if (b_mat[(i, j)] > 0) else 0)))
Eu = (1 + Eu)
edges = list(self.digraph().edges(sort=True, labels=False))
mu_d = (theta.dot_product(d) / sum(d))
Li = [(0 * d)]
it = (vector(e) for e in product(*[range((d_i + 1)) for d_i in d]))
Li += [e for e in it if (e.dot_product(theta) > (mu_d * sum(e)))]
Li.append(d)
N = (len(Li) - 1)
q = polygen(QQ, 'v')
def cardinal_RG(d):
cardinal_G = prod((((q ** d_i) - (q ** k)) for d_i in d for k in range(d_i)))
cardinal_R = prod(((q ** ((b_mat[(i, j)] * d[i]) * d[j])) for (i, j) in edges))
return (cardinal_R / cardinal_G)
Reineke_submat = matrix(q.parent().fraction_field(), N, N)
for (i, e) in enumerate(Li[:(- 1)]):
for (j, f) in enumerate(Li[1:]):
if (e == f):
Reineke_submat[(i, j)] = 1
continue
f_e = (f - e)
if all(((x >= 0) for x in f_e)):
power = (((- f_e) * Eu) * e)
Reineke_submat[(i, j)] = ((q ** power) * cardinal_RG(f_e))
poly = (((- 1) ** N) * ((1 - q) * Reineke_submat.det()).numerator())
return poly((q ** 2))
def d_vector_fan(self):
"\n Return the d-vector fan associated with the quiver.\n\n It is the fan whose maximal cones are generated by the\n d-matrices of the clusters.\n\n This is a complete simplicial fan (and even smooth when the\n initial quiver is acyclic). It only makes sense for quivers of\n finite type.\n\n EXAMPLES::\n\n sage: # needs sage.geometry.polyhedron sage.libs.singular\n sage: Fd = ClusterQuiver([[1,2]]).d_vector_fan(); Fd\n Rational polyhedral fan in 2-d lattice N\n sage: Fd.ngenerating_cones()\n 5\n sage: Fd = ClusterQuiver([[1,2],[2,3]]).d_vector_fan(); Fd\n Rational polyhedral fan in 3-d lattice N\n sage: Fd.ngenerating_cones()\n 14\n sage: Fd.is_smooth()\n True\n sage: Fd = ClusterQuiver([[1,2],[2,3],[3,1]]).d_vector_fan(); Fd\n Rational polyhedral fan in 3-d lattice N\n sage: Fd.ngenerating_cones()\n 14\n sage: Fd.is_smooth()\n False\n\n TESTS::\n\n sage: ClusterQuiver(['A',[2,2],1]).d_vector_fan()\n Traceback (most recent call last):\n ...\n ValueError: only makes sense for quivers of finite type\n "
if (not self.is_finite()):
raise ValueError('only makes sense for quivers of finite type')
from .cluster_seed import ClusterSeed
from sage.geometry.fan import Fan
from sage.geometry.cone import Cone
seed = ClusterSeed(self)
return Fan([Cone(s.d_matrix().columns()) for s in seed.mutation_class()])
def g_vector_fan(self):
"\n Return the g-vector fan associated with the quiver.\n\n It is the fan whose maximal cones are generated by the\n g-matrices of the clusters.\n\n This is a complete simplicial fan. It is only supported for\n quivers of finite type.\n\n EXAMPLES::\n\n sage: Fg = ClusterQuiver([[1,2]]).g_vector_fan(); Fg\n Rational polyhedral fan in 2-d lattice N\n sage: Fg.ngenerating_cones()\n 5\n\n sage: Fg = ClusterQuiver([[1,2],[2,3]]).g_vector_fan(); Fg\n Rational polyhedral fan in 3-d lattice N\n sage: Fg.ngenerating_cones()\n 14\n sage: Fg.is_smooth()\n True\n\n sage: Fg = ClusterQuiver([[1,2],[2,3],[3,1]]).g_vector_fan(); Fg\n Rational polyhedral fan in 3-d lattice N\n sage: Fg.ngenerating_cones()\n 14\n sage: Fg.is_smooth()\n True\n\n TESTS::\n\n sage: ClusterQuiver(['A',[2,2],1]).g_vector_fan()\n Traceback (most recent call last):\n ...\n ValueError: only supported for quivers of finite type\n "
from .cluster_seed import ClusterSeed
from sage.geometry.fan import Fan
from sage.geometry.cone import Cone
if (not self.is_finite()):
raise ValueError('only supported for quivers of finite type')
seed = ClusterSeed(self).principal_extension()
return Fan([Cone(s.g_matrix().columns()) for s in seed.mutation_class()])
|
class QuiverMutationTypeFactory(SageObject):
def __call__(self, *args):
'\n For a detailed description, see :meth:`QuiverMutationType`.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.quiver_mutation_type import QuiverMutationTypeFactory\n sage: QuiverMutationTypeFactory()\n QuiverMutationType\n '
if (len(args) == 1):
data = args[0]
else:
data = args
if isinstance(data, QuiverMutationType_Irreducible):
return data
elif isinstance(data, QuiverMutationType_Reducible):
return data
if (isinstance(data, tuple) and data):
pass
elif (isinstance(data, list) and data):
data = tuple(data)
else:
_mutation_type_error(data)
if all(((type(data_component) in [list, tuple, QuiverMutationType_Irreducible]) for data_component in data)):
if (len(data) == 1):
return QuiverMutationType(data[0])
else:
data = tuple((QuiverMutationType(comp) for comp in data))
return QuiverMutationType_Reducible(*data)
if (len(data) == 2):
data = (data[0], data[1], None)
elif (len(data) == 3):
pass
else:
_mutation_type_error(data)
if isinstance(data[2], list):
data = (data[0], data[1], tuple(data[2]))
if isinstance(data[1], list):
data = (data[0], tuple(data[1]), data[2])
if (data == ('D', 2, None)):
return QuiverMutationType(('A', 1, None), ('A', 1, None))
elif (data == ('D', 3, None)):
data = ('A', 3, None)
elif (data == ('C', 2, None)):
data = ('B', 2, None)
elif (data == ('E', 9, None)):
data = ('E', 8, 1)
elif ((data[0] == 'A') and (data[2] == 1) and isinstance(data[1], tuple) and (len(data[1]) == 2) and (min(data[1]) == 0)):
if (max(data[1]) == 0):
pass
elif (max(data[1]) == 1):
data = ('A', 1, None)
elif (max(data[1]) == 2):
return QuiverMutationType(('A', 1, None), ('A', 1, None))
elif (max(data[1]) == 3):
data = ('A', 3, None)
else:
data = ('D', max(data[1]), None)
elif ((data[0] == 'GR') and (data[2] is None) and isinstance(data[1], tuple) and (len(data[1]) == 2) and (data[1][1] > data[1][0])):
if ((min(data[1]) > (max(data[1]) / 2)) and (max(data[1]) != (min(data[1]) + 1))):
data = (data[0], ((max(data[1]) - min(data[1])), max(data[1])), data[2])
if ((min(data[1]) == 2) and (max(data[1]) > 3)):
data = ('A', (max(data[1]) - 3), None)
elif (data[1] == (3, 6)):
data = ('D', 4, None)
elif (data[1] == (3, 7)):
data = ('E', 6, None)
elif (data[1] == (3, 8)):
data = ('E', 8, None)
elif (data[1] == (3, 9)):
data = ('E', 8, [1, 1])
elif (data[1] == (4, 8)):
data = ('E', 7, [1, 1])
elif (data == ('TR', 1, None)):
data = ('A', 1, None)
elif (data == ('TR', 2, None)):
data = ('A', 3, None)
elif (data == ('TR', 3, None)):
data = ('D', 6, None)
elif (data == ('TR', 4, None)):
data = ('E', 8, (1, 1))
elif (data == ('A', 1, 1)):
data = ('A', (1, 1), 1)
elif ((data[0] == 'B') and (data[2] == 1)):
if (data[1] == 2):
data = ('CC', 2, 1)
elif (data[1] > 2):
data = ('BD', data[1], 1)
elif ((data[0] == 'B') and (data[2] == (- 1))):
if (data[1] == 2):
data = ('BB', 2, 1)
elif (data[1] > 2):
data = ('CD', data[1], 1)
elif ((data[0] == 'C') and (data[1] > 1) and (data[2] == 1)):
data = ('CC', data[1], 1)
elif ((data[0] == 'C') and (data[1] > 1) and (data[2] == (- 1))):
data = ('BB', data[1], 1)
elif (data == ('A', 2, 2)):
data = ('BC', 1, 1)
elif ((data[0] == 'A') and (data[1] in ZZ) and (data[1] > 1) and ((data[1] % 2) == 0) and (data[2] == 2)):
data = ('BC', (data[1] // 2), 1)
elif ((data[0] == 'A') and (data[1] in ZZ) and (data[1] > 3) and (data[1] % 2) and (data[2] == 2)):
data = ('CD', ((data[1] + 1) // 2), 1)
elif (data == ('A', 3, 2)):
data = ('BB', 2, 1)
elif ((data[0] == 'D') and (data[1] in ZZ) and (data[1] > 2) and (data[2] == 2)):
data = ('BB', (data[1] - 1), 1)
elif (data == ('E', 6, 2)):
data = ('F', 4, (- 1))
elif (data == ('D', 4, 3)):
data = ('G', 2, (- 1))
elif (data == ('F', 4, (2, 1))):
data = ('F', 4, (1, 2))
elif (data == ('G', 2, (3, 1))):
data = ('G', 2, (1, 3))
elif ((data[0] == 'T') and (data[2] is None)):
data = (data[0], tuple(sorted(data[1])), data[2])
(r, p, q) = data[1]
if (r == 1):
data = ('A', ((p + q) - 1), None)
elif (r == p == 2):
data = ('D', (q + 2), None)
elif ((r == 2) and (p == 3)):
if (q in (3, 4, 5)):
data = ('E', (q + 3), None)
elif (q == 6):
data = ('E', 8, 1)
else:
data = ('E', (q + 3), None)
elif ((r == 2) and (p == q == 4)):
data = ('E', 7, 1)
elif (r == p == q == 3):
data = ('E', 6, 1)
elif ((data[0] == 'R2') and (data[2] is None) and all((((data[1][i] in ZZ) and (data[1][i] > 0)) for i in [0, 1]))):
data = (data[0], tuple(sorted(data[1])), data[2])
if (data[1] == (1, 1)):
data = ('A', 2, None)
elif (data[1] == (1, 2)):
data = ('B', 2, None)
elif (data[1] == (1, 3)):
data = ('G', 2, None)
elif (data[1] == (1, 4)):
data = ('BC', 1, 1)
elif (data[1] == (2, 2)):
data = ('A', (1, 1), 1)
(letter, rank, twist) = data
if (not isinstance(letter, str)):
_mutation_type_error(data)
if isinstance(rank, list):
rank = tuple(rank)
if isinstance(twist, list):
twist = tuple(twist)
return QuiverMutationType_Irreducible(letter, rank, twist)
def _repr_(self) -> str:
'\n Return the string representation of ``self``.\n\n EXAMPLES::\n\n sage: QuiverMutationType # indirect doctest\n QuiverMutationType\n '
return 'QuiverMutationType'
def samples(self, finite=None, affine=None, elliptic=None, mutation_finite=None):
"\n Return a sample of the available quiver mutations types.\n\n INPUT:\n\n - ``finite``\n\n - ``affine``\n\n - ``elliptic``\n\n - ``mutation_finite``\n\n All four input keywords default values are ``None``. If\n set to ``True`` or ``False``, only these samples are returned.\n\n EXAMPLES::\n\n sage: QuiverMutationType.samples()\n [['A', 1], ['A', 5], ['B', 2], ['B', 5], ['C', 3],\n ['C', 5], [ ['A', 1], ['A', 1] ], ['D', 5], ['E', 6],\n ['E', 7], ['E', 8], ['F', 4], ['G', 2],\n ['A', [1, 1], 1], ['A', [4, 5], 1], ['D', 4, 1],\n ['BB', 5, 1], ['E', 6, [1, 1]], ['E', 7, [1, 1]],\n ['R2', [1, 5]], ['R2', [3, 5]], ['E', 10], ['BE', 5],\n ['GR', [3, 10]], ['T', [3, 3, 4]]]\n\n sage: QuiverMutationType.samples(finite=True)\n [['A', 1], ['A', 5], ['B', 2], ['B', 5], ['C', 3],\n ['C', 5], [ ['A', 1], ['A', 1] ], ['D', 5], ['E', 6],\n ['E', 7], ['E', 8], ['F', 4], ['G', 2]]\n\n sage: QuiverMutationType.samples(affine=True)\n [['A', [1, 1], 1], ['A', [4, 5], 1], ['D', 4, 1], ['BB', 5, 1]]\n\n sage: QuiverMutationType.samples(elliptic=True)\n [['E', 6, [1, 1]], ['E', 7, [1, 1]]]\n\n sage: QuiverMutationType.samples(mutation_finite=False)\n [['R2', [1, 5]], ['R2', [3, 5]], ['E', 10], ['BE', 5],\n ['GR', [3, 10]], ['T', [3, 3, 4]]]\n "
result = self._samples()
if (finite is not None):
result = [t for t in result if (t.is_finite() == finite)]
if (affine is not None):
result = [t for t in result if (t.is_affine() == affine)]
if (elliptic is not None):
result = [t for t in result if (t.is_elliptic() == elliptic)]
if (mutation_finite is not None):
result = [t for t in result if (t.is_mutation_finite() == mutation_finite)]
return result
@cached_method
def _samples(self):
'\n Return a list of sample of available Cartan types.\n\n EXAMPLES::\n\n sage: X = QuiverMutationType._samples()\n '
finite_types = [QuiverMutationType(t) for t in [['A', 1], ['A', 5], ['B', 2], ['B', 5], ['C', 3], ['C', 5], ['D', 2], ['D', 5], ['E', 6], ['E', 7], ['E', 8], ['F', 4], ['G', 2]]]
affine_types = [QuiverMutationType(t) for t in [['A', [1, 1], 1], ['A', [4, 5], 1], ['D', 4, 1], ['BB', 5, 1]]]
elliptic_types = [QuiverMutationType(t) for t in [['E', 6, [1, 1]], ['E', 7, [1, 1]]]]
mutation_finite_types = [QuiverMutationType(t) for t in [['R2', (1, 5)], ['R2', (3, 5)]]]
mutation_infinite_types = [QuiverMutationType(t) for t in [['E', 10], ['BE', 5], ['GR', (3, 10)], ['T', (3, 3, 4)]]]
return ((((finite_types + affine_types) + elliptic_types) + mutation_finite_types) + mutation_infinite_types)
|
class QuiverMutationType_abstract(UniqueRepresentation, SageObject):
"\n EXAMPLES::\n\n sage: mut_type1 = QuiverMutationType('A',5)\n sage: mut_type2 = QuiverMutationType('A',5)\n sage: mut_type3 = QuiverMutationType('A',6)\n sage: mut_type1 == mut_type2\n True\n sage: mut_type1 == mut_type3\n False\n "
def _repr_(self):
"\n Return the string representation of ``self``.\n\n EXAMPLES::\n\n sage: QuiverMutationType(['A', 2]) # indirect doctest\n ['A', 2]\n "
return self._description
def plot(self, circular=False, directed=True):
"\n Return the plot of the underlying graph or digraph of ``self``.\n\n INPUT:\n\n - ``circular`` -- (default: ``False``) if ``True``, the\n circular plot is chosen, otherwise >>spring<< is used.\n\n - ``directed`` -- (default: ``True``) if ``True``, the\n directed version is shown, otherwise the undirected.\n\n EXAMPLES::\n\n sage: QMT = QuiverMutationType(['A',5])\n sage: pl = QMT.plot() # needs sage.plot sage.symbolic\n sage: pl = QMT.plot(circular=True) # needs sage.plot sage.symbolic\n "
return self.standard_quiver().plot(circular=circular, directed=directed)
def show(self, circular=False, directed=True):
"\n Show the plot of the underlying digraph of ``self``.\n\n INPUT:\n\n - ``circular`` -- (default:``False``) if ``True``, the\n circular plot is chosen, otherwise >>spring<< is used.\n\n - ``directed`` -- (default: ``True``) if ``True``, the\n directed version is shown, otherwise the undirected.\n\n TESTS::\n\n sage: QMT = QuiverMutationType(['A',5])\n sage: QMT.show() # long time # needs sage.plot sage.symbolic\n "
self.plot(circular=circular, directed=directed).show()
def letter(self):
"\n Return the classification letter of ``self``.\n\n EXAMPLES::\n\n sage: mut_type = QuiverMutationType( ['A',5] ); mut_type\n ['A', 5]\n sage: mut_type.letter()\n 'A'\n\n sage: mut_type = QuiverMutationType( ['BC',5, 1] ); mut_type\n ['BC', 5, 1]\n sage: mut_type.letter()\n 'BC'\n\n sage: mut_type = QuiverMutationType(['A',3],['B',3]); mut_type\n [ ['A', 3], ['B', 3] ]\n sage: mut_type.letter()\n 'A x B'\n\n sage: mut_type = QuiverMutationType(['A',3],['B',3],['X',6]); mut_type\n [ ['A', 3], ['B', 3], ['X', 6] ]\n sage: mut_type.letter()\n 'A x B x X'\n "
return self._letter
def rank(self):
"\n Return the rank in the standard quiver of ``self``.\n\n The rank is the number of vertices.\n\n EXAMPLES::\n\n sage: mut_type = QuiverMutationType( ['A',5] ); mut_type\n ['A', 5]\n sage: mut_type.rank()\n 5\n\n sage: mut_type = QuiverMutationType( ['A',[4,5], 1] ); mut_type\n ['A', [4, 5], 1]\n sage: mut_type.rank()\n 9\n\n sage: mut_type = QuiverMutationType( ['BC',5, 1] ); mut_type\n ['BC', 5, 1]\n sage: mut_type.rank()\n 6\n\n sage: mut_type = QuiverMutationType(['A',3],['B',3]); mut_type\n [ ['A', 3], ['B', 3] ]\n sage: mut_type.rank()\n 6\n\n sage: mut_type = QuiverMutationType(['A',3],['B',3],['X',6]); mut_type\n [ ['A', 3], ['B', 3], ['X', 6] ]\n sage: mut_type.rank()\n 12\n "
return self._rank
@cached_method
def b_matrix(self):
"\n Return the B-matrix of the standard quiver of ``self``.\n\n The conventions for B-matrices agree with Fomin-Zelevinsky (up\n to a reordering of the simple roots).\n\n EXAMPLES::\n\n sage: mut_type = QuiverMutationType(['A',5]); mut_type\n ['A', 5]\n sage: mut_type.b_matrix() # needs sage.modules\n [ 0 1 0 0 0]\n [-1 0 -1 0 0]\n [ 0 1 0 1 0]\n [ 0 0 -1 0 -1]\n [ 0 0 0 1 0]\n\n sage: mut_type = QuiverMutationType(['A',3],['B',3]); mut_type\n [ ['A', 3], ['B', 3] ]\n sage: mut_type.b_matrix() # needs sage.modules\n [ 0 1 0 0 0 0]\n [-1 0 -1 0 0 0]\n [ 0 1 0 0 0 0]\n [ 0 0 0 0 1 0]\n [ 0 0 0 -1 0 -1]\n [ 0 0 0 0 2 0]\n "
return _edge_list_to_matrix(self._digraph.edges(sort=True), list(range(self._rank)), [])
@cached_method
def standard_quiver(self):
"\n Return the standard quiver of ``self``.\n\n EXAMPLES::\n\n sage: mut_type = QuiverMutationType( ['A',5] ); mut_type\n ['A', 5]\n sage: mut_type.standard_quiver() # needs sage.modules\n Quiver on 5 vertices of type ['A', 5]\n\n sage: mut_type = QuiverMutationType( ['A',[5,3], 1] ); mut_type\n ['A', [3, 5], 1]\n sage: mut_type.standard_quiver() # needs sage.modules\n Quiver on 8 vertices of type ['A', [3, 5], 1]\n\n sage: mut_type = QuiverMutationType(['A',3],['B',3]); mut_type\n [ ['A', 3], ['B', 3] ]\n sage: mut_type.standard_quiver() # needs sage.modules\n Quiver on 6 vertices of type [ ['A', 3], ['B', 3] ]\n\n sage: mut_type = QuiverMutationType(['A',3],['B',3],['X',6]); mut_type\n [ ['A', 3], ['B', 3], ['X', 6] ]\n sage: mut_type.standard_quiver() # needs sage.modules\n Quiver on 12 vertices of type [ ['A', 3], ['B', 3], ['X', 6] ]\n "
from .quiver import ClusterQuiver
Q = ClusterQuiver(self._digraph)
Q._mutation_type = self
return Q
@cached_method
def cartan_matrix(self):
"\n Return the Cartan matrix of ``self``.\n\n Note that (up to a reordering of the simple roots) the convention for\n the definition of Cartan matrix, used here and elsewhere in Sage,\n agrees with the conventions of Kac, Fulton-Harris, and\n Fomin-Zelevinsky, but disagrees with the convention of Bourbaki.\n The `(i,j)` entry is `2(\\alpha_i,\\alpha_j)/(\\alpha_i,\\alpha_i)`.\n\n EXAMPLES::\n\n sage: mut_type = QuiverMutationType(['A',5]); mut_type\n ['A', 5]\n sage: mut_type.cartan_matrix() # needs sage.modules\n [ 2 -1 0 0 0]\n [-1 2 -1 0 0]\n [ 0 -1 2 -1 0]\n [ 0 0 -1 2 -1]\n [ 0 0 0 -1 2]\n\n sage: mut_type = QuiverMutationType(['A',3],['B',3]); mut_type\n [ ['A', 3], ['B', 3] ]\n sage: mut_type.cartan_matrix() # needs sage.modules\n [ 2 -1 0 0 0 0]\n [-1 2 -1 0 0 0]\n [ 0 -1 2 0 0 0]\n [ 0 0 0 2 -1 0]\n [ 0 0 0 -1 2 -1]\n [ 0 0 0 0 -2 2]\n "
cmat = copy(self.b_matrix())
for (i, j) in cmat.nonzero_positions():
a = cmat[(i, j)]
if (a > 0):
cmat[(i, j)] = (- a)
for i in range(self._rank):
cmat[(i, i)] = 2
return cmat
def is_irreducible(self):
"\n Return ``True`` if ``self`` is irreducible.\n\n EXAMPLES::\n\n sage: mt = QuiverMutationType(['A', 2])\n sage: mt.is_irreducible()\n True\n "
return self._info['irreducible']
def is_mutation_finite(self):
"\n Return ``True`` if ``self`` is of finite mutation type.\n\n This means that its mutation class has only finitely many\n different B-matrices.\n\n EXAMPLES::\n\n sage: mt = QuiverMutationType(['D',5, 1])\n sage: mt.is_mutation_finite()\n True\n "
return self._info['mutation_finite']
def is_simply_laced(self):
"\n Return ``True`` if ``self`` is simply laced.\n\n This means that the only arrows that appear in the quiver of\n ``self`` are single unlabelled arrows.\n\n EXAMPLES::\n\n sage: mt = QuiverMutationType(['A', 2])\n sage: mt.is_simply_laced()\n True\n\n sage: mt = QuiverMutationType(['B', 2])\n sage: mt.is_simply_laced()\n False\n\n sage: mt = QuiverMutationType(['A',(1, 1), 1])\n sage: mt.is_simply_laced()\n False\n "
return self._info['simply_laced']
def is_skew_symmetric(self):
"\n Return ``True`` if the B-matrix of ``self`` is skew-symmetric.\n\n EXAMPLES::\n\n sage: mt = QuiverMutationType(['A', 2])\n sage: mt.is_skew_symmetric()\n True\n\n sage: mt = QuiverMutationType(['B', 2])\n sage: mt.is_skew_symmetric()\n False\n\n sage: mt = QuiverMutationType(['A',(1, 1), 1])\n sage: mt.is_skew_symmetric()\n True\n "
return self._info['skew_symmetric']
def is_finite(self):
"\n Return ``True`` if ``self`` is of finite type.\n\n This means that the cluster algebra associated to ``self`` has\n only a finite number of cluster variables.\n\n EXAMPLES::\n\n sage: mt = QuiverMutationType(['A', 2])\n sage: mt.is_finite()\n True\n\n sage: mt = QuiverMutationType(['A',[4, 2], 1])\n sage: mt.is_finite()\n False\n "
return self._info['finite']
def is_affine(self):
"\n Return ``True`` if ``self`` is of affine type.\n\n EXAMPLES::\n\n sage: mt = QuiverMutationType(['A', 2])\n sage: mt.is_affine()\n False\n\n sage: mt = QuiverMutationType(['A',[4, 2], 1])\n sage: mt.is_affine()\n True\n "
if self.is_irreducible():
return self._info['affine']
else:
return False
def is_elliptic(self):
"\n Return ``True`` if ``self`` is of elliptic type.\n\n EXAMPLES::\n\n sage: mt = QuiverMutationType(['A', 2])\n sage: mt.is_elliptic()\n False\n\n sage: mt = QuiverMutationType(['E',6,[1, 1]])\n sage: mt.is_elliptic()\n True\n "
if self.is_irreducible():
return self._info['elliptic']
else:
return False
def properties(self):
"\n Print a scheme of all properties of ``self``.\n\n Most properties have natural definitions for either irreducible or\n reducible types. ``affine`` and ``elliptic`` are only defined for\n irreducible types.\n\n EXAMPLES::\n\n sage: mut_type = QuiverMutationType(['A',3]); mut_type\n ['A', 3]\n sage: mut_type.properties()\n ['A', 3] has rank 3 and the following properties:\n - irreducible: True\n - mutation finite: True\n - simply-laced: True\n - skew-symmetric: True\n - finite: True\n - affine: False\n - elliptic: False\n\n sage: mut_type = QuiverMutationType(['B',3]); mut_type\n ['B', 3]\n sage: mut_type.properties()\n ['B', 3] has rank 3 and the following properties:\n - irreducible: True\n - mutation finite: True\n - simply-laced: False\n - skew-symmetric: False\n - finite: True\n - affine: False\n - elliptic: False\n\n sage: mut_type = QuiverMutationType(['B',3, 1]); mut_type\n ['BD', 3, 1]\n sage: mut_type.properties()\n ['BD', 3, 1] has rank 4 and the following properties:\n - irreducible: True\n - mutation finite: True\n - simply-laced: False\n - skew-symmetric: False\n - finite: False\n - affine: True\n - elliptic: False\n\n sage: mut_type = QuiverMutationType(['E',6,[1, 1]]); mut_type\n ['E', 6, [1, 1]]\n sage: mut_type.properties()\n ['E', 6, [1, 1]] has rank 8 and the following properties:\n - irreducible: True\n - mutation finite: True\n - simply-laced: False\n - skew-symmetric: True\n - finite: False\n - affine: False\n - elliptic: True\n\n sage: mut_type = QuiverMutationType(['A',3],['B',3]); mut_type\n [ ['A', 3], ['B', 3] ]\n sage: mut_type.properties()\n [ ['A', 3], ['B', 3] ] has rank 6 and the following properties:\n - irreducible: False\n - mutation finite: True\n - simply-laced: False\n - skew-symmetric: False\n - finite: True\n\n sage: mut_type = QuiverMutationType('GR',[4,9]); mut_type\n ['GR', [4, 9]]\n sage: mut_type.properties()\n ['GR', [4, 9]] has rank 12 and the following properties:\n - irreducible: True\n - mutation finite: False\n - simply-laced: True\n - skew-symmetric: True\n - finite: False\n - affine: False\n - elliptic: False\n "
txt = '{} has rank {} and the following properties:'
print(txt.format(self, self.rank()))
s = '\t- {} {}'
print(s.format('irreducible: ', self.is_irreducible()))
print(s.format('mutation finite: ', self.is_mutation_finite()))
print(s.format('simply-laced: ', self.is_simply_laced()))
print(s.format('skew-symmetric: ', self.is_skew_symmetric()))
print(s.format('finite: ', self.is_finite()))
if self.is_irreducible():
print(s.format('affine: ', self.is_affine()))
print(s.format('elliptic: ', self.is_elliptic()))
|
class QuiverMutationType_Irreducible(QuiverMutationType_abstract):
'\n The mutation type for a cluster algebra or a quiver. Should not be\n called directly, but through :class:`QuiverMutationType`.\n '
def __init__(self, letter, rank, twist=None):
"\n Should not be called directly but through QuiverMutationType.\n\n INPUT:\n\n - ``letter`` -- the letter of the mutation type\n - ``rank`` -- the rank of the mutation type\n - ``twist`` -- the twist of the mutation type\n\n EXAMPLES::\n\n sage: QuiverMutationType('A',5)\n ['A', 5]\n\n sage: QuiverMutationType('A',[4,5], 1)\n ['A', [4, 5], 1]\n\n sage: QuiverMutationType('BB',5, 1)\n ['BB', 5, 1]\n\n sage: QuiverMutationType('X',6)\n ['X', 6]\n "
self._rank = None
self._bi_rank = None
self._graph = Graph()
self._digraph = DiGraph()
self._info = {}
self._info['irreducible'] = True
self._info['mutation_finite'] = False
self._info['simply_laced'] = False
self._info['skew_symmetric'] = False
self._info['finite'] = False
self._info['affine'] = False
self._info['elliptic'] = False
self._info['irreducible_components'] = False
if isinstance(rank, tuple):
rank = list(rank)
if isinstance(twist, tuple):
twist = list(twist)
self._letter = letter
self._twist = twist
data = [letter, rank, twist]
if (letter == 'A'):
if ((twist is None) and (rank in ZZ) and (rank > 0)):
self._rank = rank
self._info['mutation_finite'] = True
self._info['simply_laced'] = True
self._info['skew_symmetric'] = True
self._info['finite'] = True
elif ((twist == 1) and isinstance(rank, list) and (len(rank) == 2) and all((((ri in ZZ) and (ri >= 0)) for ri in rank)) and (rank != [0, 0])):
if isinstance(rank, tuple):
rank = list(rank)
data[1] = rank
rank = sorted(rank)
self._bi_rank = rank
self._rank = sum(self._bi_rank)
self._info['mutation_finite'] = True
if (self._rank > 2):
self._info['simply_laced'] = True
self._info['skew_symmetric'] = True
if (rank[0] > 0):
self._info['affine'] = True
elif (rank[0] == 0):
self._info['finite'] = True
else:
_mutation_type_error(data)
if (((twist is None) and (self._rank == 1)) or ((twist == 1) and (self._rank == 1))):
self._graph.add_vertex(0)
elif ((twist == 1) and (self._bi_rank[0] == 1) and (self._bi_rank[1] == 1)):
self._graph.add_edge(0, 1, 2)
else:
for i in range((self._rank - 1)):
self._graph.add_edge(i, (i + 1), 1)
if (twist == 1):
self._digraph.add_edge((self._rank - 1), 0, 1)
for i in range((self._rank - 1)):
if ((i < (2 * self._bi_rank[0])) and ((i % 2) == 0)):
self._digraph.add_edge((i + 1), i, 1)
else:
self._digraph.add_edge(i, (i + 1), 1)
elif (letter == 'B'):
if ((twist is None) and (rank in ZZ) and (rank > 1)):
self._rank = rank
self._info['mutation_finite'] = True
self._info['finite'] = True
else:
_mutation_type_error(data)
for i in range((rank - 2)):
self._graph.add_edge(i, (i + 1), 1)
if ((rank % 2) == 0):
self._graph.add_edge((rank - 2), (rank - 1), (1, (- 2)))
else:
self._graph.add_edge((rank - 2), (rank - 1), (2, (- 1)))
elif (letter == 'C'):
if ((twist is None) and (rank in ZZ) and (rank > 1)):
self._rank = rank
self._info['mutation_finite'] = True
self._info['finite'] = True
else:
_mutation_type_error(data)
for i in range((rank - 2)):
self._graph.add_edge(i, (i + 1), 1)
if ((rank % 2) == 0):
self._graph.add_edge((rank - 2), (rank - 1), (2, (- 1)))
else:
self._graph.add_edge((rank - 2), (rank - 1), (1, (- 2)))
elif (letter == 'BB'):
if ((twist == 1) and (rank in ZZ) and (rank > 1)):
self._rank = (rank + 1)
self._info['mutation_finite'] = True
self._info['affine'] = True
else:
_mutation_type_error(data)
for i in range((rank - 2)):
self._graph.add_edge(i, (i + 1), 1)
if ((rank % 2) == 0):
self._graph.add_edge((rank - 2), (rank - 1), (1, (- 2)))
else:
self._graph.add_edge((rank - 2), (rank - 1), (2, (- 1)))
self._graph.add_edge(rank, 0, (1, (- 2)))
elif (letter == 'CC'):
if ((twist == 1) and (rank in ZZ) and (rank > 1)):
self._rank = (rank + 1)
self._info['mutation_finite'] = True
self._info['affine'] = True
else:
_mutation_type_error(data)
for i in range((rank - 2)):
self._graph.add_edge(i, (i + 1), 1)
if ((rank % 2) == 0):
self._graph.add_edge((rank - 2), (rank - 1), (2, (- 1)))
else:
self._graph.add_edge((rank - 2), (rank - 1), (1, (- 2)))
self._graph.add_edge(rank, 0, (2, (- 1)))
elif (letter == 'BC'):
if ((twist == 1) and (rank in ZZ) and (rank >= 1)):
self._rank = (rank + 1)
self._info['mutation_finite'] = True
self._info['affine'] = True
else:
_mutation_type_error(data)
if (rank == 1):
self._graph.add_edge(0, 1, (1, (- 4)))
else:
for i in range((rank - 2)):
self._graph.add_edge(i, (i + 1), 1)
if ((rank % 2) == 0):
self._graph.add_edge((rank - 2), (rank - 1), (2, (- 1)))
else:
self._graph.add_edge((rank - 2), (rank - 1), (1, (- 2)))
if (twist == 1):
self._graph.add_edge(rank, 0, (1, (- 2)))
elif (letter == 'BD'):
if ((twist == 1) and (rank in ZZ) and (rank > 2)):
self._rank = (rank + 1)
self._info['mutation_finite'] = True
self._info['affine'] = True
else:
_mutation_type_error(data)
for i in range((rank - 2)):
self._graph.add_edge(i, (i + 1), 1)
if ((rank % 2) == 0):
self._graph.add_edge((rank - 2), (rank - 1), (1, (- 2)))
else:
self._graph.add_edge((rank - 2), (rank - 1), (2, (- 1)))
if (twist == 1):
self._graph.add_edge(rank, 1, 1)
elif (letter == 'CD'):
if ((twist == 1) and (rank in ZZ) and (rank > 2)):
self._rank = (rank + 1)
self._info['mutation_finite'] = True
self._info['affine'] = True
else:
_mutation_type_error(data)
for i in range((rank - 2)):
self._graph.add_edge(i, (i + 1), 1)
if ((rank % 2) == 0):
self._graph.add_edge((rank - 2), (rank - 1), (2, (- 1)))
else:
self._graph.add_edge((rank - 2), (rank - 1), (1, (- 2)))
if (twist == 1):
self._graph.add_edge(rank, 1, 1)
elif (letter == 'D'):
if ((rank in ZZ) and (rank > 3) and (twist is None)):
self._rank = rank
self._info['mutation_finite'] = True
self._info['simply_laced'] = True
self._info['skew_symmetric'] = True
self._info['finite'] = True
elif ((twist == 1) and (rank in ZZ) and (rank > 3)):
self._rank = (rank + 1)
self._info['mutation_finite'] = True
self._info['simply_laced'] = True
self._info['skew_symmetric'] = True
self._info['affine'] = True
else:
_mutation_type_error(data)
for i in range((rank - 2)):
self._graph.add_edge(i, (i + 1), 1)
self._graph.add_edge((rank - 3), (rank - 1), 1)
if (twist is not None):
self._graph.add_edge(rank, 1, 1)
elif (letter == 'E'):
if ((rank in [6, 7, 8]) and (twist is None)):
self._rank = rank
self._info['mutation_finite'] = True
self._info['simply_laced'] = True
self._info['skew_symmetric'] = True
self._info['finite'] = True
if (rank == 6):
self._graph.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (2, 5)])
elif (rank == 7):
self._graph.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (2, 6)])
elif (rank == 8):
self._graph.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (2, 7)])
elif ((rank in [6, 7, 8]) and (twist == 1)):
self._rank = (rank + 1)
self._info['mutation_finite'] = True
self._info['simply_laced'] = True
self._info['skew_symmetric'] = True
self._info['affine'] = True
if (rank == 6):
self._graph.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (2, 5), (5, 6)])
elif (rank == 7):
self._graph.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (3, 7)])
elif (rank == 8):
self._graph.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (2, 8)])
elif ((rank in [6, 7, 8]) and (twist == [1, 1])):
self._rank = (rank + 2)
self._info['mutation_finite'] = True
self._info['skew_symmetric'] = True
self._info['elliptic'] = True
if (rank == 6):
self._digraph.add_edges([(0, 1, 1), (1, 2, 1), (3, 2, 1), (3, 4, 1), (5, 6, 1), (6, 7, 1), (5, 1, 1), (2, 5, 2), (5, 3, 1), (6, 2, 1)])
elif (rank == 7):
self._digraph.add_edges([(1, 0, 1), (1, 2, 1), (2, 3, 1), (4, 3, 1), (4, 5, 1), (6, 5, 1), (7, 8, 1), (3, 7, 2), (7, 2, 1), (7, 4, 1), (8, 3, 1)])
elif (rank == 8):
self._digraph.add_edges([(0, 1, 1), (1, 9, 1), (3, 9, 1), (3, 4, 1), (2, 8, 1), (2, 1, 1), (9, 2, 2), (2, 3, 1), (8, 9, 1), (5, 4, 1), (5, 6, 1), (7, 6, 1)])
elif ((rank > 9) and (twist is None)):
self._info['simply_laced'] = True
self._info['skew_symmetric'] = True
self._rank = rank
for i in range((rank - 2)):
self._graph.add_edge(i, (i + 1), 1)
self._graph.add_edge(2, (rank - 1))
else:
_mutation_type_error(data)
elif (letter == 'AE'):
if (isinstance(rank, list) and (len(rank) == 2) and all((((rank[i] in ZZ) and (rank[i] > 0)) for i in [0, 1])) and (twist is None)):
if isinstance(rank, tuple):
rank = list(rank)
data[1] = rank
rank = sorted(rank)
self._bi_rank = rank
self._rank = (sum(self._bi_rank) + 1)
if (self._rank > 3):
self._info['simply_laced'] = True
self._info['skew_symmetric'] = True
if (self._bi_rank == [1, 1]):
self._graph.add_edges([(0, 1, 2), (1, 2, None)])
else:
self._digraph.add_edge((self._rank - 2), 0)
for i in range((self._rank - 2)):
if ((i < (2 * self._bi_rank[0])) and ((i % 2) == 0)):
self._digraph.add_edge((i + 1), i)
else:
self._digraph.add_edge(i, (i + 1))
self._digraph.add_edge((self._rank - 2), (self._rank - 1))
else:
_mutation_type_error(data)
elif (letter == 'BE'):
if ((rank > 4) and (twist is None)):
self._rank = rank
for i in range((rank - 3)):
self._graph.add_edge(i, (i + 1))
self._graph.add_edge(2, (rank - 1))
if ((rank % 2) == 0):
self._graph.add_edge((rank - 3), (rank - 2), (2, (- 1)))
else:
self._graph.add_edge((rank - 3), (rank - 2), (1, (- 2)))
else:
_mutation_type_error(data)
elif (letter == 'CE'):
if ((rank > 4) and (twist is None)):
self._rank = rank
for i in range((rank - 3)):
self._graph.add_edge(i, (i + 1))
self._graph.add_edge(2, (rank - 1))
if ((rank % 2) == 0):
self._graph.add_edge((rank - 3), (rank - 2), (1, (- 2)))
else:
self._graph.add_edge((rank - 3), (rank - 2), (2, (- 1)))
else:
_mutation_type_error(data)
elif (letter == 'DE'):
if ((rank > 5) and (twist is None)):
self._rank = rank
self._info['simply_laced'] = True
self._info['skew_symmetric'] = True
for i in range((rank - 3)):
self._graph.add_edge(i, (i + 1))
self._graph.add_edge(2, (rank - 2))
self._graph.add_edge((rank - 4), (rank - 1))
else:
_mutation_type_error(data)
elif (letter == 'F'):
if ((rank == 4) and (twist is None)):
self._rank = rank
self._info['mutation_finite'] = True
self._info['finite'] = True
self._graph.add_edges([(0, 1, None), (1, 2, (2, (- 1))), (2, 3, None)])
elif ((rank == 4) and (twist == 1)):
self._rank = (rank + 1)
self._info['mutation_finite'] = True
self._info['affine'] = True
self._graph.add_edges([(0, 1, None), (1, 2, None), (2, 3, (1, (- 2))), (3, 4, None)])
elif ((rank == 4) and (twist == (- 1))):
self._rank = (rank + 1)
self._info['mutation_finite'] = True
self._info['affine'] = True
self._graph.add_edges([(0, 1, None), (1, 2, None), (2, 3, (2, (- 1))), (3, 4, None)])
elif ((rank == 4) and (twist == [1, 2])):
self._rank = (rank + 2)
self._info['mutation_finite'] = True
self._info['elliptic'] = True
self._digraph.add_edges([(0, 1, None), (1, 2, None), (2, 3, (2, (- 1))), (4, 2, (1, (- 2))), (3, 4, 2), (4, 5, None), (5, 3, None)])
elif ((rank == 4) and (twist == [2, 1])):
self._rank = (rank + 2)
self._info['mutation_finite'] = True
self._info['elliptic'] = True
self._digraph.add_edges([(0, 1, None), (1, 2, None), (2, 3, (1, (- 2))), (4, 2, (2, (- 1))), (3, 4, 2), (4, 5, None), (5, 3, None)])
elif ((rank == 4) and (twist == [2, 2])):
self._rank = (rank + 2)
self._info['mutation_finite'] = True
self._info['elliptic'] = True
self._digraph.add_edges([(0, 1, None), (1, 2, None), (3, 1, None), (2, 3, 2), (4, 2, (2, (- 1))), (3, 4, (1, (- 2))), (5, 4, None)])
elif ((rank == 4) and (twist == [1, 1])):
self._rank = (rank + 2)
self._info['mutation_finite'] = True
self._info['elliptic'] = True
self._digraph.add_edges([(0, 1, None), (1, 2, None), (3, 1, None), (2, 3, 2), (4, 2, (1, (- 2))), (3, 4, (2, (- 1))), (5, 4, None)])
else:
_mutation_type_error(data)
elif (letter == 'G'):
if ((rank == 2) and (twist is None)):
self._rank = rank
self._info['mutation_finite'] = True
self._info['finite'] = True
self._graph.add_edges([(0, 1, (1, (- 3)))])
elif ((rank == 2) and (twist == (- 1))):
self._rank = (rank + 1)
self._info['mutation_finite'] = True
self._info['affine'] = True
self._graph.add_edges([(0, 1, None), (1, 2, (1, (- 3)))])
elif ((rank == 2) and (twist == 1)):
self._rank = (rank + 1)
self._info['mutation_finite'] = True
self._info['affine'] = True
self._graph.add_edges([(0, 1, None), (1, 2, (3, (- 1)))])
elif ((rank == 2) and (twist == [1, 3])):
self._rank = (rank + 2)
self._info['mutation_finite'] = True
self._info['elliptic'] = True
self._digraph.add_edges([(0, 1, None), (1, 2, (3, (- 1))), (3, 1, (1, (- 3))), (2, 3, 2)])
elif ((rank == 2) and (twist == [3, 1])):
self._rank = (rank + 2)
self._info['mutation_finite'] = True
self._info['elliptic'] = True
self._digraph.add_edges([(0, 1, None), (1, 2, (1, (- 3))), (3, 1, (3, (- 1))), (2, 3, 2)])
elif ((rank == 2) and (twist == [3, 3])):
self._rank = (rank + 2)
self._info['mutation_finite'] = True
self._info['elliptic'] = True
self._digraph.add_edges([(1, 0, None), (0, 2, 2), (3, 0, (3, (- 1))), (2, 1, None), (2, 3, (1, (- 3)))])
elif ((rank == 2) and (twist == [1, 1])):
self._rank = (rank + 2)
self._info['mutation_finite'] = True
self._info['elliptic'] = True
self._digraph.add_edges([(1, 0, None), (0, 2, 2), (3, 0, (1, (- 3))), (2, 1, None), (2, 3, (3, (- 1)))])
else:
_mutation_type_error(data)
elif (letter == 'GR'):
if ((twist is None) and isinstance(rank, list) and (len(rank) == 2) and all((((rank[i] in ZZ) and (rank[i] > 0)) for i in [0, 1])) and ((rank[1] - 1) > rank[0] > 1)):
gr_rank = ((rank[0] - 1), ((rank[1] - rank[0]) - 1))
self._rank = prod(gr_rank)
self._info['simply_laced'] = True
self._info['skew_symmetric'] = True
(a, b) = gr_rank
for i in range(a):
for j in range(b):
if (i < (a - 1)):
if (((i + j) % 2) == 0):
self._digraph.add_edge(((i * b) + j), (((i + 1) * b) + j))
else:
self._digraph.add_edge((((i + 1) * b) + j), ((i * b) + j))
if (j < (b - 1)):
if (((i + j) % 2) == 0):
self._digraph.add_edge((((i * b) + j) + 1), ((i * b) + j))
else:
self._digraph.add_edge(((i * b) + j), (((i * b) + j) + 1))
else:
_mutation_type_error(data)
elif (letter == 'R2'):
if ((twist is None) and isinstance(rank, list) and (len(rank) == 2) and all((((rank[i] in ZZ) and (rank[i] > 0)) for i in [0, 1]))):
rank = sorted(rank)
(b, c) = rank
self._rank = 2
if (b == c):
self._info['skew_symmetric'] = True
self._graph.add_edge(0, 1, (b, (- c)))
else:
_mutation_type_error(data)
elif (letter == 'T'):
if ((twist is None) and isinstance(rank, list) and (len(rank) == 3) and all((((rank[i] in ZZ) and (rank[i] > 0)) for i in [0, 1, 2]))):
if isinstance(rank, tuple):
rank = list(rank)
data[1] = rank
rank = sorted(rank)
self._rank = (sum(rank) - 2)
self._info['simply_laced'] = True
self._info['skew_symmetric'] = True
(r, p, q) = rank
for i in range((q - 1)):
if (i == 0):
self._graph.add_edge(0, 1)
self._graph.add_edge(0, r)
self._graph.add_edge(0, ((r + p) - 1))
else:
if (i < (r - 1)):
self._graph.add_edge(i, (i + 1))
if (i < (p - 1)):
self._graph.add_edge(((i + r) - 1), (i + r))
self._graph.add_edge((((i + r) + p) - 2), (((i + r) + p) - 1))
else:
_mutation_type_error(data)
elif (letter == 'TR'):
if ((twist is None) and (rank == 1)):
self._graph.add_vertex(0)
elif ((twist is None) and (rank > 1)):
self._rank = ((rank * (rank + 1)) // 2)
self._info['simply_laced'] = True
self._info['skew_symmetric'] = True
level = 0
while (level < rank):
nr = ((rank * level) - sum(range(level)))
for i in range(nr, (((nr + rank) - level) - 1)):
self._digraph.add_edge(i, (i + 1))
self._digraph.add_edge(((i + rank) - level), i)
self._digraph.add_edge((i + 1), ((i + rank) - level))
level += 1
else:
_mutation_type_error(data)
elif (letter == 'X'):
if ((rank in [6, 7]) and (twist is None)):
self._rank = rank
self._info['mutation_finite'] = True
self._info['skew_symmetric'] = True
self._digraph.add_edges([(0, 1, 2), (1, 2, None), (2, 0, None), (2, 3, None), (3, 4, 2), (4, 2, None), (2, 5, None)])
if (rank == 7):
self._digraph.add_edges([(5, 6, 2), (6, 2, None)])
else:
_mutation_type_error(data)
else:
_mutation_type_error(data)
if (not self._digraph):
if self._graph.is_bipartite():
self._digraph = _bipartite_graph_to_digraph(self._graph)
else:
raise ValueError('The QuiverMutationType does not have a Coxeter diagram.')
if (not self._graph):
self._graph = self._digraph.to_undirected()
if twist:
self._description = str([letter, rank, twist])
else:
self._description = str([letter, rank])
def irreducible_components(self):
"\n Return a list of all irreducible components of ``self``.\n\n EXAMPLES::\n\n sage: mut_type = QuiverMutationType('A',3); mut_type\n ['A', 3]\n sage: mut_type.irreducible_components()\n (['A', 3],)\n "
return tuple([self])
@cached_method
def class_size(self):
"\n If it is known, the size of the mutation class of all quivers\n which are mutation equivalent to the standard quiver of\n ``self`` (up to isomorphism) is returned.\n\n Otherwise, :obj:`NotImplemented` is returned.\n\n Formula for finite type A is taken from Torkildsen - Counting\n cluster-tilted algebras of type `A_n`.\n Formulas for affine type A and finite type D are taken from Bastian,\n Prellberg, Rubey, Stump - Counting the number of elements in the\n mutation classes of `\\widetilde A_n` quivers.\n Formulas for finite and affine types B and C are\n proven but not yet published.\n Conjectural formulas for several other non-simply-laced affine types\n are implemented.\n Exceptional Types (finite, affine, and elliptic) E, F, G, and X are\n hardcoded.\n\n EXAMPLES::\n\n sage: mut_type = QuiverMutationType( ['A',5] ); mut_type\n ['A', 5]\n sage: mut_type.class_size()\n 19\n\n sage: mut_type = QuiverMutationType( ['A',[10,3], 1] ); mut_type\n ['A', [3, 10], 1]\n sage: mut_type.class_size()\n 142120\n\n sage: mut_type = QuiverMutationType( ['B',6] ); mut_type\n ['B', 6]\n sage: mut_type.class_size()\n 132\n\n sage: mut_type = QuiverMutationType( ['BD',6, 1] ); mut_type\n ['BD', 6, 1]\n sage: mut_type.class_size()\n Warning: This method uses a formula which has not been proved correct.\n 504\n\n Check that :trac:`14048` is fixed::\n\n sage: mut_type = QuiverMutationType( ['F',4,(2, 1)] )\n sage: mut_type.class_size()\n 90\n "
if (not self.is_mutation_finite()):
return infinity
if (self._letter == 'A'):
if self.is_finite():
n = self._rank
a = (binomial((2 * (n + 1)), (n + 1)) // (n + 2))
if ((n % 2) == 1):
a += binomial((n + 1), ((n + 1) // 2))
if ((n % 3) == 0):
a += (2 * binomial(((2 * n) // 3), (n // 3)))
return (a // (n + 3))
elif self.is_affine():
(i, j) = self._bi_rank
i = ZZ(i)
j = ZZ(j)
n = (i + j)
f = euler_phi
if (i == j):
return ((binomial((2 * i), i) + (sum(((f(k) * (binomial(((2 * i) // k), (i // k)) ** 2)) for k in i.divisors() if (k in j.divisors()))) // n)) // 4)
else:
return (sum((((f(k) * binomial(((2 * i) // k), (i // k))) * binomial(((2 * j) // k), (j // k))) for k in i.divisors() if (k in j.divisors()))) // (2 * n))
elif (self._letter in ['B', 'C']):
if self.is_finite():
n = self._rank
return (binomial((2 * n), n) // (n + 1))
elif (self._letter in ['BB', 'CC']):
print('Warning: This method uses a formula which has not been proved correct.')
if self.is_affine():
if (self._twist == 1):
n = (self._rank - 1)
N = binomial(((2 * n) - 1), (n - 1))
if (n % 2):
return N
else:
return (N + binomial((n - 1), ((n // 2) - 1)))
elif (self._letter == 'BC'):
print('Warning: This method uses a formula which has not been proved correct.')
if self.is_affine():
if (self._twist == 1):
n = (self._rank - 1)
return binomial((2 * n), n)
elif (self._letter in ['BD', 'CD']):
print('Warning: This method uses a formula which has not been proved correct.')
if self.is_affine():
if (self._twist == 1):
n = (self._rank - 2)
return (2 * binomial((2 * n), n))
elif (self._letter == 'D'):
if self.is_finite():
if (self._rank == 4):
return 6
else:
f = euler_phi
n = ZZ(self._rank)
return (sum(((f((n // k)) * binomial((2 * k), k)) for k in n.divisors())) // (2 * n))
elif self.is_affine():
n = (self._rank - 3)
if (n == 2):
return 9
else:
print('Warning: This method uses a formula which has not been proved correct.')
if (n % 2):
return (2 * binomial((2 * n), n))
else:
return ((2 * binomial((2 * n), n)) + binomial(n, (n // 2)))
elif (self._letter == 'E'):
if self.is_finite():
if (self._rank == 6):
return 67
elif (self._rank == 7):
return 416
elif (self._rank == 8):
return 1574
elif self.is_affine():
if (self._rank == 7):
return 132
elif (self._rank == 8):
return 1080
elif (self._rank == 9):
return 7560
elif self.is_elliptic():
if (self._rank == 8):
return 49
elif (self._rank == 9):
return 506
elif (self._rank == 10):
return 5739
elif (self._letter == 'F'):
if self.is_finite():
return 15
elif self.is_affine():
return 60
elif self.is_elliptic():
if (self._twist == [1, 2]):
return 90
if ((self._twist == [1, 1]) or (self._twist == [2, 2])):
return 35
elif (self._letter == 'G'):
if self.is_finite():
return 2
elif self.is_affine():
return 6
elif self.is_elliptic():
if (self._twist == [1, 3]):
return 7
if ((self._twist == [1, 1]) or (self._twist == [3, 3])):
return 2
elif (self._letter == 'X'):
if (self._rank == 6):
return 5
elif (self._rank == 7):
return 2
else:
print('Size unknown')
return NotImplemented
def dual(self):
"\n Return the :class:`QuiverMutationType` which is dual to ``self``.\n\n EXAMPLES::\n\n sage: mut_type = QuiverMutationType('A',5); mut_type\n ['A', 5]\n sage: mut_type.dual()\n ['A', 5]\n\n sage: mut_type = QuiverMutationType('B',5); mut_type\n ['B', 5]\n sage: mut_type.dual()\n ['C', 5]\n sage: mut_type.dual().dual()\n ['B', 5]\n sage: mut_type.dual().dual() == mut_type\n True\n "
letter = self.letter()
if ((letter != 'BC') and (letter[0] in ['B', 'C'])):
if (letter == 'BB'):
letter = 'CC'
elif (letter == 'CC'):
letter = 'BB'
elif (letter[0] == 'B'):
letter = ('C' + letter[1:])
elif (letter[0] == 'C'):
letter = ('B' + letter[1:])
rank = self._rank
if self.is_affine():
rank -= 1
twist = self._twist
return QuiverMutationType(letter, rank, twist)
elif (letter in ['F', 'G']):
if self.is_finite():
return self
elif self.is_affine():
rank = (self._rank - 1)
twist = (- self._twist)
elif self.is_elliptic():
twist = self._twist
rank = (self._rank - 2)
if (letter == 'F'):
if (self._twist == [2, 2]):
(twist == [1, 1])
if (self._twist == [1, 1]):
(twist == [2, 2])
if (letter == 'G'):
if (self._twist == [3, 3]):
twist = [1, 1]
elif (self._twist == [1, 1]):
twist = [3, 3]
else:
rank = self._rank
return QuiverMutationType(letter, rank, twist)
else:
return self
|
class QuiverMutationType_Reducible(QuiverMutationType_abstract):
'\n The mutation type for a cluster algebra or a quiver. Should not be\n called directly, but through :class:`QuiverMutationType`. Inherits from\n :class:`QuiverMutationType_abstract`.\n '
def __init__(self, *args):
"\n Should not be called directly, but through QuiverMutationType.\n\n INPUT:\n\n - ``data`` -- a list each of whose entries is a\n QuiverMutationType_Irreducible\n\n EXAMPLES::\n\n sage: QuiverMutationType(['A',4],['B',6])\n [ ['A', 4], ['B', 6] ]\n "
data = args
if ((len(data) < 2) or (not all((isinstance(comp, QuiverMutationType_Irreducible) for comp in data)))):
return _mutation_type_error(data)
self._info = {}
self._info['irreducible'] = False
self._info['mutation_finite'] = all((comp.is_mutation_finite() for comp in data))
self._info['simply_laced'] = all((comp.is_simply_laced() for comp in data))
self._info['skew_symmetric'] = all((comp.is_skew_symmetric() for comp in data))
self._info['finite'] = all((comp.is_finite() for comp in data))
self._info['irreducible_components'] = copy(data)
self._letter = ''
self._rank = 0
self._graph = Graph()
self._digraph = DiGraph()
for comp in data:
if self._letter:
self._letter += ' x '
self._letter += comp._letter
self._rank += comp._rank
self._graph = self._graph.disjoint_union(comp._graph, labels='integers')
self._digraph = self._digraph.disjoint_union(comp._digraph, labels='integers')
self._graph.name('')
self._digraph.name('')
self._description = '[ '
comps = self.irreducible_components()
for i in range(len(comps)):
if (i > 0):
self._description += ', '
self._description += comps[i]._description
self._description += ' ]'
def irreducible_components(self):
"\n Return a list of all irreducible components of ``self``.\n\n EXAMPLES::\n\n sage: mut_type = QuiverMutationType('A',3); mut_type\n ['A', 3]\n sage: mut_type.irreducible_components()\n (['A', 3],)\n\n sage: mut_type = QuiverMutationType(['A',3],['B',3]); mut_type\n [ ['A', 3], ['B', 3] ]\n sage: mut_type.irreducible_components()\n (['A', 3], ['B', 3])\n\n sage: mut_type = QuiverMutationType(['A',3],['B',3],['X',6])\n sage: mut_type\n [ ['A', 3], ['B', 3], ['X', 6] ]\n sage: mut_type.irreducible_components()\n (['A', 3], ['B', 3], ['X', 6])\n "
return self._info['irreducible_components']
@cached_method
def class_size(self):
"\n If it is known, the size of the mutation class of all quivers\n which are mutation equivalent to the standard quiver of\n ``self`` (up to isomorphism) is returned.\n\n Otherwise, :obj:`NotImplemented` is returned.\n\n EXAMPLES::\n\n sage: mut_type = QuiverMutationType(['A',3],['B',3]); mut_type\n [ ['A', 3], ['B', 3] ]\n sage: mut_type.class_size()\n 20\n\n sage: mut_type = QuiverMutationType(['A',3],['B',3],['X',6])\n sage: mut_type\n [ ['A', 3], ['B', 3], ['X', 6] ]\n sage: mut_type.class_size()\n 100\n "
if (not self.is_mutation_finite()):
return infinity
components = []
multiplicities = []
for x in self.irreducible_components():
if (not components.count(x)):
components.append(x)
multiplicities.append(1)
else:
y = components.index(x)
multiplicities[y] += 1
sizes = [x.class_size() for x in components]
if (NotImplemented in sizes):
print('Size unknown')
return NotImplemented
else:
return prod((binomial(((sizes[i] + multiplicities[i]) - 1), multiplicities[i]) for i in range(len(sizes))))
def dual(self):
"\n Return the :class:`QuiverMutationType` which is dual to ``self``.\n\n EXAMPLES::\n\n sage: mut_type = QuiverMutationType(['A',5],['B',6],['C',5],['D',4]); mut_type\n [ ['A', 5], ['B', 6], ['C', 5], ['D', 4] ]\n sage: mut_type.dual()\n [ ['A', 5], ['C', 6], ['B', 5], ['D', 4] ]\n "
comps = self.irreducible_components()
return QuiverMutationType([comp.dual() for comp in comps])
|
def _construct_classical_mutation_classes(n) -> dict[(tuple, (list | set))]:
'\n Return a dict with keys being tuples representing regular\n QuiverMutationTypes of the given rank, and with values being lists\n or sets containing all mutation equivalent quivers as dig6 data.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.quiver_mutation_type import _construct_classical_mutation_classes\n sage: rank_2_classes = _construct_classical_mutation_classes(2) # long time\n sage: for mut_class in sorted(rank_2_classes.keys(),key=str): # long time\n ....: print("{} {}".format(mut_class, rank_2_classes[mut_class]))\n (\'A\', (1, 1), 1) [(\'AO\', (((0, 1), (2, -2)),))]\n (\'A\', 2) [(\'AO\', ())]\n (\'B\', 2) [(\'AO\', (((0, 1), (1, -2)),)), (\'AO\', (((0, 1), (2, -1)),))]\n (\'BC\', 1, 1) [(\'AO\', (((0, 1), (1, -4)),)),\n (\'AO\', (((0, 1), (4, -1)),))]\n '
from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver
data: dict[(tuple, (set | list))] = {}
data[('A', n)] = ClusterQuiver(['A', n]).mutation_class(data_type='dig6')
for j in range(1, ((n // 2) + 1)):
data[('A', ((n - j), j), 1)] = ClusterQuiver(['A', [(n - j), j], 1]).mutation_class(data_type='dig6')
if (n > 1):
data[('B', n)] = ClusterQuiver(['B', n]).mutation_class(data_type='dig6')
if (n > 2):
data[('BB', (n - 1), 1)] = ClusterQuiver(['BB', (n - 1), 1]).mutation_class(data_type='dig6')
if (n > 2):
data[('C', n)] = ClusterQuiver(['C', n]).mutation_class(data_type='dig6')
if (n > 1):
data[('BC', (n - 1), 1)] = ClusterQuiver(['BC', (n - 1), 1]).mutation_class(data_type='dig6')
if (n > 2):
data[('CC', (n - 1), 1)] = ClusterQuiver(['CC', (n - 1), 1]).mutation_class(data_type='dig6')
if (n > 3):
data[('BD', (n - 1), 1)] = ClusterQuiver(['BD', (n - 1), 1]).mutation_class(data_type='dig6')
if (n > 3):
data[('CD', (n - 1), 1)] = ClusterQuiver(['CD', (n - 1), 1]).mutation_class(data_type='dig6')
if (n > 3):
data[('D', n)] = ClusterQuiver(['D', n]).mutation_class(data_type='dig6')
if (n > 4):
data[('D', (n - 1), 1)] = ClusterQuiver(['D', (n - 1), 1]).mutation_class(data_type='dig6')
return data
|
def _construct_exceptional_mutation_classes(n) -> dict[(tuple, (list | set))]:
'\n Return a dict with keys being tuples representing exceptional\n QuiverMutationTypes of the given rank, and with values being lists\n or sets containing all mutation equivalent quivers as dig6 data.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.quiver_mutation_type import _construct_exceptional_mutation_classes\n sage: rank_3_exceptional = _construct_exceptional_mutation_classes(3) # long time\n sage: for mut_class in sorted(rank_3_exceptional.keys(), key=str): # long time\n ....: print("{} {}".format(mut_class, rank_3_exceptional[mut_class]))\n (\'G\', 2, -1) [(\'BH?\', (((1, 2), (1, -3)),)),\n (\'BGO\', (((2, 1), (3, -1)),)), (\'BW?\', (((0, 1), (3, -1)),)),\n (\'BP?\', (((0, 1), (1, -3)),)),\n (\'BP_\', (((0, 1), (1, -3)), ((2, 0), (3, -1)))),\n (\'BP_\', (((0, 1), (3, -1)), ((1, 2), (1, -3)), ((2, 0), (2, -2))))]\n (\'G\', 2, 1) [(\'BH?\', (((1, 2), (3, -1)),)),\n (\'BGO\', (((2, 1), (1, -3)),)), (\'BW?\', (((0, 1), (1, -3)),)),\n (\'BP?\', (((0, 1), (3, -1)),)),\n (\'BKO\', (((1, 0), (3, -1)), ((2, 1), (1, -3)))),\n (\'BP_\', (((0, 1), (2, -2)), ((1, 2), (1, -3)), ((2, 0), (3, -1))))]\n '
from sage.combinat.cluster_algebra_quiver.quiver import ClusterQuiver
data: dict[(tuple, (list | set))] = {}
if (n in [6, 7, 8]):
data[('E', n)] = ClusterQuiver(['E', n]).mutation_class(data_type='dig6')
if (n in [7, 8, 9]):
data[('E', (n - 1), 1)] = ClusterQuiver(['E', (n - 1), 1]).mutation_class(data_type='dig6')
if (n in [8, 9, 10]):
data[('E', (n - 2), (1, 1))] = ClusterQuiver(['E', (n - 2), [1, 1]]).mutation_class(data_type='dig6')
if (n == 4):
data[('F', 4)] = ClusterQuiver(['F', 4]).mutation_class(data_type='dig6')
if (n == 5):
data[('F', 4, 1)] = ClusterQuiver(['F', 4, 1]).mutation_class(data_type='dig6')
data[('F', 4, (- 1))] = ClusterQuiver(['F', 4, (- 1)]).mutation_class(data_type='dig6')
if (n == 2):
data[('G', 2)] = ClusterQuiver(['G', 2]).mutation_class(data_type='dig6')
if (n == 3):
data[('G', 2, 1)] = ClusterQuiver(['G', 2, 1]).mutation_class(data_type='dig6')
data[('G', 2, (- 1))] = ClusterQuiver(['G', 2, (- 1)]).mutation_class(data_type='dig6')
if (n == 4):
data[('G', 2, (1, 3))] = ClusterQuiver(['G', 2, (1, 3)]).mutation_class(data_type='dig6')
data[('G', 2, (1, 1))] = ClusterQuiver(['G', 2, (1, 1)]).mutation_class(data_type='dig6')
data[('G', 2, (3, 3))] = ClusterQuiver(['G', 2, (3, 3)]).mutation_class(data_type='dig6')
if (n in [6, 7]):
data[('X', n)] = ClusterQuiver(['X', n]).mutation_class(data_type='dig6')
if (n == 6):
data[('F', 4, (1, 2))] = ClusterQuiver(['F', 4, (1, 2)]).mutation_class(data_type='dig6')
data[('F', 4, (1, 1))] = ClusterQuiver(['F', 4, (1, 1)]).mutation_class(data_type='dig6')
data[('F', 4, (2, 2))] = ClusterQuiver(['F', 4, (2, 2)]).mutation_class(data_type='dig6')
return data
|
def _save_data_dig6(n, types='ClassicalExceptional', verbose=False):
"\n Save all exceptional mutation classes as dig6 data into the file ``exc_classes_n.dig6`` in the folder ``DOT_SAGE``.\n\n TESTS::\n\n sage: # needs sage.modules\n sage: from sage.combinat.cluster_algebra_quiver.quiver_mutation_type import save_quiver_data\n sage: save_quiver_data(2) # indirect doctest\n <BLANKLINE>\n The following types are saved to file ... and will now be used to determine quiver mutation types:\n [('A', 1)]\n <BLANKLINE>\n The following types are saved to file ... and will now be used to determine quiver mutation types:\n [('A', (1, 1), 1), ('A', 2), ('B', 2), ('BC', 1, 1), ('G', 2)]\n sage: save_quiver_data(2, up_to=False) # indirect doctest\n <BLANKLINE>\n The following types are saved to file ... and will now be used to determine quiver mutation types:\n [('A', (1, 1), 1), ('A', 2), ('B', 2), ('BC', 1, 1), ('G', 2)]\n sage: save_quiver_data(2, up_to=False, types='Classical') # indirect doctest\n <BLANKLINE>\n The following types are saved to file ... and will now be used to determine quiver mutation types:\n [('A', (1, 1), 1), ('A', 2), ('B', 2), ('BC', 1, 1)]\n sage: save_quiver_data(2, up_to=False, types='Exceptional') # indirect doctest\n <BLANKLINE>\n The following types are saved to file ... and will now be used to determine quiver mutation types:\n [('G', 2)]\n sage: save_quiver_data(2, up_to=False, verbose=False) # indirect doctest\n "
data = {}
possible_types = ['Classical', 'ClassicalExceptional', 'Exceptional']
if (types not in possible_types):
raise ValueError('The third input must be either ClassicalExceptional (default), Classical, or Exceptional.')
if (types in possible_types[:2]):
data.update(_construct_classical_mutation_classes(n))
if (types in possible_types[1:]):
data.update(_construct_exceptional_mutation_classes(n))
from sage.env import DOT_SAGE
types_path = (Path(DOT_SAGE) / 'cluster_algebra_quiver')
types_path.mkdir(exist_ok=True)
types_file = (types_path / f'mutation_classes_{n}.dig6')
from sage.misc.temporary_file import atomic_write
with atomic_write(types_file, binary=True) as f:
pickle.dump(data, f)
if verbose:
keys = sorted(data, key=str)
print('\nThe following types are saved to file', types_file, 'and will now be used to determine quiver mutation types:')
print(keys)
|
def save_quiver_data(n, up_to=True, types='ClassicalExceptional', verbose=True):
"\n Save mutation classes of certain quivers of ranks up to and equal\n to ``n`` or equal to ``n`` to\n ``DOT_SAGE/cluster_algebra_quiver/mutation_classes_n.dig6``.\n\n This data will then be used to determine quiver mutation types.\n\n INPUT:\n\n - ``n`` -- the rank (or the upper limit on the rank) of the mutation\n classes that are being saved.\n\n - ``up_to`` -- (default:``True``) if ``True``, saves data for\n ranks smaller than or equal to ``n``. If ``False``, saves data\n for rank exactly ``n``.\n\n - ``types`` -- (default:'ClassicalExceptional') if all, saves data\n for both exceptional mutation-finite quivers and for classical\n quiver. The input 'Exceptional' or 'Classical' is also allowed\n to save only part of this data.\n\n TESTS::\n\n sage: # needs sage.modules\n sage: from sage.combinat.cluster_algebra_quiver.quiver_mutation_type import save_quiver_data\n sage: save_quiver_data(2)\n <BLANKLINE>\n The following types are saved to file ... and will now be used to determine quiver mutation types:\n [('A', 1)]\n <BLANKLINE>\n The following types are saved to file ... and will now be used to determine quiver mutation types:\n [('A', (1, 1), 1), ('A', 2), ('B', 2), ('BC', 1, 1), ('G', 2)]\n sage: save_quiver_data(2,up_to=False)\n <BLANKLINE>\n The following types are saved to file ... and will now be used to determine quiver mutation types:\n [('A', (1, 1), 1), ('A', 2), ('B', 2), ('BC', 1, 1), ('G', 2)]\n sage: save_quiver_data(2,up_to=False, types='Classical')\n <BLANKLINE>\n The following types are saved to file ... and will now be used to determine quiver mutation types:\n [('A', (1, 1), 1), ('A', 2), ('B', 2), ('BC', 1, 1)]\n sage: save_quiver_data(2,up_to=False, types='Exceptional')\n <BLANKLINE>\n The following types are saved to file ... and will now be used to determine quiver mutation types:\n [('G', 2)]\n sage: save_quiver_data(2,up_to=False, verbose=False)\n "
from sage.combinat.cluster_algebra_quiver.mutation_type import load_data
if (up_to is True):
ranks = range(1, (n + 1))
elif (up_to is False):
ranks = [n]
for i in ranks:
_save_data_dig6(i, types=types, verbose=verbose)
load_data.clear_cache()
|
def _bipartite_graph_to_digraph(g) -> DiGraph:
'\n Return a digraph obtained from a bipartite graph ``g`` by choosing one\n set of the bipartition to be the set of sinks and the other to be the\n set of sources.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.quiver_mutation_type import _bipartite_graph_to_digraph\n sage: G = Graph([(1, 2)])\n sage: _bipartite_graph_to_digraph(G)\n Digraph on 2 vertices\n '
sources = g.bipartite_sets()[0]
dg = DiGraph()
dg.add_vertices(g)
for (a, b, c) in g.edge_iterator():
if (a in sources):
dg.add_edge(a, b, c)
else:
dg.add_edge(b, a, c)
return dg
|
def _is_mutation_type(data) -> bool:
"\n Return ``True`` if ``data`` is a QuiverMutationType.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.quiver_mutation_type import _is_mutation_type\n sage: _is_mutation_type ( [ 'A', 2 ] )\n True\n sage: _is_mutation_type ( [ 'P', 1 ] )\n False\n "
try:
QuiverMutationType(data)
return True
except Exception:
return False
|
def _mutation_type_error(data):
"\n Output an error message because data which is not a valid quiver mutation\n type has been passed to QuiverMutationType.\n\n EXAMPLES::\n\n sage: QuiverMutationType( 'Christian', 'Stump' ) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: ['Christian', 'Stump'] is not a valid quiver mutation type\n Finite types have the form [ '?', n ] for type ? and rank n\n Affine type A has the form [ 'A', [ i, j ], 1 ] for rank i+j\n Affine type ? has the form [ '?', k, \\pm 1 ] for rank k+1\n Elliptic type ? has the form [ '?', k, [i, j] ] (1 <= i,j <= 3) for rank k+2\n For correct syntax in other types, please consult the documentation.\n "
if (data[2] is None):
del data[2]
return_str = (str(data) + ' is not a valid quiver mutation type')
return_str += "\n Finite types have the form [ '?', n ] for type ? and rank n"
return_str += "\n Affine type A has the form [ 'A', [ i, j ], 1 ] for rank i+j"
return_str += "\n Affine type ? has the form [ '?', k, \\pm 1 ] for rank k+1"
return_str += "\n Elliptic type ? has the form [ '?', k, [i, j] ] (1 <= i,j <= 3) for rank k+2"
return_str += '\n For correct syntax in other types, please consult the documentation.'
raise ValueError(return_str)
|
def _edge_list_to_matrix(edges, nlist, mlist) -> matrix:
"\n Return the matrix obtained from the edge list of a quiver.\n\n INPUT:\n\n - ``edges`` -- the list of edges\n - ``nlist`` -- the list of mutable vertices of the quiver\n - ``mlist`` -- the list of frozen vertices of the quiver\n\n OUTPUT:\n\n An `(n+m) \\times n` matrix corresponding to the edge-list.\n\n EXAMPLES::\n\n sage: from sage.combinat.cluster_algebra_quiver.quiver_mutation_type import _edge_list_to_matrix\n sage: G = QuiverMutationType(['A', 2])._digraph\n sage: _edge_list_to_matrix(G.edges(sort=True), [0, 1], []) # needs sage.modules\n [ 0 1]\n [-1 0]\n\n sage: G2 = DiGraph([('a', 'b', 1)])\n sage: _edge_list_to_matrix(G2.edges(sort=True), ['a', 'b'], []) # needs sage.modules\n [ 0 1]\n [-1 0]\n\n sage: G3 = DiGraph([('a', 'b', 1), ('b', 'c', 1)])\n sage: _edge_list_to_matrix(G3.edges(sort=True), ['a', 'b'], ['c']) # needs sage.modules\n [ 0 1]\n [-1 0]\n [ 0 -1]\n "
n = len(nlist)
nmlist = (nlist + mlist)
nm = len(nmlist)
M = matrix(ZZ, nm, n, sparse=True)
for (v1, v2, label) in edges:
if (label is None):
(a, b) = (1, (- 1))
elif (label in ZZ):
(a, b) = (label, (- label))
else:
(a, b) = label
if (v1 in nlist):
M[(nmlist.index(v2), nmlist.index(v1))] = b
if (v2 in nlist):
M[(nmlist.index(v1), nmlist.index(v2))] = a
return M
|
class ClusterComplexFacet(SubwordComplexFacet):
'\n A cluster (i.e., a facet) of a cluster complex.\n '
def cluster(self):
"\n Return this cluster as a set of almost positive roots.\n\n EXAMPLES::\n\n sage: C = ClusterComplex(['A', 2])\n sage: F = C((0, 1))\n sage: F.cluster()\n [(-1, 0), (0, -1)]\n "
if (self.parent().k() != 1):
raise NotImplementedError('not working for multi-cluster complexes')
F = self.parent().greedy_facet(side='positive')
R = F.extended_root_configuration()
N = len(list(F))
return [((- R[i]) if (i < N) else R[i]) for i in self]
def upper_cluster(self):
"\n Return the part of the cluster that contains positive roots\n\n EXAMPLES::\n\n sage: C = ClusterComplex(['A', 2])\n sage: F = C((0, 1))\n sage: F.upper_cluster()\n []\n "
return [beta for beta in self.cluster() if (sum(beta) > 0)]
def product_of_upper_cluster(self):
"\n Return the product of the upper cluster in reversed order.\n\n EXAMPLES::\n\n sage: C = ClusterComplex(['A', 2])\n sage: for F in C: F.product_of_upper_cluster().reduced_word()\n []\n [2]\n [1]\n [1, 2]\n [1, 2]\n "
W = self.parent().group()
return W.prod((W.reflections()[beta] for beta in reversed(self.upper_cluster())))
|
class ClusterComplex(SubwordComplex):
"\n A cluster complex (or generalized dual associahedron).\n\n The cluster complex (or generalized dual associahedron) is a\n simplicial complex constructed from a cluster algebra. Its\n vertices are the cluster variables and its facets are the\n clusters, i.e., maximal subsets of compatible cluster variables.\n\n The cluster complex of type `A_n` is the simplicial complex with\n vertices being (proper) diagonals in a convex `(n+3)`-gon and with\n facets being triangulations.\n\n The implementation of the cluster complex depends on its\n connection to subword complexes, see [CLS2014]_. Let `c` be a Coxeter\n element with reduced word `{\\bf c}` in a finite Coxeter group `W`,\n and let `{\\bf w}_\\circ` be the `c`-sorting word for the longest\n element `w_\\circ \\in W`.\n\n The ``multi-cluster complex`` `\\Delta(W,k)` has vertices in\n one-to-one correspondence with letters in the word\n `Q = {\\bf c^k w}_\\circ` and with facets being complements\n in `Q` of reduced expressions for `w_\\circ`.\n\n For `k = 1`, the multi-cluster complex is isomorphic to the\n cluster complex as defined above.\n\n EXAMPLES:\n\n A first example of a cluster complex::\n\n sage: C = ClusterComplex(['A', 2]); C\n Cluster complex of type ['A', 2] with 5 vertices and 5 facets\n\n Its vertices, facets, and minimal non-faces::\n\n sage: C.vertices()\n (0, 1, 2, 3, 4)\n\n sage: C.facets()\n [(0, 1), (0, 4), (1, 2), (2, 3), (3, 4)]\n\n sage: C.minimal_nonfaces()\n [[0, 2], [0, 3], [1, 3], [1, 4], [2, 4]]\n\n We can do everything we can do on simplicial complexes,\n e.g. computing its homology::\n\n sage: C.homology()\n {0: 0, 1: Z}\n\n We can also create a multi-cluster complex::\n\n sage: ClusterComplex(['A', 2], k=2)\n Multi-cluster complex of type ['A', 2] with 7 vertices and 14 facets\n\n REFERENCES:\n\n - [CLS2014]_\n "
@staticmethod
def __classcall__(cls, W, k=1, coxeter_element=None, algorithm='inductive'):
'\n Standardize input to ensure a unique representation.\n\n TESTS::\n\n sage: S1 = ClusterComplex([\'B\',2])\n sage: W = CoxeterGroup([\'B\',2])\n sage: S2 = ClusterComplex(W)\n sage: S3 = ClusterComplex(CoxeterMatrix(\'B2\'), coxeter_element=(1,2))\n sage: w = W.from_reduced_word([1,2])\n sage: S4 = ClusterComplex(\'B2\', coxeter_element=w, algorithm="inductive")\n sage: S1 is S2 and S2 is S3 and S3 is S4\n True\n '
if (k not in NN):
raise ValueError('the additional parameter must be a nonnegative integer')
if (W not in CoxeterGroups):
W = CoxeterGroup(W)
if (not W.is_finite()):
raise ValueError('the Coxeter group must be finite')
if (coxeter_element is None):
coxeter_element = W.index_set()
elif hasattr(coxeter_element, 'reduced_word'):
coxeter_element = coxeter_element.reduced_word()
coxeter_element = tuple(coxeter_element)
return super(SubwordComplex, cls).__classcall__(cls, W=W, k=k, coxeter_element=coxeter_element, algorithm=algorithm)
def __init__(self, W, k, coxeter_element, algorithm):
"\n Initialize ``self``.\n\n TESTS::\n\n sage: S = ClusterComplex(['A', 2])\n sage: TestSuite(S).run()\n sage: S = ClusterComplex(['A', 2], k=2)\n sage: TestSuite(S).run()\n "
w = W.w0
Q = ((coxeter_element * k) + tuple(w.coxeter_sorting_word(coxeter_element)))
SubwordComplex.__init__(self, Q, w, algorithm=algorithm)
self._W = W
self._w0 = w
self._k = k
self.set_immutable()
def __call__(self, F, facet_test=True):
"\n Create a facet of ``self``.\n\n INPUT:\n\n - ``F`` -- an iterable of positions\n - ``facet_test`` -- boolean (default: ``True``); tells whether\n or not the facet ``F`` should be tested before creation\n\n OUTPUT:\n\n The facet of ``self`` at positions given by ``F``.\n\n EXAMPLES::\n\n sage: C = ClusterComplex(['A', 2])\n sage: F = C((0, 1)); F\n (0, 1)\n\n TESTS::\n\n sage: C = ClusterComplex(['A', 2])\n sage: F = C((0, 1))\n sage: C(F) is F\n True\n "
if (isinstance(F, ClusterComplexFacet) and (F.parent() is self)):
return F
return self.element_class(self, F, facet_test=facet_test)
Element = ClusterComplexFacet
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: ClusterComplex([\'A\', 2])._repr_()\n "Cluster complex of type [\'A\', 2] with 5 vertices and 5 facets"\n '
if (self._k == 1):
name = 'Cluster complex'
else:
name = 'Multi-cluster complex'
name += (' of type %s with %s vertices and %s facets' % (self.cartan_type(), len(self.vertices()), len(self._facets)))
return name
def k(self):
"\n Return the index `k` of ``self``.\n\n EXAMPLES::\n\n sage: ClusterComplex(['A', 2]).k()\n 1\n "
return self._k
def minimal_nonfaces(self):
"\n Return the minimal non-faces of ``self``.\n\n EXAMPLES::\n\n sage: ClusterComplex(['A', 2]).minimal_nonfaces()\n [[0, 2], [0, 3], [1, 3], [1, 4], [2, 4]]\n "
from sage.combinat.combination import Combinations
return [X for X in Combinations(self.vertices(), (self.k() + 1)) if (not any((set(X).issubset(F) for F in self.facets())))]
def cyclic_rotation(self):
"\n Return the operation on the facets of ``self`` obtained by the\n cyclic rotation as defined in [CLS2014]_.\n\n EXAMPLES::\n\n sage: ClusterComplex(['A', 2]).cyclic_rotation()\n <function ...act at ...>\n "
W = self._W
w = self._w0
Q = self._Q
l = len(Q)
S = W.simple_reflections()
S_inv = {S[j]: j for j in W.index_set()}
Q = (Q + tuple((S_inv[((w * S[k]) * w)] for k in Q)))
D = {i: (((Q[(i + 1):].index(Q[i]) + i) + 1) % l) for i in range(l)}
def act(F):
return self.parent().element_class(sorted([D[i] for i in F]))
return act
|
class ColoredPermutation(MultiplicativeGroupElement):
'\n A colored permutation.\n '
def __init__(self, parent, colors, perm):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: TestSuite(s1*s2*t).run()\n '
self._colors = tuple(colors)
self._perm = perm
MultiplicativeGroupElement.__init__(self, parent=parent)
def __hash__(self):
'\n TESTS::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: for gen in s1,s2,t:\n ....: assert hash(gen) ^^ hash(gen._colors) == hash(gen._perm)\n '
return (hash(self._perm) ^ hash(self._colors))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: s1*s2*t\n [[1, 0, 0], [3, 1, 2]]\n '
return repr([list(self._colors), self._perm])
def _latex_(self):
'\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: latex(s1*s2*t)\n [3_{1}, 1_{0}, 2_{0}]\n '
ret = '['
ret += ', '.join(('{}_{{{}}}'.format(x, c) for (c, x) in zip(self._colors, self._perm)))
return (ret + ']')
def __len__(self):
'\n Return the length of the one line form of ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(2, 3)\n sage: s1,s2,t = C.gens()\n sage: len(s1)\n 3\n '
return len(self._perm)
def _mul_(self, other):
'\n Multiply ``self`` and ``other``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: s1*s2*s1 == s2*s1*s2\n True\n '
colors = tuple(((c + other._colors[(val - 1)]) for (c, val) in zip(self._colors, self._perm)))
p = self._perm._left_to_right_multiply_on_right(other._perm)
return self.__class__(self.parent(), colors, p)
def __invert__(self):
'\n Return the inverse of ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: ~t # indirect doctest\n [[0, 0, 3], [1, 2, 3]]\n sage: all(x * ~x == C.one() for x in C.gens())\n True\n '
ip = (~ self._perm)
return self.__class__(self.parent(), tuple(((- self._colors[(i - 1)]) for i in ip)), ip)
def __eq__(self, other):
'\n Check equality.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: s1*s2*s1 == s2*s1*s2\n True\n sage: t^4 == C.one()\n True\n sage: s1*s2 == s2*s1\n False\n '
if (not isinstance(other, ColoredPermutation)):
return False
return ((self.parent() is other.parent()) and (self._colors == other._colors) and (self._perm == other._perm))
def __ne__(self, other):
'\n Check inequality.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: s1*s2*s1 != s2*s1*s2\n False\n sage: s1*s2 != s2*s1\n True\n '
return (not (self == other))
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: x = s1*s2*t\n sage: list(x)\n [(1, 3), (0, 1), (0, 2)]\n '
(yield from zip(self._colors, self._perm))
def one_line_form(self):
'\n Return the one line form of ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: x = s1*s2*t\n sage: x\n [[1, 0, 0], [3, 1, 2]]\n sage: x.one_line_form()\n [(1, 3), (0, 1), (0, 2)]\n '
return list(self)
def __getitem__(self, key):
'\n Return the specified element in the one line form of ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: x = s1*s2*t\n sage: x\n [[1, 0, 0], [3, 1, 2]]\n sage: x[1]\n (0, 1)\n sage: x[1:]\n [(0, 1), (0, 2)]\n '
if isinstance(key, slice):
return list(zip(self._colors[key], self._perm[key]))
return (self._colors[key], self._perm[key])
def colors(self):
'\n Return the colors of ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: x = s1*s2*t\n sage: x.colors()\n [1, 0, 0]\n '
return list(self._colors)
def permutation(self):
'\n Return the permutation of ``self``.\n\n This is obtained by forgetting the colors.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: x = s1*s2*t\n sage: x.permutation()\n [3, 1, 2]\n '
return self._perm
def to_matrix(self):
'\n Return a matrix of ``self``.\n\n The colors are mapped to roots of unity.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s1,s2,t = C.gens()\n sage: x = s1*s2*t*s2; x.one_line_form()\n [(1, 2), (0, 1), (0, 3)]\n sage: M = x.to_matrix(); M # needs sage.rings.number_field\n [ 0 1 0]\n [zeta4 0 0]\n [ 0 0 1]\n\n The matrix multiplication is in the *opposite* order::\n\n sage: M == s2.to_matrix()*t.to_matrix()*s2.to_matrix()*s1.to_matrix() # needs sage.rings.number_field\n True\n '
Cp = CyclotomicField(self.parent()._m)
g = Cp.gen()
D = diagonal_matrix(Cp, [(g ** i) for i in self._colors])
return (self._perm.to_matrix() * D)
def has_left_descent(self, i):
'\n Return ``True`` if ``i`` is a left descent of ``self``.\n\n Let `p = ((s_1, \\ldots s_n), \\sigma)` be a colored permutation.\n We say `p` has a left `n`-descent if `s_n > 0`. If `i < n`, then\n we say `p` has a left `i`-descent if either\n\n - `s_i \\neq 0, s_{i+1} = 0` and `\\sigma_i < \\sigma_{i+1}` or\n - `s_i = s_{i+1}` and `\\sigma_i > \\sigma_{i+1}`.\n\n This notion of a left `i`-descent is done in order to recursively\n construct `w(p) = \\sigma_i w(\\sigma_i^{-1} p)`, where `w(p)`\n denotes a reduced word of `p`.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(2, 4)\n sage: s1,s2,s3,s4 = C.gens()\n sage: x = s4*s1*s2*s3*s4\n sage: [x.has_left_descent(i) for i in C.index_set()]\n [True, False, False, True]\n\n sage: C = ColoredPermutations(1, 5)\n sage: s1,s2,s3,s4 = C.gens()\n sage: x = s4*s1*s2*s3*s4\n sage: [x.has_left_descent(i) for i in C.index_set()]\n [True, False, False, True]\n\n sage: C = ColoredPermutations(3, 3)\n sage: x = C([[2,1,0],[3,1,2]])\n sage: [x.has_left_descent(i) for i in C.index_set()]\n [False, True, False]\n\n sage: C = ColoredPermutations(4, 4)\n sage: x = C([[2,1,0,1],[3,2,4,1]])\n sage: [x.has_left_descent(i) for i in C.index_set()]\n [False, True, False, True]\n '
if (self.parent()._m == 1):
return (self._perm[(i - 1)] > self._perm[i])
if (i == self.parent()._n):
return (self._colors[(- 1)] != 0)
if (self._colors[(i - 1)] != 0):
return ((self._colors[i] == 0) or (self._perm[(i - 1)] < self._perm[i]))
return ((self._colors[i] == 0) and (self._perm[(i - 1)] > self._perm[i]))
def reduced_word(self):
'\n Return a word in the simple reflections to obtain ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(3, 3)\n sage: x = C([[2,1,0],[3,1,2]])\n sage: x.reduced_word()\n [2, 1, 3, 2, 1, 3, 3]\n\n sage: C = ColoredPermutations(4, 4)\n sage: x = C([[2,1,0,1],[3,2,4,1]])\n sage: x.reduced_word()\n [2, 1, 4, 3, 2, 1, 4, 3, 2, 4, 4, 3]\n\n TESTS::\n\n sage: C = ColoredPermutations(3, 3)\n sage: all(C.from_reduced_word(p.reduced_word()) == p for p in C)\n True\n '
if (self == self.parent().one()):
return []
I = self.parent().index_set()
sinv = self.parent()._inverse_simple_reflections()
for i in I:
if self.has_left_descent(i):
return ([i] + (sinv[i] * self).reduced_word())
assert False, 'BUG in reduced_word'
def length(self):
'\n Return the length of ``self`` in generating reflections.\n\n This is the minimal numbers of generating reflections needed\n to obtain ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(3, 3)\n sage: x = C([[2,1,0],[3,1,2]])\n sage: x.length()\n 7\n\n sage: C = ColoredPermutations(4, 4)\n sage: x = C([[2,1,0,1],[3,2,4,1]])\n sage: x.length()\n 12\n\n TESTS::\n\n sage: C = ColoredPermutations(3, 3)\n sage: d = [p.length() for p in C]\n sage: [d.count(i) for i in range(14)]\n [1, 3, 6, 10, 15, 20, 23, 24, 23, 19, 12, 5, 1, 0]\n sage: d = [p.length() for p in ReflectionGroup([3, 1, 3])] # optional - gap3\n sage: [d.count(i) for i in range(14)] # optional - gap3\n [1, 3, 6, 10, 15, 20, 23, 24, 23, 19, 12, 5, 1, 0]\n\n sage: C = ColoredPermutations(4, 3)\n sage: d = [p.length() for p in C]\n sage: [d.count(i) for i in range(17)]\n [1, 3, 6, 11, 18, 27, 36, 44, 50, 52, 49, 40, 27, 14, 5, 1, 0]\n sage: d = [p.length() for p in ReflectionGroup([4, 1, 3])] # optional - gap3\n sage: [d.count(i) for i in range(17)] # optional - gap3\n [1, 3, 6, 11, 18, 27, 36, 44, 50, 52, 49, 40, 27, 14, 5, 1, 0]\n\n sage: C = ColoredPermutations(3, 4)\n sage: d = [p.length() for p in C]\n sage: [d.count(i) for i in range(22)]\n [1, 4, 10, 20, 35, 56, 82, 112, 144, 174, 197,\n 209, 209, 197, 173, 138, 96, 55, 24, 7, 1, 0]\n sage: d = [p.length() for p in ReflectionGroup([3, 1, 4])] # optional - gap3\n sage: [d.count(i) for i in range(22)] # optional - gap3\n [1, 4, 10, 20, 35, 56, 82, 112, 144, 174, 197,\n 209, 209, 197, 173, 138, 96, 55, 24, 7, 1, 0]\n '
return ZZ(len(self.reduced_word()))
|
class ColoredPermutations(Parent, UniqueRepresentation):
'\n The group of `m`-colored permutations on `\\{1, 2, \\ldots, n\\}`.\n\n Let `S_n` be the symmetric group on `n` letters and `C_m` be the cyclic\n group of order `m`. The `m`-colored permutation group on `n` letters\n is given by `P_n^m = C_m \\wr S_n`. This is also the complex reflection\n group `G(m, 1, n)`.\n\n We define our multiplication by\n\n .. MATH::\n\n ((s_1, \\ldots s_n), \\sigma) \\cdot ((t_1, \\ldots, t_n), \\tau)\n = ((s_1 t_{\\sigma(1)}, \\ldots, s_n t_{\\sigma(n)}), \\tau \\sigma).\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3); C\n 4-colored permutations of size 3\n sage: s1,s2,t = C.gens()\n sage: (s1, s2, t)\n ([[0, 0, 0], [2, 1, 3]], [[0, 0, 0], [1, 3, 2]], [[0, 0, 1], [1, 2, 3]])\n sage: s1*s2\n [[0, 0, 0], [3, 1, 2]]\n sage: s1*s2*s1 == s2*s1*s2\n True\n sage: t^4 == C.one()\n True\n sage: s2*t*s2\n [[0, 1, 0], [1, 2, 3]]\n\n We can also create a colored permutation by passing\n an iterable consisting of tuples consisting of ``(color, element)``::\n\n sage: x = C([(2,1), (3,3), (3,2)]); x\n [[2, 3, 3], [1, 3, 2]]\n\n or a list of colors and a permutation::\n\n sage: C([[3,3,1], [1,3,2]])\n [[3, 3, 1], [1, 3, 2]]\n sage: C(([3,3,1], [1,3,2]))\n [[3, 3, 1], [1, 3, 2]]\n\n There is also the natural lift from permutations::\n\n sage: P = Permutations(3)\n sage: C(P.an_element())\n [[0, 0, 0], [3, 1, 2]]\n\n\n A colored permutation::\n\n sage: C(C.an_element()) == C.an_element()\n True\n\n REFERENCES:\n\n - :wikipedia:`Generalized_symmetric_group`\n - :wikipedia:`Complex_reflection_group`\n '
def __init__(self, m, n):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: TestSuite(C).run()\n sage: C = ColoredPermutations(2, 3)\n sage: TestSuite(C).run()\n sage: C = ColoredPermutations(1, 3)\n sage: TestSuite(C).run()\n '
if (m <= 0):
raise ValueError('m must be a positive integer')
self._m = ZZ(m)
self._n = ZZ(n)
self._C = IntegerModRing(self._m)
self._P = Permutations(self._n)
if ((self._m == 1) or (self._m == 2)):
from sage.categories.finite_coxeter_groups import FiniteCoxeterGroups
category = FiniteCoxeterGroups().Irreducible()
else:
from sage.categories.complex_reflection_groups import ComplexReflectionGroups
category = ComplexReflectionGroups().Finite().Irreducible().WellGenerated()
Parent.__init__(self, category=category)
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: ColoredPermutations(4, 3)\n 4-colored permutations of size 3\n '
return '{}-colored permutations of size {}'.format(self._m, self._n)
@cached_method
def index_set(self):
'\n Return the index set of ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(3, 4)\n sage: C.index_set()\n (1, 2, 3, 4)\n\n sage: C = ColoredPermutations(1, 4)\n sage: C.index_set()\n (1, 2, 3)\n\n TESTS::\n\n sage: S = SignedPermutations(4)\n sage: S.index_set()\n (1, 2, 3, 4)\n '
n = self._n
if (self._m != 1):
n += 1
return tuple(range(1, n))
def coxeter_matrix(self):
'\n Return the Coxeter matrix of ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(3, 4)\n sage: C.coxeter_matrix() # needs sage.modules\n [1 3 2 2]\n [3 1 3 2]\n [2 3 1 4]\n [2 2 4 1]\n\n sage: C = ColoredPermutations(1, 4)\n sage: C.coxeter_matrix() # needs sage.modules\n [1 3 2]\n [3 1 3]\n [2 3 1]\n\n TESTS::\n\n sage: S = SignedPermutations(4)\n sage: S.coxeter_matrix() # needs sage.modules\n [1 3 2 2]\n [3 1 3 2]\n [2 3 1 4]\n [2 2 4 1]\n '
from sage.combinat.root_system.cartan_type import CartanType
if (self._m == 1):
return CartanType(['A', (self._n - 1)]).coxeter_matrix()
return CartanType(['B', self._n]).coxeter_matrix()
@cached_method
def one(self):
'\n Return the identity element of ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: C.one()\n [[0, 0, 0], [1, 2, 3]]\n '
return self.element_class(self, ([self._C.zero()] * self._n), self._P.identity())
def random_element(self):
'\n Return an element drawn uniformly at random.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: s = C.random_element(); s # random\n [[0, 2, 1], [2, 1, 3]]\n sage: s in C\n True\n '
return self.element_class(self, [self._C.random_element() for _ in range(self._n)], self._P.random_element())
def simple_reflection(self, i):
'\n Return the ``i``-th simple reflection of ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: C.gens()\n ([[0, 0, 0], [2, 1, 3]], [[0, 0, 0], [1, 3, 2]], [[0, 0, 1], [1, 2, 3]])\n sage: C.simple_reflection(2)\n [[0, 0, 0], [1, 3, 2]]\n sage: C.simple_reflection(3)\n [[0, 0, 1], [1, 2, 3]]\n\n sage: S = SignedPermutations(4)\n sage: S.simple_reflection(1)\n [2, 1, 3, 4]\n sage: S.simple_reflection(4)\n [1, 2, 3, -4]\n '
if (i not in self.index_set()):
raise ValueError('i must be in the index set')
colors = ([self._C.zero()] * self._n)
if (i < self._n):
p = list(range(1, (self._n + 1)))
p[(i - 1)] = (i + 1)
p[i] = i
return self.element_class(self, colors, self._P(p))
colors[(- 1)] = self._C.one()
return self.element_class(self, colors, self._P.identity())
@cached_method
def _inverse_simple_reflections(self):
'\n Return the inverse of the simple reflections of ``self``.\n\n .. WARNING::\n\n This returns a ``dict`` that should not be mutated since\n the result is cached.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: C._inverse_simple_reflections()\n {1: [[0, 0, 0], [2, 1, 3]],\n 2: [[0, 0, 0], [1, 3, 2]],\n 3: [[0, 0, 3], [1, 2, 3]]}\n '
s = self.simple_reflections()
return {i: (~ s[i]) for i in self.index_set()}
@cached_method
def gens(self):
'\n Return the generators of ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: C.gens()\n ([[0, 0, 0], [2, 1, 3]],\n [[0, 0, 0], [1, 3, 2]],\n [[0, 0, 1], [1, 2, 3]])\n\n sage: S = SignedPermutations(4)\n sage: S.gens()\n ([2, 1, 3, 4], [1, 3, 2, 4], [1, 2, 4, 3], [1, 2, 3, -4])\n '
return tuple((self.simple_reflection(i) for i in self.index_set()))
def matrix_group(self):
'\n Return the matrix group corresponding to ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: C.matrix_group() # needs sage.modules\n Matrix group over Cyclotomic Field of order 4 and degree 2 with 3 generators (\n [0 1 0] [1 0 0] [ 1 0 0]\n [1 0 0] [0 0 1] [ 0 1 0]\n [0 0 1], [0 1 0], [ 0 0 zeta4]\n )\n '
from sage.groups.matrix_gps.finitely_generated import MatrixGroup
return MatrixGroup([g.to_matrix() for g in self.gens()])
def as_permutation_group(self):
'\n Return the permutation group corresponding to ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: C.as_permutation_group() # needs sage.groups\n Complex reflection group G(4, 1, 3) as a permutation group\n '
from sage.groups.perm_gps.permgroup_named import ComplexReflectionGroup
return ComplexReflectionGroup(self._m, 1, self._n)
def _element_constructor_(self, x):
'\n Construct an element of ``self`` from ``x``.\n\n INPUT:\n\n Either a list of pairs (color, element)\n or a pair of lists (colors, elements).\n\n TESTS::\n\n sage: C = ColoredPermutations(4, 3)\n sage: x = C([(2,1), (3,3), (3,2)]); x\n [[2, 3, 3], [1, 3, 2]]\n sage: x == C([[2,3,3], [1,3,2]])\n True\n '
if (isinstance(x, self.element_class) and (x.parent() is self)):
return self
x = list(x)
if isinstance(x[0], tuple):
c = []
p = []
for k in x:
if (len(k) != 2):
raise ValueError('input must be pairs (color, element)')
c.append(self._C(k[0]))
p.append(k[1])
return self.element_class(self, c, self._P(p))
if (len(x) != 2):
raise ValueError('input must be a pair of a list of colors and a permutation')
return self.element_class(self, [self._C(v) for v in x[0]], self._P(x[1]))
def _coerce_map_from_(self, C):
'\n Return a coerce map from ``C`` if it exists and ``None`` otherwise.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(2, 3)\n sage: S = SignedPermutations(3)\n sage: C.has_coerce_map_from(S)\n True\n\n sage: C = ColoredPermutations(4, 3)\n sage: C.has_coerce_map_from(S)\n False\n sage: S = SignedPermutations(4)\n sage: C.has_coerce_map_from(S)\n False\n\n sage: P = Permutations(3)\n sage: C.has_coerce_map_from(P)\n True\n sage: P = Permutations(4)\n sage: C.has_coerce_map_from(P)\n False\n '
if (isinstance(C, Permutations) and (C.n == self._n)):
return (lambda P, x: P.element_class(P, ([P._C.zero()] * P._n), x))
if ((self._m == 2) and isinstance(C, SignedPermutations) and (C._n == self._n)):
return (lambda P, x: P.element_class(P, [(P._C.zero() if (v == 1) else P._C.one()) for v in x._colors], x._perm))
return super()._coerce_map_from_(C)
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(2, 2)\n sage: [x for x in C]\n [[[0, 0], [1, 2]],\n [[0, 1], [1, 2]],\n [[1, 0], [1, 2]],\n [[1, 1], [1, 2]],\n [[0, 0], [2, 1]],\n [[0, 1], [2, 1]],\n [[1, 0], [2, 1]],\n [[1, 1], [2, 1]]]\n '
for p in self._P:
for c in itertools.product(self._C, repeat=self._n):
(yield self.element_class(self, c, p))
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: C.cardinality()\n 384\n sage: C.cardinality() == 4**3 * factorial(3)\n True\n '
return ((self._m ** self._n) * self._P.cardinality())
order = cardinality
def rank(self):
'\n Return the rank of ``self``.\n\n The rank of a complex reflection group is equal to the dimension\n of the complex vector space the group acts on.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 12)\n sage: C.rank()\n 12\n sage: C = ColoredPermutations(7, 4)\n sage: C.rank()\n 4\n sage: C = ColoredPermutations(1, 4)\n sage: C.rank()\n 3\n '
if (self._m == 1):
return (self._n - 1)
return self._n
def degrees(self):
'\n Return the degrees of ``self``.\n\n The degrees of a complex reflection group are the degrees of\n the fundamental invariants of the ring of polynomial invariants.\n\n If `m = 1`, then we are in the special case of the symmetric group\n and the degrees are `(2, 3, \\ldots, n, n+1)`. Otherwise the degrees\n are `(m, 2m, \\ldots, nm)`.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: C.degrees()\n (4, 8, 12)\n sage: S = ColoredPermutations(1, 3)\n sage: S.degrees()\n (2, 3)\n\n We now check that the product of the degrees is equal to the\n cardinality of ``self``::\n\n sage: prod(C.degrees()) == C.cardinality()\n True\n sage: prod(S.degrees()) == S.cardinality()\n True\n '
start = (2 if (self._m == 1) else 1)
return tuple(((self._m * i) for i in range(start, (self._n + 1))))
def codegrees(self):
'\n Return the codegrees of ``self``.\n\n Let `G` be a complex reflection group. The codegrees\n `d_1^* \\leq d_2^* \\leq \\cdots \\leq d_{\\ell}^*` of `G` can be\n defined by:\n\n .. MATH::\n\n \\prod_{i=1}^{\\ell} (q - d_i^* - 1)\n = \\sum_{g \\in G} \\det(g) q^{\\dim(V^g)},\n\n where `V` is the natural complex vector space that `G` acts on\n and `\\ell` is the :meth:`rank`.\n\n If `m = 1`, then we are in the special case of the symmetric group\n and the codegrees are `(n-2, n-3, \\ldots 1, 0)`. Otherwise the degrees\n are `((n-1)m, (n-2)m, \\ldots, m, 0)`.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: C.codegrees()\n (8, 4, 0)\n sage: S = ColoredPermutations(1, 3)\n sage: S.codegrees()\n (1, 0)\n\n TESTS:\n\n We check the polynomial identity::\n\n sage: R.<q> = ZZ[]\n sage: C = ColoredPermutations(3, 2)\n sage: f = prod(q - ds - 1 for ds in C.codegrees())\n sage: d = lambda x: sum(1 for e in x.to_matrix().eigenvalues() if e == 1)\n sage: g = sum(det(x.to_matrix()) * q**d(x) for x in C) # needs sage.modules sage.rings.number_field\n sage: f == g # needs sage.modules sage.rings.number_field\n True\n '
last = ((self._n - 1) if (self._m == 1) else self._n)
return tuple(((self._m * i) for i in reversed(range(last))))
def number_of_reflection_hyperplanes(self):
'\n Return the number of reflection hyperplanes of ``self``.\n\n The number of reflection hyperplanes of a complex reflection\n group is equal to the sum of the codegrees plus the rank.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(1, 2)\n sage: C.number_of_reflection_hyperplanes()\n 1\n sage: C = ColoredPermutations(1, 3)\n sage: C.number_of_reflection_hyperplanes()\n 3\n sage: C = ColoredPermutations(4, 12)\n sage: C.number_of_reflection_hyperplanes()\n 276\n '
return (sum(self.codegrees()) + self.rank())
def fixed_point_polynomial(self, q=None):
"\n The fixed point polynomial of ``self``.\n\n The fixed point polynomial `f_G` of a complex reflection group `G`\n is counting the dimensions of fixed points subspaces:\n\n .. MATH::\n\n f_G(q) = \\sum_{w \\in W} q^{\\dim V^w}.\n\n Furthermore, let `d_1, d_2, \\ldots, d_{\\ell}` be the degrees of `G`,\n where `\\ell` is the :meth:`rank`. Then the fixed point polynomial\n is given by\n\n .. MATH::\n\n f_G(q) = \\prod_{i=1}^{\\ell} (q + d_i - 1).\n\n INPUT:\n\n - ``q`` -- (default: the generator of ``ZZ['q']``) the parameter `q`\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: C.fixed_point_polynomial()\n q^3 + 21*q^2 + 131*q + 231\n\n sage: S = ColoredPermutations(1, 3)\n sage: S.fixed_point_polynomial()\n q^2 + 3*q + 2\n\n TESTS:\n\n We check the against the degrees and codegrees::\n\n sage: R.<q> = ZZ[]\n sage: C = ColoredPermutations(4, 3)\n sage: C.fixed_point_polynomial(q) == prod(q + d - 1 for d in C.degrees())\n True\n "
if (q is None):
q = PolynomialRing(ZZ, 'q').gen(0)
return prod((((q + d) - 1) for d in self.degrees()))
def is_well_generated(self):
'\n Return if ``self`` is a well-generated complex reflection group.\n\n A complex reflection group `G` is well-generated if it is\n generated by `\\ell` reflections. Equivalently, `G` is well-generated\n if `d_i + d_i^* = d_{\\ell}` for all `1 \\leq i \\leq \\ell`.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(4, 3)\n sage: C.is_well_generated()\n True\n sage: C = ColoredPermutations(2, 8)\n sage: C.is_well_generated()\n True\n sage: C = ColoredPermutations(1, 4)\n sage: C.is_well_generated()\n True\n '
deg = self.degrees()
codeg = self.codegrees()
return all(((deg[(- 1)] == (d + dstar)) for (d, dstar) in zip(deg, codeg)))
Element = ColoredPermutation
|
class SignedPermutation(ColoredPermutation, metaclass=InheritComparisonClasscallMetaclass):
'\n A signed permutation.\n '
@staticmethod
def __classcall_private__(cls, pi):
'\n Create a signed permutation.\n\n EXAMPLES::\n\n sage: SignedPermutation([2, 1, 3])\n [2, 1, 3]\n\n sage: SignedPermutation([2, 1, -3])\n [2, 1, -3]\n\n sage: SignedPermutation((2,1,-3))\n [2, 1, -3]\n\n sage: SignedPermutation(range(1,4))\n [1, 2, 3]\n '
return SignedPermutations(len(list(pi)))(pi)
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: S = SignedPermutations(4)\n sage: s1,s2,s3,s4 = S.gens()\n sage: s4*s1*s2*s3*s4\n [-4, 1, 2, -3]\n '
return repr(list(self))
_latex_ = _repr_
def _mul_(self, other):
'\n Multiply ``self`` and ``other``.\n\n EXAMPLES::\n\n sage: S = SignedPermutations(4)\n sage: s1,s2,s3,s4 = S.gens()\n sage: x = s4*s1*s2*s3*s4; x\n [-4, 1, 2, -3]\n sage: x * x\n [3, -4, 1, -2]\n\n ::\n\n sage: s1*s2*s1 == s1*s2*s1\n True\n sage: s3*s4*s3*s4 == s4*s3*s4*s3\n True\n '
colors = tuple(((c * other._colors[(val - 1)]) for (c, val) in zip(self._colors, self._perm)))
p = self._perm._left_to_right_multiply_on_right(other._perm)
return self.__class__(self.parent(), colors, p)
def __invert__(self):
'\n Return the inverse of ``self``.\n\n EXAMPLES::\n\n sage: S = SignedPermutations(4)\n sage: s1,s2,s3,s4 = S.gens()\n sage: x = s4*s1*s2*s3*s4\n sage: ~x # indirect doctest\n [2, 3, -4, -1]\n sage: x * ~x == S.one()\n True\n '
ip = (~ self._perm)
return self.__class__(self.parent(), tuple((self._colors[(i - 1)] for i in ip)), ip)
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: S = SignedPermutations(4)\n sage: s1,s2,s3,s4 = S.gens()\n sage: x = s4*s1*s2*s3*s4\n sage: [a for a in x]\n [-4, 1, 2, -3]\n '
for (c, p) in zip(self._colors, self._perm):
(yield (c * p))
def __getitem__(self, key):
'\n Return the specified element in the one line form of ``self``.\n\n EXAMPLES::\n\n sage: pi = SignedPermutation([-4, 5, -1, 2, -3])\n sage: pi[-1]\n -3\n sage: pi[1::2]\n [5, 2]\n '
if isinstance(key, slice):
return [(c * v) for (c, v) in zip(self._colors[key], self._perm[key])]
return (self._colors[key] * self._perm[key])
def __call__(self, i):
'\n Return the image of the integer ``i`` in ``self``.\n\n EXAMPLES::\n\n sage: pi = SignedPermutations(7)([2,-1,4,-6,-5,-3,7])\n sage: pi(2)\n -1\n sage: pi(-2)\n 1\n sage: pi(7)\n 7\n sage: pi(-7)\n -7\n sage: [pi(i) for i in range(1,8)]\n [2, -1, 4, -6, -5, -3, 7]\n sage: [pi(-i) for i in range(1,8)]\n [-2, 1, -4, 6, 5, 3, -7]\n '
if ((i in ZZ) and (1 <= abs(i) <= len(self))):
i = ZZ(i)
if (i < 0):
return ((- self._colors[((- i) - 1)]) * self._perm[((- i) - 1)])
return (self._colors[(i - 1)] * self._perm[(i - 1)])
raise TypeError(('i (= %s) must equal +/- an integer between %s and %s' % (i, 1, len(self))))
def to_matrix(self):
'\n Return a matrix of ``self``.\n\n EXAMPLES::\n\n sage: S = SignedPermutations(4)\n sage: s1,s2,s3,s4 = S.gens()\n sage: x = s4*s1*s2*s3*s4\n sage: M = x.to_matrix(); M # needs sage.modules\n [ 0 1 0 0]\n [ 0 0 1 0]\n [ 0 0 0 -1]\n [-1 0 0 0]\n\n The matrix multiplication is in the *opposite* order::\n\n sage: m1,m2,m3,m4 = [g.to_matrix() for g in S.gens()] # needs sage.modules\n sage: M == m4 * m3 * m2 * m1 * m4 # needs sage.modules\n True\n '
return (self._perm.to_matrix() * diagonal_matrix(self._colors))
def has_left_descent(self, i):
'\n Return ``True`` if ``i`` is a left descent of ``self``.\n\n EXAMPLES::\n\n sage: S = SignedPermutations(4)\n sage: s1,s2,s3,s4 = S.gens()\n sage: x = s4*s1*s2*s3*s4\n sage: [x.has_left_descent(i) for i in S.index_set()]\n [True, False, False, True]\n '
n = self.parent()._n
if (i == n):
return (self._colors[(- 1)] == (- 1))
if (self._colors[(i - 1)] == (- 1)):
return ((self._colors[i] == 1) or (self._perm[(i - 1)] < self._perm[i]))
return ((self._colors[i] == 1) and (self._perm[(i - 1)] > self._perm[i]))
def to_cycles(self, singletons=True, use_min=True, negative_cycles=True):
'\n Return the signed permutation ``self`` as a list of disjoint cycles.\n\n The cycles are returned in the order of increasing smallest\n elements, and each cycle is returned as a tuple which starts\n with its smallest positive element.\n\n INPUT:\n\n - ``singletons`` -- (default: ``True``) whether to include singleton\n cycles or not\n - ``use_min`` -- (default: ``True``) if ``False``, the cycles are\n returned in the order of increasing *largest* (not smallest)\n elements, and each cycle starts with its largest element\n - ``negative_cycles`` -- (default: ``True``) if ``False``, for any\n two cycles `C^{\\pm} = \\{\\pm c_1, \\ldots, \\pm c_k\\}` such that\n `C^+ \\neq C^-`, this does not include the cycle `C^-`\n\n .. WARNING::\n\n The arugment ``negative_cycles`` does not refer to the usual\n definition of a negative cycle; see :meth:`cycle_type`.\n\n EXAMPLES::\n\n sage: pi = SignedPermutations(7)([2,-1,4,-6,-5,-3,7])\n sage: pi.to_cycles()\n [(1, 2, -1, -2), (3, 4, -6), (-3, -4, 6), (5, -5), (7,), (-7,)]\n sage: pi.to_cycles(singletons=False)\n [(1, 2, -1, -2), (3, 4, -6), (-3, -4, 6), (5, -5)]\n sage: pi.to_cycles(negative_cycles=False)\n [(1, 2, -1, -2), (3, 4, -6), (5, -5), (7,)]\n sage: pi.to_cycles(singletons=False, negative_cycles=False)\n [(1, 2, -1, -2), (3, 4, -6), (5, -5)]\n sage: pi.to_cycles(use_min=False)\n [(7,), (-7,), (6, -3, -4), (-6, 3, 4), (5, -5), (2, -1, -2, 1)]\n sage: pi.to_cycles(singletons=False, use_min=False)\n [(6, -3, -4), (-6, 3, 4), (5, -5), (2, -1, -2, 1)]\n '
cycles = []
l = self._perm[:]
if use_min:
groundset = range(len(l))
else:
groundset = reversed(range(len(l)))
for i in groundset:
if (not l[i]):
continue
cycle_first = (i + 1)
cycle = [cycle_first]
(l[i], next_val) = (False, l[i])
s = self._colors[i]
add_neg = True
while (next_val != cycle_first):
cycle.append((s * next_val))
s *= self._colors[(next_val - 1)]
(l[(next_val - 1)], next_val) = (False, l[(next_val - 1)])
if (s != 1):
cycle.extend([(- e) for e in cycle])
add_neg = False
if (singletons or (len(cycle) > 1)):
cycles.append(tuple(cycle))
if (negative_cycles and add_neg):
cycles.append(tuple([(- e) for e in cycle]))
return cycles
def cycle_type(self):
'\n Return a pair of partitions of ``len(self)`` corresponding to the\n signed cycle type of ``self``.\n\n A *cycle* is a tuple `C = (c_0, \\ldots, c_{k-1})` with\n `\\pi(c_i) = c_{i+1}` for `0 \\leq i < k` and `\\pi(c_{k-1}) = c_0`.\n If `C` is a cycle, `\\overline{C} = (-c_0, \\ldots, -c_{k-1})` is\n also a cycle. A cycle is *negative*, if `C = \\overline{C}` up\n to cyclic reordering. In this case, `k` is necessarily even\n and the length of `C` is `k/2`. A *positive cycle* is a pair\n `C \\overline{C}`, its length is `k`.\n\n Let `\\alpha` be the partition whose parts are the lengths of the\n positive cycles and let `\\beta` be the partition whose parts are\n the lengths of the negative cycles. Then `(\\alpha, \\beta)` is\n the cycle type of `\\pi`.\n\n EXAMPLES::\n\n sage: G = SignedPermutations(7)\n sage: pi = G([2, -1, 4, -6, -5, -3, 7])\n sage: pi.cycle_type()\n ([3, 1], [2, 1])\n\n sage: G = SignedPermutations(5)\n sage: all(pi.cycle_type().size() == 5 for pi in G)\n True\n sage: set(pi.cycle_type() for pi in G) == set(PartitionTuples(2, 5))\n True\n '
cycles = self.to_cycles(negative_cycles=False)
pos_cycles = []
neg_cycles = []
for C in cycles:
if ((not (len(C) % 2)) and (C[0] == (- C[(len(C) // 2)]))):
neg_cycles.append(C)
else:
pos_cycles.append(C)
pos_type = [len(C) for C in pos_cycles]
pos_type.sort(reverse=True)
neg_type = [(len(C) // 2) for C in neg_cycles]
neg_type.sort(reverse=True)
from sage.combinat.partition_tuple import PartitionTuples
PT = PartitionTuples(2, self.parent()._n)
return PT([pos_type, neg_type])
def order(self):
'\n Return the multiplicative order of the signed permutation.\n\n EXAMPLES::\n\n sage: pi = SignedPermutations(7)([2,-1,4,-6,-5,-3,7])\n sage: pi.to_cycles(singletons=False)\n [(1, 2, -1, -2), (3, 4, -6), (-3, -4, 6), (5, -5)]\n sage: pi.order()\n 12\n '
return lcm((len(c) for c in self.to_cycles(singletons=False, negative_cycles=False)))
|
class SignedPermutations(ColoredPermutations):
'\n Group of signed permutations.\n\n The group of signed permutations is also known as the hyperoctahedral\n group, the Coxeter group of type `B_n`, and the 2-colored permutation\n group. Thus it can be constructed as the wreath product `S_2 \\wr S_n`.\n\n EXAMPLES::\n\n sage: S = SignedPermutations(4)\n sage: s1,s2,s3,s4 = S.group_generators()\n sage: x = s4*s1*s2*s3*s4; x\n [-4, 1, 2, -3]\n sage: x^4 == S.one()\n True\n\n This is a finite Coxeter group of type `B_n`::\n\n sage: S.canonical_representation() # needs sage.modules\n Finite Coxeter group over Number Field in a with defining polynomial x^2 - 2\n with a = 1.414213562373095? with Coxeter matrix:\n [1 3 2 2]\n [3 1 3 2]\n [2 3 1 4]\n [2 2 4 1]\n sage: S.long_element()\n [-1, -2, -3, -4]\n sage: S.long_element().reduced_word()\n [1, 2, 1, 3, 2, 1, 4, 3, 2, 1, 4, 3, 2, 4, 3, 4]\n\n We can also go between the 2-colored permutation group::\n\n sage: C = ColoredPermutations(2, 3)\n sage: S = SignedPermutations(3)\n sage: S.an_element()\n [-3, 1, 2]\n sage: C(S.an_element())\n [[1, 0, 0], [3, 1, 2]]\n sage: S(C(S.an_element())) == S.an_element()\n True\n sage: S(C.an_element())\n [-3, 1, 2]\n\n There is also the natural lift from permutations::\n\n sage: P = Permutations(3)\n sage: x = S(P.an_element()); x\n [3, 1, 2]\n sage: x.parent()\n Signed permutations of 3\n\n REFERENCES:\n\n - :wikipedia:`Hyperoctahedral_group`\n '
def __init__(self, n):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: S = SignedPermutations(4)\n sage: TestSuite(S).run()\n '
ColoredPermutations.__init__(self, 2, n)
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: SignedPermutations(4)\n Signed permutations of 4\n '
return 'Signed permutations of {}'.format(self._n)
@cached_method
def one(self):
'\n Return the identity element of ``self``.\n\n EXAMPLES::\n\n sage: S = SignedPermutations(4)\n sage: S.one()\n [1, 2, 3, 4]\n '
return self.element_class(self, ([ZZ.one()] * self._n), self._P.identity())
def random_element(self):
'\n Return an element drawn uniformly at random.\n\n EXAMPLES::\n\n sage: C = SignedPermutations(7)\n sage: s = C.random_element(); s # random\n [7, 6, -4, -5, 2, 3, -1]\n sage: s in C\n True\n '
return self.element_class(self, [choice([ZZ.one(), (- ZZ.one())]) for _ in range(self._n)], self._P.random_element())
def simple_reflection(self, i):
'\n Return the ``i``-th simple reflection of ``self``.\n\n EXAMPLES::\n\n sage: S = SignedPermutations(4)\n sage: S.simple_reflection(1)\n [2, 1, 3, 4]\n sage: S.simple_reflection(4)\n [1, 2, 3, -4]\n '
if (i not in self.index_set()):
raise ValueError('i must be in the index set')
if (i < self._n):
p = list(range(1, (self._n + 1)))
p[(i - 1)] = (i + 1)
p[i] = i
return self.element_class(self, ([ZZ.one()] * self._n), self._P(p))
temp = ([ZZ.one()] * self._n)
temp[(- 1)] = (- ZZ.one())
return self.element_class(self, temp, self._P.identity())
def _element_constructor_(self, x):
'\n Construct an element of ``self`` from ``x``.\n\n TESTS::\n\n sage: S = SignedPermutations(3)\n sage: x = S([(+1,1), (-1,3), (-1,2)]); x\n [1, -3, -2]\n sage: x == S([[+1,-1,-1], [1,3,2]])\n True\n sage: x == S([1, -3, -2])\n True\n\n sage: S = SignedPermutations(0)\n sage: S([]) == list(S)[0]\n True\n\n sage: T = SignedPermutation(range(1,4))\n sage: SignedPermutations(3)(T)\n [1, 2, 3]\n '
if (isinstance(x, self.element_class) and (x.parent() is self)):
return self
x = list(x)
if (x and isinstance(x[0], tuple)):
c = []
p = []
for k in x:
if (len(k) != 2):
raise ValueError('input must be pairs (sign, element)')
if ((k[0] != 1) and (k[0] != (- 1))):
raise ValueError('the sign must be +1 or -1')
c.append(ZZ(k[0]))
p.append(k[1])
return self.element_class(self, c, self._P(p))
if (len(x) == self._n):
c = []
p = []
one = ZZ.one()
for v in x:
if (v > 0):
c.append(one)
p.append(v)
else:
c.append((- one))
p.append((- v))
return self.element_class(self, c, self._P(p))
if (len(x) != 2):
raise ValueError('input must be a pair of a list of signs and a permutation')
if any((((s != 1) and (s != (- 1))) for s in x[0])):
raise ValueError('the sign must be +1 or -1')
return self.element_class(self, [ZZ(v) for v in x[0]], self._P(x[1]))
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: S = SignedPermutations(2)\n sage: [x for x in S]\n [[1, 2], [1, -2], [-1, 2], [-1, -2],\n [2, 1], [2, -1], [-2, 1], [-2, -1]]\n '
pmone = [ZZ.one(), (- ZZ.one())]
for p in self._P:
for c in itertools.product(pmone, repeat=self._n):
(yield self.element_class(self, c, p))
def _coerce_map_from_(self, C):
'\n Return a coerce map from ``C`` if it exists and ``None`` otherwise.\n\n EXAMPLES::\n\n sage: C = ColoredPermutations(2, 3)\n sage: S = SignedPermutations(3)\n sage: S.has_coerce_map_from(C)\n True\n\n sage: C = ColoredPermutations(4, 3)\n sage: S.has_coerce_map_from(C)\n False\n\n sage: P = Permutations(3)\n sage: C.has_coerce_map_from(P)\n True\n sage: P = Permutations(4)\n sage: C.has_coerce_map_from(P)\n False\n '
if (isinstance(C, Permutations) and (C.n == self._n)):
return (lambda P, x: P.element_class(P, ([1] * P._n), x))
if (isinstance(C, ColoredPermutations) and (C._n == self._n) and (C._m == 2)):
return (lambda P, x: P.element_class(P, [(1 if (v == 0) else (- 1)) for v in x._colors], x._perm))
return super()._coerce_map_from_(C)
def long_element(self, index_set=None):
'\n Return the longest element of ``self``, or of the\n parabolic subgroup corresponding to the given ``index_set``.\n\n INPUT:\n\n - ``index_set`` -- (optional) a subset (as a list or iterable)\n of the nodes of the indexing set\n\n EXAMPLES::\n\n sage: S = SignedPermutations(4)\n sage: S.long_element()\n [-1, -2, -3, -4]\n\n TESTS:\n\n Check that this is the element of maximal length (:trac:`25200`)::\n\n sage: S = SignedPermutations(4)\n sage: S.long_element().length() == max(x.length() for x in S)\n True\n sage: all(SignedPermutations(n).long_element().length() == n^2\n ....: for n in range(2,10))\n True\n '
if (index_set is not None):
return super().long_element()
return self.element_class(self, ([(- ZZ.one())] * self._n), self._P.one())
def conjugacy_class_representative(self, nu):
'\n Return a permutation with (signed) cycle type ``nu``.\n\n EXAMPLES::\n\n sage: G = SignedPermutations(4)\n sage: for nu in PartitionTuples(2, 4):\n ....: print(nu, G.conjugacy_class_representative(nu))\n ....: assert nu == G.conjugacy_class_representative(nu).cycle_type(), nu\n ([4], []) [2, 3, 4, 1]\n ([3, 1], []) [2, 3, 1, 4]\n ([2, 2], []) [2, 1, 4, 3]\n ([2, 1, 1], []) [2, 1, 3, 4]\n ([1, 1, 1, 1], []) [1, 2, 3, 4]\n ([3], [1]) [2, 3, 1, -4]\n ([2, 1], [1]) [2, 1, 3, -4]\n ([1, 1, 1], [1]) [1, 2, 3, -4]\n ([2], [2]) [2, 1, 4, -3]\n ([2], [1, 1]) [2, 1, -3, -4]\n ([1, 1], [2]) [1, 2, 4, -3]\n ([1, 1], [1, 1]) [1, 2, -3, -4]\n ([1], [3]) [1, 3, 4, -2]\n ([1], [2, 1]) [1, 3, -2, -4]\n ([1], [1, 1, 1]) [1, -2, -3, -4]\n ([], [4]) [2, 3, 4, -1]\n ([], [3, 1]) [2, 3, -1, -4]\n ([], [2, 2]) [2, -1, 4, -3]\n ([], [2, 1, 1]) [2, -1, -3, -4]\n ([], [1, 1, 1, 1]) [-1, -2, -3, -4]\n\n TESTS::\n\n sage: all(nu == SignedPermutations(n).conjugacy_class_representative(nu).cycle_type()\n ....: for n in range(1, 6) for nu in PartitionTuples(2, n))\n True\n '
from sage.combinat.partition_tuple import PartitionTuple
nu = PartitionTuple(nu)
if (nu.size() != self._n):
raise ValueError(('the size of the partition pair (=%s) must equal the rank (=%s)' % (nu.size(), self._n)))
(la, mu) = nu
cyc = []
cnt = 0
for i in la:
cyc += ([tuple(range((cnt + 1), ((cnt + i) + 1)))] + [tuple(range(((- cnt) - 1), (((- cnt) - i) - 1), (- 1)))])
cnt += i
for i in mu:
cyc += [(tuple(range((cnt + 1), ((cnt + i) + 1))) + tuple(range(((- cnt) - 1), (((- cnt) - i) - 1), (- 1))))]
cnt += i
p = ([None] * self._n)
for c in cyc:
for i in range((len(c) - 1)):
if (c[i] > 0):
p[(c[i] - 1)] = c[(i + 1)]
if (c[(- 1)] > 0):
p[(c[(- 1)] - 1)] = c[0]
return self(p)
Element = SignedPermutation
|
def bell_number(n, algorithm='flint', **options) -> Integer:
"\n Return the `n`-th Bell number.\n\n This is the number of ways to partition a set\n of `n` elements into pairwise disjoint nonempty subsets.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n - ``algorithm`` -- (Default: ``'flint'``) any one of the following:\n\n - ``'dobinski'`` -- Use Dobinski's formula implemented in Sage\n\n - ``'flint'`` -- Wrap FLINT's ``arith_bell_number``\n\n - ``'gap'`` -- Wrap GAP's ``Bell``\n\n - ``'mpmath'`` -- Wrap mpmath's ``bell``\n\n .. WARNING::\n\n When using the mpmath algorithm to compute Bell numbers and you specify\n ``prec``, it can return incorrect results due to low precision. See\n the examples section.\n\n Let `B_n` denote the `n`-th Bell number. Dobinski's formula is:\n\n .. MATH::\n\n B_n = e^{-1} \\sum_{k=0}^{\\infty} \\frac{k^n}{k!}.\n\n To show our implementation of Dobinski's method works, suppose that `n \\geq 5`\n and let `k_0` be the smallest positive integer such that `\\frac{k_0^n}{k_0!} < 1`.\n Note that `k_0 > n` and `k_0 \\leq 2n` because we can prove that\n `\\frac{(2n)^n}{(2n)!} < 1` by Stirling.\n\n If `k > k_0`, then we have `\\frac{k^n}{k!} < \\frac{1}{2^{k-k_0}}`.\n We show this by induction:\n let `c_k = \\frac{k^n}{k!}`, if `k > n` then\n\n .. MATH::\n\n \\frac{c_{k+1}}{c_k} = \\frac{(1+k^{-1})^n}{k+1} < \\frac{(1+n^{-1})^n}{n}\n < \\frac{1}{2}.\n\n The last inequality can easily be checked numerically for `n \\geq 5`.\n\n Using this, we can see that `\\frac{c_k}{c_{k_0}} < \\frac{1}{2^{k-k_0}}`\n for `k > k_0 > n`. So summing this it gives that `\\sum_{k=k_0+1}^{\\infty}\n \\frac{k^n}{k!} < 1`, and hence\n\n .. MATH::\n\n B_n = e^{-1} \\left( \\sum_{k=0}^{k_0} \\frac{k^n}{k!} + E_1 \\right)\n = e^{-1} \\sum_{k=0}^{k_0} \\frac{k^n}{k!} + E_2,\n\n where `0 < E_1 < 1` and `0 < E_2 < e^{-1}`. Next we have for any `q > 0`\n\n .. MATH::\n\n \\sum_{k=0}^{k_0} \\frac{k^n}{k!} = \\frac{1}{q} \\sum_{k=0}^{k_0} \\left\\lfloor\n \\frac{q k^n}{k!} \\right\\rfloor + \\frac{E_3}{q}\n\n where `0 \\leq E_3 \\leq k_0 + 1 \\leq 2n + 1`. Let `E_4 = \\frac{E_3}{q}`\n and let `q = 2n + 1`. We find `0 \\leq E_4 \\leq 1`. These two bounds give:\n\n .. MATH::\n\n \\begin{aligned}\n B_n & = \\frac{e^{-1}}{q} \\sum_{k=0}^{k_0} \\left\\lfloor\n \\frac{q k^n}{k!} \\right\\rfloor + e^{-1} E_4 + E_2 \\\\\n & = \\frac{e^{-1}}{q} \\sum_{k=0}^{k_0} \\left\\lfloor \\frac{q k^n}{k!}\n \\right\\rfloor + E_5\n \\end{aligned}\n\n where\n\n .. MATH::\n\n 0 < E_5 = e^{-1} E_4 + E_2 \\leq e^{-1} + e^{-1} < \\frac{3}{4}.\n\n It follows that\n\n .. MATH::\n\n B_n = \\left\\lceil \\frac{e^{-1}}{q} \\sum_{k=0}^{k_0} \\left\\lfloor\n \\frac{q k^n}{k!} \\right\\rfloor \\right\\rceil.\n\n Now define\n\n .. MATH::\n\n b = \\sum_{k=0}^{k_0} \\left\\lfloor \\frac{q k^n}{k!} \\right\\rfloor.\n\n This `b` can be computed exactly using integer arithmetic.\n To avoid the costly integer division by `k!`, we collect\n more terms and do only one division, for example with 3 terms:\n\n .. MATH::\n\n \\frac{k^n}{k!} + \\frac{(k+1)^n}{(k+1)!} + \\frac{(k+2)^n}{(k+2)!}\n = \\frac{k^n (k+1)(k+2) + (k+1)^n (k+2) + (k+2)^n}{(k+2)!}\n\n In the implementation, we collect `\\sqrt{n}/2` terms.\n\n To actually compute `B_n` from `b`,\n we let `p = \\lfloor \\log_2(b) \\rfloor + 1` such that `b < 2^p` and\n we compute with `p` bits of precision.\n This implies that `b` (and `q < b`) can be represented exactly.\n\n We compute `\\frac{e^{-1}}{q} b`, rounding down, and we must have an\n absolute error of at most `1/4` (given that `E_5 < 3/4`).\n This means that we need a relative error of at most\n\n .. MATH::\n\n \\frac{e q}{4 b} > \\frac{(e q)/4}{2^p} > \\frac{7}{2^p}\n\n (assuming `n \\geq 5`).\n With a precision of `p` bits and rounding down, every rounding\n has a relative error of at most `2^{1-p} = 2/2^p`.\n Since we do 3 roundings (`b` and `q` do not require rounding),\n we get a relative error of at most `6/2^p`.\n All this implies that the precision of `p` bits is sufficient.\n\n EXAMPLES::\n\n sage: # needs sage.libs.flint\n sage: bell_number(10)\n 115975\n sage: bell_number(2)\n 2\n sage: bell_number(-10)\n Traceback (most recent call last):\n ...\n ArithmeticError: Bell numbers not defined for negative indices\n sage: bell_number(1)\n 1\n sage: bell_number(1/3)\n Traceback (most recent call last):\n ...\n TypeError: no conversion of this rational to integer\n\n When using the mpmath algorithm, we are required have mpmath's precision\n set to at least `\\log_2(B_n)` bits. If upon computing the Bell number the\n first time, we deem the precision too low, we use our guess to\n (temporarily) raise mpmath's precision and the Bell number is recomputed. ::\n\n sage: k = bell_number(30, 'mpmath'); k # needs mpmath\n 846749014511809332450147\n sage: k == bell_number(30) # needs mpmath sage.libs.flint\n True\n\n If you knows what precision is necessary before computing the Bell number,\n you can use the ``prec`` option::\n\n sage: k2 = bell_number(30, 'mpmath', prec=30); k2 # needs mpmath\n 846749014511809332450147\n sage: k == k2 # needs mpmath\n True\n\n .. WARNING::\n\n Running mpmath with the precision set too low can result in\n incorrect results::\n\n sage: k = bell_number(30, 'mpmath', prec=15); k # needs mpmath\n 846749014511809388871680\n sage: k == bell_number(30) # needs mpmath sage.libs.flint\n False\n\n TESTS::\n\n sage: all(bell_number(n) == bell_number(n,'dobinski') for n in range(100)) # needs sage.libs.flint\n True\n sage: all(bell_number(n) == bell_number(n,'gap') for n in range(100)) # needs sage.libs.flint sage.libs.gap\n True\n sage: all(bell_number(n) == bell_number(n,'mpmath', prec=500) # needs mpmath sage.libs.flint\n ....: for n in range(200, 220))\n True\n\n AUTHORS:\n\n - Robert Gerbicz\n\n - Jeroen Demeyer: improved implementation of Dobinski formula with\n more accurate error estimates (:trac:`17157`)\n\n REFERENCES:\n\n - :wikipedia:`Bell_number`\n - http://fredrik-j.blogspot.com/2009/03/computing-generalized-bell-numbers.html\n - http://mathworld.wolfram.com/DobinskisFormula.html\n "
n = ZZ(n)
if (n < 0):
raise ArithmeticError('Bell numbers not defined for negative indices')
if (algorithm == 'mpmath'):
from sage.libs.mpmath.all import bell, mp, mag
old_prec = mp.dps
if ('prec' in options):
mp.dps = options['prec']
ret = ZZ(int(bell(n)))
mp.dps = old_prec
return ret
ret_mp = bell(n)
p = (mag(ret_mp) + 10)
if (p > mp.dps):
mp.dps = p
ret = ZZ(int(bell(n)))
mp.dps = old_prec
return ret
return ZZ(int(ret_mp))
elif (algorithm == 'flint'):
import sage.libs.flint.arith
return sage.libs.flint.arith.bell_number(n)
elif (algorithm == 'gap'):
from sage.libs.gap.libgap import libgap
return libgap.Bell(n).sage()
elif (algorithm == 'dobinski'):
if (n < 4):
return Integer((1, 1, 2, 5)[n])
b = ZZ.zero()
fact = k = ZZ.one()
q = ((2 * n) + 1)
si = (Integer(n).sqrtrem()[0] // 2)
while True:
partfact = ZZ.one()
v = ZZ.zero()
for i in range((si - 1), (- 1), (- 1)):
v += (partfact * ((k + i) ** n))
partfact *= (k + i)
fact *= partfact
v = ((q * v) // fact)
if (not v):
break
b += v
k += si
from sage.rings.real_mpfr import RealField
R = RealField((b.exact_log(2) + 1), rnd='RNDD')
return ((R((- 1)).exp() / q) * b).ceil()
raise ValueError(('unknown algorithm %r' % algorithm))
|
def catalan_number(n):
'\n Return the `n`-th Catalan number.\n\n The `n`-th Catalan number is given\n directly in terms of binomial coefficients by\n\n .. MATH::\n\n C_n = \\frac{1}{n+1}\\binom{2n}{n} = \\frac{(2n)!}{(n+1)!\\,n!}\n \\qquad\\mbox{ for }\\quad n\\ge 0.\n\n Consider the set `S = \\{ 1, ..., n \\}`. A noncrossing\n partition of `S` is a partition in which no two blocks\n "cross" each other, i.e., if `a` and `b` belong to one block and\n `x` and `y` to another, they are not arranged in the order `axby`.\n `C_n` is the number of noncrossing partitions of the set\n `S`. There are many other interpretations (see REFERENCES).\n\n When `n=-1`, this function returns the limit value `-1/2`. For\n other `n<0` it returns `0`.\n\n INPUT:\n\n - ``n`` -- integer\n\n OUTPUT:\n\n integer\n\n EXAMPLES::\n\n sage: [catalan_number(i) for i in range(7)]\n [1, 1, 2, 5, 14, 42, 132]\n sage: x = (QQ[[\'x\']].0).O(8)\n sage: (-1/2)*sqrt(1 - 4*x)\n -1/2 + x + x^2 + 2*x^3 + 5*x^4 + 14*x^5 + 42*x^6 + 132*x^7 + O(x^8)\n sage: [catalan_number(i) for i in range(-7,7)]\n [0, 0, 0, 0, 0, 0, -1/2, 1, 1, 2, 5, 14, 42, 132]\n sage: [catalan_number(n).mod(2) for n in range(16)]\n [1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1]\n\n REFERENCES:\n\n - :wikipedia:`Catalan_number`\n\n - http://www-history.mcs.st-andrews.ac.uk/~history/Miscellaneous/CatalanNumbers/catalan.html\n '
n = ZZ(n)
if (n < (- 1)):
return ZZ.zero()
if (n == (- 1)):
return QQ(((- 1), 2))
return (2 * n).binomial(n).divide_knowing_divisible_by((n + 1))
|
def narayana_number(n: Integer, k: Integer) -> Integer:
'\n Return the Narayana number of index ``(n, k)``.\n\n For every integer `n \\geq 1`, the sum of Narayana numbers `\\sum_k N_{n,k}`\n is the Catalan number `C_n`.\n\n INPUT:\n\n - ``n`` -- an integer\n\n - ``k`` -- an integer between ``0`` and ``n - 1``\n\n OUTPUT:\n\n an integer\n\n EXAMPLES::\n\n sage: from sage.combinat.combinat import narayana_number\n sage: [narayana_number(3, i) for i in range(3)]\n [1, 3, 1]\n sage: sum(narayana_number(7,i) for i in range(7)) == catalan_number(7)\n True\n\n REFERENCES:\n\n - :wikipedia:`Narayana_number`\n '
n = ZZ(n)
if (n <= 0):
return ZZ.zero()
return (n.binomial((k + 1)) * n.binomial(k)).divide_knowing_divisible_by(n)
|
def euler_number(n, algorithm='flint') -> Integer:
"\n Return the `n`-th Euler number.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n - ``algorithm`` -- (Default: ``'flint'``) any one of the following:\n\n - ``'maxima'`` -- Wraps Maxima's ``euler``.\n\n - ``'flint'`` -- Wrap FLINT's ``arith_euler_number``\n\n EXAMPLES::\n\n sage: [euler_number(i) for i in range(10)] # needs sage.libs.flint\n [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0]\n sage: x = PowerSeriesRing(QQ, 'x').gen().O(10)\n sage: 2/(exp(x)+exp(-x))\n 1 - 1/2*x^2 + 5/24*x^4 - 61/720*x^6 + 277/8064*x^8 + O(x^10)\n sage: [euler_number(i)/factorial(i) for i in range(11)] # needs sage.libs.flint\n [1, 0, -1/2, 0, 5/24, 0, -61/720, 0, 277/8064, 0, -50521/3628800]\n sage: euler_number(-1)\n Traceback (most recent call last):\n ...\n ValueError: n (=-1) must be a nonnegative integer\n\n TESTS::\n\n sage: euler_number(6, 'maxima') # needs sage.symbolic\n -61\n\n REFERENCES:\n\n - :wikipedia:`Euler_number`\n "
n = ZZ(n)
if (n < 0):
raise ValueError(('n (=%s) must be a nonnegative integer' % n))
if (algorithm == 'maxima'):
return ZZ(maxima.euler(n))
elif (algorithm == 'flint'):
import sage.libs.flint.arith
return sage.libs.flint.arith.euler_number(n)
else:
raise ValueError("algorithm must be 'flint' or 'maxima'")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.