code stringlengths 17 6.64M |
|---|
def thwart_lemma_4_1(k, n, m, explain_construction=False):
'\n Returns an `OA(k,nm+4(n-2))`.\n\n Implements Lemma 4.1 from [Thwarts]_.\n\n If `n\\equiv 0,1\\pmod{3}` is a prime power, then there exists a truncated\n `OA(n+1,n)` whose last four columns have size `n-2` and intersect every\n block on `1,3` or `4` values. Consequently, if there exists an\n `OA(k,m+1)`, `OA(k,m+3)`, `OA(k,m+4)` and a `OA(k,n-2)` then there\n exists an `OA(k,nm+4(n-2)`\n\n Proof: form the transversal design by removing one point of the\n `AG(2,3)` (Affine Geometry) contained in the Desarguesian Projective\n Plane `PG(2,n)`.\n\n The affine geometry on 9 points contained in the projective geometry\n `PG(2,n)` is given explicitly in [OS64]_ (Thanks to Julian R. Abel for\n finding the reference!).\n\n INPUT:\n\n - ``k,n,m`` (integers)\n\n - ``explain_construction`` (boolean) -- return a string describing\n the construction.\n\n .. SEEALSO::\n\n - :func:`~sage.combinat.designs.orthogonal_arrays_find_recursive.find_thwart_lemma_4_1`\n\n EXAMPLES::\n\n sage: print(designs.orthogonal_arrays.explain_construction(10,408)) # needs sage.schemes\n Lemma 4.1 with n=13,m=28 from:\n Charles J.Colbourn, Jeffrey H. Dinitz, Mieczyslaw Wojtas,\n Thwarts in transversal designs,\n Designs, Codes and Cryptography 5, no. 3 (1995): 189-197.\n\n\n REFERENCES:\n\n .. [OS64] Finite projective planes with affine subplanes,\n T. G. Ostrom and F. A. Sherk.\n Canad. Math. Bull vol7 num.4 (1964)\n '
from sage.rings.finite_rings.finite_field_constructor import FiniteField
from sage.arith.misc import is_prime_power
from .block_design import DesarguesianProjectivePlaneDesign
from itertools import chain
if explain_construction:
return ((('Lemma 4.1 with n={},m={} from:\n' + ' Charles J.Colbourn, Jeffrey H. Dinitz, Mieczyslaw Wojtas,\n') + ' Thwarts in transversal designs,\n') + ' Designs, Codes and Cryptography 5, no. 3 (1995): 189-197.').format(n, m)
assert is_prime_power(n), 'n(={}) must be a prime power'
assert ((k + 4) <= (n + 1))
q = n
K = FiniteField(q, 'x')
relabel = {x: i for (i, x) in enumerate(K)}
PG = DesarguesianProjectivePlaneDesign(q, check=False, point_coordinates=False).blocks()
if ((q % 3) == 0):
t = K.one()
elif ((q % 3) == 1):
t = (K.multiplicative_generator() ** ((q - 1) // 3))
else:
raise ValueError('q(={}) must be congruent to 0 or 1 mod 3'.format(q))
points = [((1 + t), t, (1 + t)), (1, 1, 1), ((1 + t), t, t), (1, 1, 2), (0, 0, 1), (1, 0, 1), (0, 1, (1 + t)), (0, 1, 1), (1, 0, (- t))]
points = [[K(_) for _ in t] for t in points]
AG_2_3 = []
for (x, y, z) in points:
if (z != 0):
(x, y, z) = ((x / z), (y / z), (z / z))
AG_2_3.append((relabel[x] + (n * relabel[y])))
elif (y != 0):
(x, y, z) = ((x / y), (y / y), z)
AG_2_3.append(((q ** 2) + relabel[x]))
else:
AG_2_3.append(((q ** 2) + q))
AG_2_3 = set(AG_2_3)
assert all(((len(AG_2_3.intersection(B)) != 2) for B in PG))
p = list(AG_2_3)[0]
blocks = []
columns = []
for B in PG:
if (p not in B):
blocks.append(B)
else:
B.remove(p)
columns.append(B)
columns.sort(key=(lambda x: len(AG_2_3.intersection(x))))
for i in range(4):
columns[((- i) - 1)].sort(key=(lambda x: int((x in AG_2_3))))
relabel = {v: i for (i, v) in enumerate(chain(columns))}
TD = [sorted((relabel[x] for x in B)) for B in blocks]
OA = [[(x % q) for x in B[((- k) - 4):]] for B in TD]
for B in OA:
for i in range(4):
if (B[(k + i)] >= (n - 2)):
B[(k + i)] = None
return wilson_construction(OA, k, n, m, ([(n - 2)] * 4), check=False)
|
def three_factor_product(k, n1, n2, n3, check=False, explain_construction=False):
"\n Returns an `OA(k+1,n_1n_2n_3)`\n\n The three factor product construction from [DukesLing14]_ does the following:\n\n If `n_1\\leq n_2\\leq n_3` are such that there exists an\n `OA(k,n_1)`, `OA(k+1,n_2)` and `OA(k+1,n_3)`, then there exists a\n `OA(k+1,n_1n_2n_3)`.\n\n It works with a modified product of orthogonal arrays ([Rees93]_, [Rees00]_)\n which keeps track of parallel classes in the `OA` (the definition is given\n for transversal designs).\n\n A subset of blocks in an `TD(k,n)` is called a `c`-parallel class if\n every point is covered exactly `c` times. A 1-parallel class is a\n parallel class.\n\n The modified product:\n\n If there exists an `OA(k,n_1)`, and if there exists an `OA(k,n_2)` whose\n blocks are partitionned into `s` `n_1`-parallel classes and `n_2-sn_1`\n parallel classes, then there exists an `OA(k,n_1n_2)` whose blocks can\n be partitionned into `sn_1^2` parallel classes and\n `(n_1n_2-sn_1^2)/n_1=n_2-sn_1` `n_1`-parallel classes.\n\n Proof:\n\n - The product of the blocks of a parallel class with an `OA(k,n_1)`\n yields an `n_1`-parallel class of an `OA(k,n_1n_2)`.\n\n - The product of the blocks of a `n_1`-parallel class of `OA(k,n_2)`\n with an `OA(k,n_1)` can be done in such a way that it yields `n_1n_2`\n parallel classes of `OA(k,n_1n_2)`. Those classes cover exactly the\n pairs that would have been covered with the usual product.\n\n This can be achieved by simple cyclic permutations. Let us build the\n product of the `n_1`-parallel class `\\mathcal P\\subseteq OA(k,n_2)`\n with `OA(k,n_1)`: when computing the product of `P\\in\\mathcal P` with\n `B^1\\in OA(k,n_1)` the `i`-th coordinate should not be `(B^1_i,P_i)`\n but `(B^1_i+r,P_i)` (the sum is mod `n_1`) where `r` is the number of\n blocks of `\\mathcal P` we have already processed whose `i`-th\n coordinate is equal to `P_i` (note that `r< n_1` as `\\mathcal P` is\n `n_1`-parallel).\n\n With these tools, one can obtain the designs promised by the three factors\n construction applied to `k,n_1,n_2,n_3` (thanks to Julian R. Abel's help):\n\n 1) Let `s` be the largest integer `\\leq n_3/n_1`. Apply the product\n construction to `OA(k,n_1)` and a resolvable `OA(k,n_3)` whose blocks\n are partitionned into `s` `n_1`-parallel classes and `n_3-sn_1`\n parallel classes. It results in a `OA(k,n_1n_3)` partitionned into\n `sn_1^2` parallel classes plus `(n_1n_3-sn_1^2)/n_1=n_3-sn_1`\n `n_1`-parallel classes.\n\n 2) Add `n_3-n_1` parallel classes to every `n_1`-parallel class to turn\n them into `n_3`-parallel classes. Apply the product construction to\n this partitionned `OA(k,n_1n_3)` with a resolvable `OA(k,n_2)`.\n\n 3) As `OA(k,n_2)` is resolvable, the `n_2`-parallel classes of\n `OA(k,n_1n_2n_3)` are actually the union of `n_2` parallel classes,\n thus the `OA(k,n_1n_2n_3)` is resolvable and can be turned into an\n `OA(k+1,n_1n_2n_3)`\n\n INPUT:\n\n - ``k,n1,n2,n3`` (integers)\n\n - ``check`` -- (boolean) Whether to check that everything is going smoothly\n while the design is being built. It is disabled by default, as the\n constructor of orthogonal arrays checks the final design anyway.\n\n - ``explain_construction`` (boolean) -- return a string describing\n the construction.\n\n .. SEEALSO::\n\n - :func:`~sage.combinat.designs.orthogonal_arrays_find_recursive.find_three_factor_product`\n\n EXAMPLES::\n\n sage: # needs sage.schemes\n sage: from sage.combinat.designs.designs_pyx import is_orthogonal_array\n sage: from sage.combinat.designs.orthogonal_arrays_build_recursive import three_factor_product\n sage: OA = three_factor_product(4,4,4,4)\n sage: is_orthogonal_array(OA,5,64)\n True\n sage: OA = three_factor_product(4,3,4,5)\n sage: is_orthogonal_array(OA,5,60)\n True\n sage: OA = three_factor_product(5,4,5,7)\n sage: is_orthogonal_array(OA,6,140)\n True\n sage: OA = three_factor_product(9,8,9,9) # long time\n sage: is_orthogonal_array(OA,10,8*9*9) # long time\n True\n sage: print(designs.orthogonal_arrays.explain_construction(10,648))\n Three-factor product with n=8.9.9 from:\n Peter J. Dukes, Alan C.H. Ling,\n A three-factor product construction for mutually orthogonal latin squares,\n https://arxiv.org/abs/1401.1466\n\n REFERENCE:\n\n .. [DukesLing14] A three-factor product construction for mutually orthogonal latin squares,\n Peter J. Dukes, Alan C.H. Ling,\n :arxiv:`1401.1466`\n\n .. [Rees00] Truncated Transversal Designs: A New Lower Bound on the Number of Idempotent MOLS of Side,\n Rolf S. Rees,\n Journal of Combinatorial Theory, Series A 90.2 (2000): 257-266.\n\n .. [Rees93] Two new direct product-type constructions for resolvable group-divisible designs,\n Rolf S. Rees,\n Journal of Combinatorial Designs 1.1 (1993): 15-26.\n "
assert ((n1 <= n2) and (n2 <= n3))
if explain_construction:
return ((('Three-factor product with n={}.{}.{} from:\n' + ' Peter J. Dukes, Alan C.H. Ling,\n') + ' A three-factor product construction for mutually orthogonal latin squares,\n') + ' https://arxiv.org/abs/1401.1466').format(n1, n2, n3)
def assert_c_partition(classs, k, n, c):
'\n Makes sure that ``classs`` contains blocks `B` of size `k` such that the list of\n ``B[i]`` covers `[n]` exactly `c` times for every index `i`.\n '
c = int(c)
assert all(((len(B) == k) for B in classs)), 'A block has length {}!=k(={})'.format(len(B), k)
assert (len(classs) == (n * c)), 'not the right number of blocks'
for p in zip(*classs):
assert all(((x == (i // c)) for (i, x) in enumerate(sorted(p)))), 'A class is not c(={})-parallel'.format(c)
def product_with_parallel_classes(OA1, k, g1, g2, g1_parall, parall, check=True):
'\n Returns the product of two OA while keeping track of parallel classes\n\n INPUT:\n\n - ``OA1`` (an `OA(k,g_1)`\n\n - ``k,g1,g2`` integers\n\n - ``g1_parall`` -- list of `g_1`-parallel classes\n\n - ``parall`` -- list of parallel classes\n\n .. NOTE::\n\n The list ``g1_parall+parall`` should be an `OA(k,g_2)`\n\n OUTPUT:\n\n Two lists of classes ``g1_parall`` and ``parallel`` which are respectively\n `g_1`-parallel and parallel classes such that ``g1_parall+parallel`` is an\n `OA(k,g1*g2)``.\n '
if check:
for classs in g1_parall:
assert_c_partition(classs, k, g2, g1)
for classs in parall:
assert_c_partition(classs, k, g2, 1)
new_parallel_classes = []
for classs2 in g1_parall:
count = [([0] * g2) for _ in range(k)]
copies_of_OA1 = []
for B2 in classs2:
copy_of_OA1 = []
shift = [count[i][x2] for (i, x2) in enumerate(B2)]
assert (max(shift) < g1)
for B1 in OA1:
copy_of_OA1.append([((x2 * g1) + ((x1 + sh) % g1)) for (sh, x1, x2) in zip(shift, B1, B2)])
copies_of_OA1.append(copy_of_OA1)
for (i, x2) in enumerate(B2):
count[i][x2] += 1
new_parallel_classes.extend([list(_) for _ in zip(*copies_of_OA1)])
new_g1_parallel_classes = []
for classs2 in parall:
disjoint_copies_of_OA1 = []
for B2 in classs2:
for B1 in OA1:
disjoint_copies_of_OA1.append([((x2 * g1) + x1) for (x1, x2) in zip(B1, B2)])
new_g1_parallel_classes.append(disjoint_copies_of_OA1)
if check:
for classs in new_g1_parallel_classes:
assert_c_partition(classs, k, (g2 * g1), g1)
for classs in new_parallel_classes:
assert_c_partition(classs, k, (g2 * g1), 1)
return (new_g1_parallel_classes, new_parallel_classes)
OA1 = orthogonal_array(k, n1)
OA3 = sorted(orthogonal_array((k + 1), n3))
OA3 = [B[1:] for B in OA3]
OA2 = orthogonal_array((k + 1), n2)
OA2.sort()
OA2 = [B[1:] for B in OA2]
OA3_n1_parall = [OA3[i:(i + (n1 * n3))] for i in range(0, ((n3 - n1) * n3), (n1 * n3))]
OA3_parall = [OA3[i:(i + n3)] for i in range(((len(OA3_n1_parall) * n1) * n3), len(OA3), n3)]
(n1_parall, parall) = product_with_parallel_classes(OA1, k, n1, n3, OA3_n1_parall, OA3_parall, check=check)
if check:
OA_13 = [block for classs in (parall + n1_parall) for block in classs]
assert is_orthogonal_array(OA_13, k, (n1 * n3), 2, 1)
for classs in n1_parall:
for i in range((n2 - n1)):
classs.extend(parall.pop())
n2_parall = n1_parall
del n1_parall
(n2_parall, parall) = product_with_parallel_classes(OA2, k, n2, (n1 * n3), n2_parall, parall, check=check)
for n2_classs in n2_parall:
for i in range(n2):
partition = [B for j in range((n1 * n3)) for B in n2_classs[((j * (n2 ** 2)) + (i * n2)):((j * (n2 ** 2)) + ((i + 1) * n2))]]
parall.append(partition)
for (i, classs) in enumerate(parall):
for B in classs:
B.append(i)
OA = [block for classs in parall for block in classs]
if check:
assert is_orthogonal_array(OA, (k + 1), ((n1 * n2) * n3), 2, 1)
return OA
|
def _reorder_matrix(matrix):
'\n Return a matrix which is obtained from ``matrix`` by permutation of each row\n in which each column contain every symbol exactly once.\n\n The input must be a `N \\times k` matrix with entries in `\\{0,\\ldots,N-1\\}`\n such that:\n\n - the symbols on each row are distinct (and hence can be identified with\n subsets of `\\{0,\\ldots,N-1\\}`),\n - each symbol appear exactly `k` times.\n\n The problem is equivalent to an edge coloring of a bipartite graph. This\n function is used by :func:`brouwer_separable_design`.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays_build_recursive import _reorder_matrix\n sage: N = 4; k = 3\n sage: M = [[0,1,2],[0,1,3],[0,2,3],[1,2,3]]\n sage: M2 = _reorder_matrix(M)\n sage: all(set(M2[i][0] for i in range(N)) == set(range(N)) for i in range(k))\n True\n\n sage: M = [list(range(10))] * 10\n sage: N = k = 10\n sage: M2 = _reorder_matrix(M)\n sage: all(set(M2[i][0] for i in range(N)) == set(range(N)) for i in range(k))\n True\n '
from sage.graphs.graph import Graph
N = len(matrix)
k = len(matrix[0])
g = Graph()
g.add_edges(((x, (N + i)) for (i, S) in enumerate(matrix) for x in S))
matrix = []
for _ in range(k):
matching = g.matching(algorithm='LP')
col = ([0] * N)
for (x, i, _) in matching:
if (i < N):
(x, i) = (i, x)
col[(i - N)] = x
matrix.append(col)
g.delete_edges(matching)
return list(zip(*matrix))
|
def brouwer_separable_design(k, t, q, x, check=False, verbose=False, explain_construction=False):
"\n Returns a `OA(k,t(q^2+q+1)+x)` using Brouwer's result on separable designs.\n\n This method is an implementation of Brouwer's construction presented in\n [Brouwer80]_. It consists in a systematic application of the usual\n transformation from PBD to OA, applied to a specific PBD.\n\n **Baer subplanes**\n\n When `q` is a prime power, the projective plane `PG(2,q^2)` can be\n partitionned into subplanes `PG(2,q)` (called Baer subplanes), giving\n `PG(2,q^2)=B_1\\cup \\dots\\cup B_{q^2-q+1}`. As a result, every line of the\n `PG(2,q^2)` intersects one of the subplane on `q+1` points and all others on\n `1` point.\n\n The `OA` are built by considering `B_1\\cup\\dots\\cup B_t`, for a total of\n `t(q^2+q+1)` points (to which `x` new points are then added). The blocks of\n this subdesign belong to two categories:\n\n * The blocks of size `t`: they come from the lines which intersect a\n `B_i` on `q+1` points for some `i>t`. The blocks of size `t` can be partitionned\n into `q^2-q+t-1` parallel classes according to their associated subplane `B_i`\n with `i>t`.\n\n * The blocks of size `q+t`: those blocks form a symmetric design, as every\n point is incident with `q+t` of them.\n\n **Constructions**\n\n In the following, we write `N=t(q^2+q+1)+x`. The code is also heavily\n commented, and will clear any doubt.\n\n * i) `x=0`: in that case we build a resolvable `OA(k-1,N)` that will then be\n completed into an `OA(k,N)`.\n\n * *Sets of size* `t`)\n\n We take the product of each parallel class with the parallel classes\n of a resolvable `OA(k-1,t)-t.OA(k-1,t)`, yielding new parallel\n classes.\n\n * *Sets of size* `q+t`)\n\n A `N \\times (q+t)` array is built whose rows are the sets of size\n `q+t` such that every value appears once per column. For each block of\n a `OA(k-1,q+t)-(q+t).OA(k-1,t)`, the product with the rows of the\n matrix yields a parallel class.\n\n * ii) `x=q+t`\n\n * *Sets of size* `t`)\n\n Each set of size `t` gives a `OA(k,t)-t.OA(k,1)`, except if there is\n only one parallel class in which case a `OA(k,t)` is sufficient.\n\n * *Sets of size* `q+t`)\n\n A `(N-x) \\times (q+t)` array `M` is built whose `N-x` rows are the\n sets of size `q+t` such that every value appears once per column. For\n each of the new `x=q+t` points `p_1,\\dots,p_{q+t}` we build a matrix\n `M_i` obtained from `M` by adding a column equal to `(p_i,p_i,p_i\\dots\n )`. We add to the OA the product of all rows of the `M_i` with the\n block of the `x=q+t` parallel classes of a resolvable\n `OA(k,t+q+1)-(t+q+1).OA(k,1)`.\n\n * *Set of size* `x`) An `OA(k,x)`\n\n * iii) `x = q^2-q+1-t`\n\n * *Sets of size* `t`)\n\n All blocks of the `i`-th parallel class are extended with the `i`-th\n new point. The blocks are then replaced by a `OA(k,t+1)-(t+1).OA(k,1)`\n or, if there is only one parallel class (i.e. `x=1`) by a\n `OA(k,t+1)-OA(k,1)`.\n\n * *Set of size* `q+t`)\n\n They are replaced by `OA(k,q+t)-(q+t).OA(k,1)`.\n\n * *Set of size* `x`) An `OA(k,x)`\n\n * iv) `x = q^2+1`\n\n * *Sets of size* `t`)\n\n All blocks of the `i`-th parallel class are extended with the `i`-th\n new point (the other `x-q-t` new points are not touched at this\n step). The blocks are then replaced by a `OA(k,t+1)-(t+1).OA(k,1)` or,\n if there is only one parallel class (i.e. `x=1`) by a\n `OA(k,t+1)-OA(k,1)`.\n\n * *Sets of size* `q+t`) Same as for ii)\n\n * *Set of size* `x`) An `OA(k,x)`\n\n * v) `0<x<q^2-q+1-t`\n\n * *Sets of size* `t`)\n\n The blocks of the first `x` parallel class are extended with the `x`\n new points, and replaced with `OA(k.t+1)-(t+1).OA(k,1)` or, if `x=1`,\n by `OA(k.t+1)-.OA(k,1)`\n\n The blocks of the other parallel classes are replaced by\n `OA(k,t)-t.OA(k,t)` or, if there is only one class left, by\n `OA(k,t)-OA(k,t)`\n\n * *Sets of size* `q+t`)\n\n They are replaced with `OA(k,q+t)-(q+t).OA(k,1)`.\n\n * *Set of size* `x`) An `OA(k,x)`\n\n * vi) `t+q<x<q^2+1`\n\n * *Sets of size* `t`) Same as in v) with an `x` equal to `x-q+t`.\n\n * *Sets of size* `t`) Same as in vii)\n\n * *Set of size* `x`) An `OA(k,x)`\n\n INPUT:\n\n - ``k,t,q,x`` (integers)\n\n - ``check`` -- (boolean) Whether to check that output is correct before\n returning it. Set to ``False`` by default.\n\n - ``verbose`` (boolean) -- whether to print some information on the\n construction and parameters being used.\n\n - ``explain_construction`` (boolean) -- return a string describing\n the construction.\n\n .. SEEALSO::\n\n - :func:`~sage.combinat.designs.orthogonal_arrays_find_recursive.find_brouwer_separable_design`\n\n REFERENCES:\n\n .. [Brouwer80] A Series of Separable Designs with Application to Pairwise Orthogonal Latin Squares,\n Andries E. Brouwer,\n Vol. 1, n. 1, pp. 39-41,\n European Journal of Combinatorics, 1980\n http://www.sciencedirect.com/science/article/pii/S0195669880800199\n\n EXAMPLES:\n\n Test all possible cases::\n\n sage: from sage.combinat.designs.orthogonal_arrays_build_recursive import brouwer_separable_design\n sage: k,q,t=4,4,3; _=brouwer_separable_design(k,q,t,0,verbose=True)\n Case i) with k=4,q=3,t=4,x=0\n sage: k,q,t=3,3,3; _=brouwer_separable_design(k,t,q,t+q,verbose=True,check=True)\n Case ii) with k=3,q=3,t=3,x=6,e3=1\n sage: k,q,t=3,3,6; _=brouwer_separable_design(k,t,q,t+q,verbose=True,check=True)\n Case ii) with k=3,q=3,t=6,x=9,e3=0\n sage: k,q,t=3,3,6; _=brouwer_separable_design(k,t,q,q**2-q+1-t,verbose=True,check=True)\n Case iii) with k=3,q=3,t=6,x=1,e2=0\n sage: k,q,t=3,4,6; _=brouwer_separable_design(k,t,q,q**2-q+1-t,verbose=True,check=True)\n Case iii) with k=3,q=4,t=6,x=7,e2=1\n sage: k,q,t=3,4,6; _=brouwer_separable_design(k,t,q,q**2+1,verbose=True,check=True)\n Case iv) with k=3,q=4,t=6,x=17,e4=1\n sage: k,q,t=3,2,2; _=brouwer_separable_design(k,t,q,q**2+1,verbose=True,check=True)\n Case iv) with k=3,q=2,t=2,x=5,e4=0\n sage: k,q,t=3,4,7; _=brouwer_separable_design(k,t,q,3,verbose=True,check=True)\n Case v) with k=3,q=4,t=7,x=3,e1=1,e2=1\n sage: k,q,t=3,4,7; _=brouwer_separable_design(k,t,q,1,verbose=True,check=True)\n Case v) with k=3,q=4,t=7,x=1,e1=1,e2=0\n sage: k,q,t=3,4,7; _=brouwer_separable_design(k,t,q,q**2-q-t,verbose=True,check=True)\n Case v) with k=3,q=4,t=7,x=5,e1=0,e2=1\n sage: k,q,t=5,4,7; _=brouwer_separable_design(k,t,q,t+q+3,verbose=True,check=True)\n Case vi) with k=5,q=4,t=7,x=14,e3=1,e4=1\n sage: k,q,t=5,4,8; _=brouwer_separable_design(k,t,q,t+q+1,verbose=True,check=True)\n Case vi) with k=5,q=4,t=8,x=13,e3=1,e4=0\n sage: k,q,t=5,4,8; _=brouwer_separable_design(k,t,q,q**2,verbose=True,check=True)\n Case vi) with k=5,q=4,t=8,x=16,e3=0,e4=1\n\n sage: print(designs.orthogonal_arrays.explain_construction(10,189))\n Brouwer's separable design construction with t=9,q=4,x=0 from:\n Andries E. Brouwer,\n A series of separable designs with application to pairwise orthogonal Latin squares\n Vol. 1, n. 1, pp. 39-41,\n European Journal of Combinatorics, 1980\n "
from sage.combinat.designs.orthogonal_arrays import OA_from_PBD
from .difference_family import difference_family
from .orthogonal_arrays import incomplete_orthogonal_array
from sage.arith.misc import is_prime_power
if explain_construction:
return (((("Brouwer's separable design construction with t={},q={},x={} from:\n" + ' Andries E. Brouwer,\n') + ' A series of separable designs with application to pairwise orthogonal Latin squares\n') + ' Vol. 1, n. 1, pp. 39-41,\n') + ' European Journal of Combinatorics, 1980').format(t, q, x)
assert (t < (((q ** 2) - q) + 1))
assert (x >= 0)
assert is_prime_power(q)
N2 = (((q ** 4) + (q ** 2)) + 1)
N1 = (((q ** 2) + q) + 1)
B = difference_family(N2, ((q ** 2) + 1), 1)[1][0]
BIBD = [[((xx + i) % N2) for xx in B] for i in range(N2)]
m = (((q ** 2) - q) + 1)
for i in range(m):
for B in BIBD:
assert (sum((((xx % m) == i) for xx in B)) in [1, (q + 1)]), sum((((xx % m) == i) for xx in B))
blocks_of_size_q_plus_t = []
partition_of_blocks_of_size_t = [[] for _ in repeat(None, (m - t))]
relabel = {(i + (j * m)): ((N1 * i) + j) for i in range(t) for j in range(N1)}
for B in BIBD:
B_mod = sorted(((xx % m) for xx in B))
while (B_mod.pop(0) != B_mod[0]):
pass
plane = B_mod[0]
if (plane < t):
blocks_of_size_q_plus_t.append([relabel[xx] for xx in B if ((xx % m) < t)])
else:
partition_of_blocks_of_size_t[(plane - t)].append([relabel[xx] for xx in B if ((xx % m) < t)])
e1 = int((x != (((q ** 2) - q) - t)))
e2 = int((x != 1))
e3 = int((x != (q ** 2)))
e4 = int((x != ((t + q) + 1)))
N = ((t * N1) + x)
if (x == 0):
if verbose:
print('Case i) with k={},q={},t={},x={}'.format(k, q, t, x))
rOA_N_classes = []
OA_t = incomplete_orthogonal_array((k - 1), t, ([1] * t), resolvable=True)
OA_t_classes = [OA_t[(i * t):((i + 1) * t)] for i in range((t - 1))]
for PBD_parallel_class in partition_of_blocks_of_size_t:
for OA_class in OA_t_classes:
rOA_N_classes.append([[B[x] for x in BB] for BB in OA_class for B in PBD_parallel_class])
block_of_size_q_plus_t = _reorder_matrix(blocks_of_size_q_plus_t)
OA = incomplete_orthogonal_array((k - 1), (q + t), ([1] * (q + t)))
for B in OA:
rOA_N_classes.append([[R[x] for x in B] for R in block_of_size_q_plus_t])
rOA_N_classes.append([([i] * (k - 1)) for i in range(N)])
OA = [B for classs in rOA_N_classes for B in classs]
for (i, B) in enumerate(OA):
B.append((i // N))
elif ((x == (t + q)) and orthogonal_array((k + e3), t, existence=True) and orthogonal_array(k, (t + q), existence=True) and orthogonal_array((k + 1), ((t + q) + 1), existence=True)):
if verbose:
print('Case ii) with k={},q={},t={},x={},e3={}'.format(k, q, t, x, e3))
if (x == (q ** 2)):
assert (e3 == 0), 'equivalent to x==q^2'
assert (len(partition_of_blocks_of_size_t) == 1), 'also equivalent to exactly one partition into sets of size t'
OA = [[B[xx] for xx in R] for R in orthogonal_array(k, t) for B in partition_of_blocks_of_size_t[0]]
else:
OA = OA_from_PBD(k, N, sum(partition_of_blocks_of_size_t, []), check=False)[:(- N)]
OA.extend((([i] * k) for i in range((N - x))))
OA_tq1 = incomplete_orthogonal_array(k, ((t + q) + 1), ([1] * ((t + q) + 1)), resolvable=True)
OA_tq1_classes = [OA_tq1[(i * ((t + q) + 1)):((i + 1) * ((t + q) + 1))] for i in range((t + q))]
blocks_of_size_q_plus_t = _reorder_matrix(blocks_of_size_q_plus_t)
for (i, classs) in enumerate(OA_tq1_classes):
OA.extend(([(R[xx] if (xx < (t + q)) else ((N - i) - 1)) for xx in B] for R in blocks_of_size_q_plus_t for B in classs))
OA.extend(([((N - 1) - xx) for xx in R] for R in orthogonal_array(k, x)))
elif ((x == ((((q ** 2) - q) + 1) - t)) and orthogonal_array(k, x, existence=True) and orthogonal_array((k + e2), (t + 1), existence=True) and orthogonal_array((k + 1), (t + q), existence=True)):
if verbose:
print('Case iii) with k={},q={},t={},x={},e2={}'.format(k, q, t, x, e2))
OA = []
if (x == 1):
assert (e2 == 0), 'equivalent to x=1'
OA.extend(([(B[xx] if (xx < t) else (N - 1)) for xx in R] for R in incomplete_orthogonal_array(k, (t + 1), [1]) for B in partition_of_blocks_of_size_t[0]))
else:
assert (e2 == 1), 'equivalent to x!=1'
for (i, partition) in enumerate(partition_of_blocks_of_size_t):
for B in partition:
B.append(((N - i) - 1))
OA = OA_from_PBD(k, N, sum(partition_of_blocks_of_size_t, []), check=False)[:(- x)]
OA.extend(OA_from_PBD(k, N, blocks_of_size_q_plus_t, check=False)[:(- N)])
OA.extend(([((N - xx) - 1) for xx in B] for B in orthogonal_array(k, x)))
elif ((x == ((q ** 2) + 1)) and orthogonal_array(k, x, existence=True) and orthogonal_array((k + e4), (t + 1), existence=True) and orthogonal_array((k + 1), ((t + q) + 1), existence=True)):
if verbose:
print(f'Case iv) with k={k},q={q},t={t},x={x},e4={e4}')
if (e4 == 0):
OA = [[(B[xx] if (xx < t) else (N - x)) for xx in R] for R in incomplete_orthogonal_array(k, (t + 1), [1]) for B in partition_of_blocks_of_size_t[0]]
else:
for (i, classs) in enumerate(partition_of_blocks_of_size_t):
for B in classs:
B.append(((N - x) + i))
OA = OA_from_PBD(k, N, sum(partition_of_blocks_of_size_t, []), check=False)[:(- x)]
OA_tq1 = incomplete_orthogonal_array(k, ((t + q) + 1), ([1] * ((t + q) + 1)), resolvable=True)
OA_tq1_classes = [OA_tq1[(i * ((t + q) + 1)):((i + 1) * ((t + q) + 1))] for i in range((t + q))]
blocks_of_size_q_plus_t = _reorder_matrix(blocks_of_size_q_plus_t)
for (i, classs) in enumerate(OA_tq1_classes):
OA.extend(([(R[xx] if (xx < (t + q)) else ((N - i) - 1)) for xx in B] for R in blocks_of_size_q_plus_t for B in classs))
OA_k_x = orthogonal_array(k, x)
OA.extend(([((N - i) - 1) for i in R] for R in OA_k_x))
elif ((0 < x) and (x < ((((q ** 2) - q) + 1) - t)) and (e1 or e2) and orthogonal_array(k, x, existence=True) and orthogonal_array((k + e1), t, existence=True) and orthogonal_array((k + e2), (t + 1), existence=True) and orthogonal_array((k + 1), (t + q), existence=True)):
if verbose:
print('Case v) with k={},q={},t={},x={},e1={},e2={}'.format(k, q, t, x, e1, e2))
OA = []
if e2:
assert (x != 1), 'equivalent to e2==1'
for (i, classs) in enumerate(partition_of_blocks_of_size_t[:x]):
for B in classs:
B.append(((N - 1) - i))
OA.extend(OA_from_PBD(k, N, sum(partition_of_blocks_of_size_t[:x], []), check=False)[:(- N)])
else:
assert (x == 1), 'equivalent to e2==0'
OA.extend(([(B[xx] if (xx < t) else (N - 1)) for xx in R] for R in incomplete_orthogonal_array(k, (t + 1), [1]) for B in partition_of_blocks_of_size_t[0]))
if e1:
assert (x != (((q ** 2) - q) - t)), 'equivalent to e1=1'
OA.extend(OA_from_PBD(k, N, sum(partition_of_blocks_of_size_t[x:], []), check=False)[:(- N)])
else:
assert (x == (((q ** 2) - q) - t)), 'equivalent to e1=0'
OA.extend(([B[xx] for xx in R] for R in orthogonal_array(k, t) for B in partition_of_blocks_of_size_t[(- 1)]))
if (e1 and e2):
OA.extend((([i] * k) for i in range((N - x))))
if ((e1 == 0) and (e2 == 0)):
raise RuntimeError("Brouwer's construction does not work for case v) with e2=e1=0")
OA.extend(OA_from_PBD(k, N, blocks_of_size_q_plus_t, check=False)[:(- N)])
OA.extend(([((N - i) - 1) for i in R] for R in orthogonal_array(k, x)))
elif (((t + q) < x) and (x < ((q ** 2) + 1)) and (e3 or e4) and orthogonal_array(k, x, existence=True) and orthogonal_array((k + e3), t, existence=True) and orthogonal_array((k + e4), (t + 1), existence=True) and orthogonal_array((k + 1), ((t + q) + 1), existence=True)):
if verbose:
print('Case vi) with k={},q={},t={},x={},e3={},e4={}'.format(k, q, t, x, e3, e4))
OA = []
if e4:
assert (x != ((q + t) + 1)), 'equivalent to e4=1'
for (i, classs) in enumerate(partition_of_blocks_of_size_t[:(x - (q + t))]):
for B in classs:
B.append(((N - x) + i))
OA.extend(OA_from_PBD(k, N, sum(partition_of_blocks_of_size_t[:(x - (q + t))], []), check=False)[:(- N)])
else:
assert (x == ((q + t) + 1)), 'equivalent to e4=0'
OA.extend(([(B[xx] if (xx < t) else (N - x)) for xx in R] for R in incomplete_orthogonal_array(k, (t + 1), [1]) for B in partition_of_blocks_of_size_t[0]))
if e3:
assert (x != (q ** 2)), 'equivalent to e3=1'
OA.extend(OA_from_PBD(k, N, sum(partition_of_blocks_of_size_t[(x - (q + t)):], []), check=False)[:(- N)])
else:
assert (x == (q ** 2)), 'equivalent to e3=0'
OA.extend(([B[xx] for xx in R] for R in orthogonal_array(k, t) for B in partition_of_blocks_of_size_t[(- 1)]))
if (e3 and e4):
OA.extend((([i] * k) for i in range((N - x))))
elif ((e3 == 0) and (e4 == 0)):
raise RuntimeError("Brouwer's construction does not work for case v) with e3=e4=0")
OA_tq1 = incomplete_orthogonal_array(k, ((t + q) + 1), ([1] * ((t + q) + 1)), resolvable=True)
OA_tq1_classes = [OA_tq1[(i * ((t + q) + 1)):((i + 1) * ((t + q) + 1))] for i in range((t + q))]
blocks_of_size_q_plus_t = _reorder_matrix(blocks_of_size_q_plus_t)
for (i, classs) in enumerate(OA_tq1_classes):
OA.extend(([(R[xx] if (xx < (t + q)) else ((N - i) - 1)) for xx in B] for R in blocks_of_size_q_plus_t for B in classs))
OA.extend(([((N - xx) - 1) for xx in B] for B in orthogonal_array(k, x)))
else:
raise ValueError("this input is not handled by Brouwer's result")
if check:
assert is_orthogonal_array(OA, k, N, 2, 1)
return OA
|
def resolvable_balanced_incomplete_block_design(v, k, existence=False):
'\n Return a resolvable BIBD of parameters `v,k`.\n\n A BIBD is said to be *resolvable* if its blocks can be partitionned into\n parallel classes, i.e. partitions of the ground set.\n\n INPUT:\n\n - ``v,k`` (integers)\n\n - ``existence`` (boolean) -- instead of building the design, return:\n\n - ``True`` -- meaning that Sage knows how to build the design\n\n - ``Unknown`` -- meaning that Sage does not know how to build the\n design, but that the design may exist (see :mod:`sage.misc.unknown`).\n\n - ``False`` -- meaning that the design does not exist.\n\n .. SEEALSO::\n\n - :meth:`IncidenceStructure.is_resolvable`\n - :func:`~sage.combinat.designs.bibd.balanced_incomplete_block_design`\n\n EXAMPLES::\n\n sage: KTS15 = designs.resolvable_balanced_incomplete_block_design(15,3); KTS15\n (15,3,1)-Balanced Incomplete Block Design\n sage: KTS15.is_resolvable()\n True\n\n TESTS::\n\n sage: for v in range(40):\n ....: for k in range(v):\n ....: if designs.resolvable_balanced_incomplete_block_design(v,k,existence=True) is True:\n ....: _ = designs.resolvable_balanced_incomplete_block_design(v,k)\n '
if ((v == 1) or (k == v)):
return balanced_incomplete_block_design(v, k, existence=existence)
if ((v < k) or (k < 2) or ((v % k) != 0) or (((v - 1) % (k - 1)) != 0) or (((v * (v - 1)) % (k * (k - 1))) != 0) or ((k == 6) and (v == 36)) or (((v * (v - 1)) / (k * (k - 1))) < v)):
if existence:
return False
raise EmptySetError('There exists no ({},{},{})-RBIBD'.format(v, k, 1))
if (k == 2):
if existence:
return True
classes = [[[((c + i) % (v - 1)), (((c + v) - i) % (v - 1))] for i in range(1, (v // 2))] for c in range((v - 1))]
for (i, classs) in enumerate(classes):
classs.append([(v - 1), i])
B = BalancedIncompleteBlockDesign(v, sum(classes, []), k=k, check=True, copy=False)
B._classes = classes
return B
elif (k == 3):
return kirkman_triple_system(v, existence=existence)
elif (k == 4):
return v_4_1_rbibd(v, existence=existence)
else:
if existence:
return Unknown
raise NotImplementedError("I don't know how to build a ({},{},1)-RBIBD!".format(v, 3))
|
def kirkman_triple_system(v, existence=False):
"\n Return a Kirkman Triple System on `v` points.\n\n A Kirkman Triple System `KTS(v)` is a resolvable Steiner Triple System. It\n exists if and only if `v\\equiv 3\\pmod{6}`.\n\n INPUT:\n\n - `n` (integer)\n\n - ``existence`` (boolean; ``False`` by default) -- whether to build the\n `KTS(n)` or only answer whether it exists.\n\n .. SEEALSO::\n\n :meth:`IncidenceStructure.is_resolvable`\n\n EXAMPLES:\n\n A solution to Kirkmman's original problem::\n\n sage: kts = designs.kirkman_triple_system(15)\n sage: classes = kts.is_resolvable(1)[1]\n sage: names = '0123456789abcde'\n sage: def to_name(r_s_t):\n ....: r, s, t = r_s_t\n ....: return ' ' + names[r] + names[s] + names[t] + ' '\n sage: rows = [' '.join(('Day {}'.format(i) for i in range(1,8)))]\n sage: rows.extend(' '.join(map(to_name,row)) for row in zip(*classes))\n sage: print('\\n'.join(rows))\n Day 1 Day 2 Day 3 Day 4 Day 5 Day 6 Day 7\n 07e 18e 29e 3ae 4be 5ce 6de\n 139 24a 35b 46c 05d 167 028\n 26b 03c 14d 257 368 049 15a\n 458 569 06a 01b 12c 23d 347\n acd 7bd 78c 89d 79a 8ab 9bc\n\n TESTS::\n\n sage: for i in range(3,300,6): # needs sage.combinat\n ....: _ = designs.kirkman_triple_system(i)\n "
if ((v % 6) != 3):
if existence:
return False
raise ValueError('There is no KTS({}) as v!=3 mod(6)'.format(v))
if existence:
return False
elif (v == 3):
return BalancedIncompleteBlockDesign(3, [[0, 1, 2]], k=3, lambd=1)
elif (v == 9):
classes = [[[0, 1, 5], [2, 6, 7], [3, 4, 8]], [[1, 6, 8], [3, 5, 7], [0, 2, 4]], [[1, 4, 7], [0, 3, 6], [2, 5, 8]], [[4, 5, 6], [0, 7, 8], [1, 2, 3]]]
KTS = BalancedIncompleteBlockDesign(v, [tr for cl in classes for tr in cl], k=3, lambd=1, copy=False)
KTS._classes = classes
return KTS
elif (((((v - 1) // 2) % 6) == 1) and is_prime_power(((v - 1) // 2))):
from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF
q = ((v - 1) // 2)
K = GF(q, 'x')
a = K.primitive_element()
t = ((q - 1) // 6)
from sage.groups.generic import discrete_log
m = discrete_log((((a ** t) + 1) / 2), a)
assert ((2 * (a ** m)) == ((a ** t) + 1))
first_class = [[(0, 1), (0, 2), 'inf']]
b0 = K.one()
b1 = (a ** t)
b2 = (a ** m)
first_class.extend(([((b0 * (a ** i)), 1), ((b1 * (a ** i)), 1), ((b2 * (a ** i)), 2)] for i in ((list(range(t)) + list(range((2 * t), (3 * t)))) + list(range((4 * t), (5 * t))))))
b0 = (a ** (m + t))
b1 = (a ** (m + (3 * t)))
b2 = (a ** (m + (5 * t)))
first_class.extend([[((b0 * (a ** i)), 2), ((b1 * (a ** i)), 2), ((b2 * (a ** i)), 2)] for i in range(t)])
action = (lambda v, x: (((v + x[0]), x[1]) if (len(x) == 2) else x))
relabel = {(p, x): (i + ((x - 1) * q)) for (i, p) in enumerate(K) for x in [1, 2]}
relabel['inf'] = (2 * q)
classes = [[[relabel[action(p, x)] for x in tr] for tr in first_class] for p in K]
KTS = BalancedIncompleteBlockDesign(v, [tr for cl in classes for tr in cl], k=3, lambd=1, copy=False)
KTS._classes = classes
return KTS
elif ((((v // 3) % 6) == 1) and is_prime_power((v // 3))):
from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF
q = (v // 3)
K = GF(q, 'x')
a = K.primitive_element()
t = ((q - 1) // 6)
A0 = [(0, 0), (0, 1), (0, 2)]
B = [[((a ** i), j), ((a ** (i + (2 * t))), j), ((a ** (i + (4 * t))), j)] for j in range(3) for i in range(t)]
A = [[((a ** i), 0), ((a ** (i + (2 * t))), 1), ((a ** (i + (4 * t))), 2)] for i in range((6 * t))]
action = (lambda v, x: ((v + x[0]), x[1]))
relabel = {(p, j): (i + (j * q)) for (i, p) in enumerate(K) for j in range(3)}
B0 = (((([A0] + B) + A[t:(2 * t)]) + A[(3 * t):(4 * t)]) + A[(5 * t):(6 * t)])
classes = [[[relabel[action(p, x)] for x in tr] for tr in B0] for p in K]
for i in ((list(range(t)) + list(range((2 * t), (3 * t)))) + list(range((4 * t), (5 * t)))):
classes.append([[relabel[action(p, x)] for x in A[i]] for p in K])
KTS = BalancedIncompleteBlockDesign(v, [tr for cl in classes for tr in cl], k=3, lambd=1, copy=False)
KTS._classes = classes
return KTS
else:
gdd4 = kirkman_triple_system(9)
gdd7 = kirkman_triple_system(15)
X = [B for B in gdd4 if (8 in B)]
for b in X:
b.remove(8)
X = (sum(X, []) + [8])
gdd4.relabel({v: i for (i, v) in enumerate(X)})
gdd4 = gdd4.is_resolvable(True)[1]
X = [B for B in gdd7 if (14 in B)]
for b in X:
b.remove(14)
X = (sum(X, []) + [14])
gdd7.relabel({v: i for (i, v) in enumerate(X)})
gdd7 = gdd7.is_resolvable(True)[1]
for B in gdd4:
for (i, b) in enumerate(B):
if (8 in b):
j = min(b)
del B[i]
B.insert(0, j)
break
gdd4.sort()
for B in gdd4:
B.pop(0)
for B in gdd7:
for (i, b) in enumerate(B):
if (14 in b):
j = min(b)
del B[i]
B.insert(0, j)
break
gdd7.sort()
for B in gdd7:
B.pop(0)
classes = [[] for _ in repeat(None, ((v - 1) // 2))]
gdd = {4: gdd4, 7: gdd7}
for B in PBD_4_7(((v - 1) // 2), check=False):
for (i, classs) in enumerate(gdd[len(B)]):
classes[B[i]].extend([[((2 * B[(x // 2)]) + (x % 2)) for x in BB] for BB in classs])
for (i, classs) in enumerate(classes):
classs.append([(2 * i), ((2 * i) + 1), (v - 1)])
KTS = BalancedIncompleteBlockDesign(v, blocks=[tr for cl in classes for tr in cl], k=3, lambd=1, check=True, copy=False)
KTS._classes = classes
assert KTS.is_resolvable()
return KTS
|
def v_4_1_rbibd(v, existence=False):
'\n Return a `(v,4,1)`-RBIBD.\n\n INPUT:\n\n - `n` (integer)\n\n - ``existence`` (boolean; ``False`` by default) -- whether to build the\n design or only answer whether it exists.\n\n .. SEEALSO::\n\n - :meth:`IncidenceStructure.is_resolvable`\n - :func:`resolvable_balanced_incomplete_block_design`\n\n .. NOTE::\n\n A resolvable `(v,4,1)`-BIBD exists whenever `1\\equiv 4\\pmod(12)`. This\n function, however, only implements a construction of `(v,4,1)`-BIBD such\n that `v=3q+1\\equiv 1\\pmod{3}` where `q` is a prime power (see VII.7.5.a\n from [BJL99]_).\n\n EXAMPLES::\n\n sage: rBIBD = designs.resolvable_balanced_incomplete_block_design(28,4)\n sage: rBIBD.is_resolvable()\n True\n sage: rBIBD.is_t_design(return_parameters=True)\n (True, (2, 28, 4, 1))\n\n TESTS::\n\n sage: for q in prime_powers(2,30): # indirect doctest\n ....: if (3*q+1)%12 == 4:\n ....: _ = designs.resolvable_balanced_incomplete_block_design(3*q+1,4)\n '
if (((v % 3) != 1) or (not is_prime_power(((v - 1) // 3)))):
if existence:
return Unknown
raise NotImplementedError("I don't know how to build a ({},{},1)-RBIBD!".format(v, 4))
from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF
q = ((v - 1) // 3)
nn = ((q - 1) // 4)
G = GF(q, 'x')
w = G.primitive_element()
e = (w ** nn)
assert ((e ** 2) == (- 1))
first_class = [[((w ** i), j), ((- (w ** i)), j), ((e * (w ** i)), (j + 1)), (((- e) * (w ** i)), (j + 1))] for i in range(nn) for j in range(3)]
first_class.append([(0, 0), (0, 1), (0, 2), 'inf'])
label = {p: i for (i, p) in enumerate(G)}
classes = [[[((v - 1) if (x == 'inf') else (((x[1] % 3) * q) + label[(x[0] + g)])) for x in S] for S in first_class] for g in G]
BIBD = BalancedIncompleteBlockDesign(v, blocks=sum(classes, []), k=4, check=True, copy=False)
BIBD._classes = classes
assert BIBD.is_resolvable()
return BIBD
|
def PBD_4_7(v, check=True, existence=False):
'\n Return a `(v,\\{4,7\\})`-PBD\n\n For all `v` such that `n\\equiv 1\\pmod{3}` and `n\\neq 10,19, 31` there exists\n a `(v,\\{4,7\\})`-PBD. This is proved in Proposition IX.4.5 from [BJL99]_,\n which this method implements.\n\n This construction of PBD is used by the construction of Kirkman Triple\n Systems.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.resolvable_bibd import PBD_4_7\n sage: PBD_4_7(22)\n Pairwise Balanced Design on 22 points with sets of sizes in [4, 7]\n\n TESTS:\n\n All values `\\leq 300`::\n\n sage: for i in range(1,300,3): # needs sage.schemes\n ....: if i not in [10,19,31]:\n ....: assert PBD_4_7(i,existence=True) is True\n ....: _ = PBD_4_7(i,check=True)\n '
if (((v % 3) != 1) or (v in [10, 19, 31])):
if existence:
return Unknown
raise NotImplementedError
if existence:
return True
from .group_divisible_designs import GroupDivisibleDesign
from .group_divisible_designs import GDD_4_2
from .bibd import PairwiseBalancedDesign
from .bibd import balanced_incomplete_block_design
if (v == 22):
KTS15 = kirkman_triple_system(15)
blocks = ([(S + [(i + 15)]) for (i, classs) in enumerate(KTS15._classes) for S in classs] + [list(range(15, 22))])
elif (v == 34):
A = [(0, 0), (1, 1), (2, 0), (4, 1)]
B = [(0, 0), (1, 0), (4, 2)]
C = [(0, 0), (2, 2), (5, 0)]
D = [(0, 0), (0, 1), (0, 2)]
A = [[((x + i), (y + j)) for (x, y) in A] for i in range(9) for j in range(3)]
B = [([((x + i), ((y + i) + j)) for (x, y) in B] + [(27 + j)]) for i in range(9) for j in range(3)]
C = [([(((x + i) + j), ((y + (2 * i)) + j)) for (x, y) in C] + [(30 + j)]) for i in range(9) for j in range(3)]
D = [([((x + i), (y + i)) for (x, y) in D] + [33]) for i in range(9)]
blocks = [[(int(x) if (not isinstance(x, tuple)) else (((x[1] % 3) * 9) + (x[0] % 9))) for x in S] for S in ((((A + B) + C) + D) + [list(range(27, 34))])]
elif (v == 46):
A = [(1, 0), (3, 0), (9, 0), (0, 1)]
B = [(2, 0), (6, 0), (5, 0), (0, 1)]
C = [(0, 0), (1, 1), (4, 2)]
D = [(0, 0), (2, 1), (7, 2)]
E = [(0, 0), (0, 1), (0, 2)]
A = [[((x + i), (y + j)) for (x, y) in A] for i in range(13) for j in range(3)]
B = [[((x + i), (y + j)) for (x, y) in B] for i in range(13) for j in range(3)]
C = [([((x + i), (y + j)) for (x, y) in C] + [(39 + j)]) for i in range(13) for j in range(3)]
D = [([((x + i), (y + j)) for (x, y) in D] + [(42 + j)]) for i in range(13) for j in range(3)]
E = [([((x + i), (y + i)) for (x, y) in E] + [45]) for i in range(13)]
blocks = [[(int(x) if (not isinstance(x, tuple)) else (((x[1] % 3) * 13) + (x[0] % 13))) for x in S] for S in (((((A + B) + C) + D) + E) + [list(range(39, 46))])]
elif (v == 58):
A = [(0, 0), (1, 0), (4, 0), (5, 1)]
B = [(0, 0), (2, 0), (8, 0), (11, 1)]
C = [(0, 0), (5, 0), (2, 1), (12, 1)]
D = [(0, 0), (8, 1), (7, 2)]
E = [(0, 0), (6, 1), (4, 2)]
F = [(0, 0), (0, 1), (0, 2)]
A = [[((x + i), (y + j)) for (x, y) in A] for i in range(17) for j in range(3)]
B = [[((x + i), (y + j)) for (x, y) in B] for i in range(17) for j in range(3)]
C = [[((x + i), (y + j)) for (x, y) in C] for i in range(17) for j in range(3)]
D = [([((x + i), (y + j)) for (x, y) in D] + [(51 + j)]) for i in range(17) for j in range(3)]
E = [([((x + i), (y + j)) for (x, y) in E] + [(54 + j)]) for i in range(17) for j in range(3)]
F = [([((x + i), (y + i)) for (x, y) in F] + [57]) for i in range(17)]
blocks = [[(int(x) if (not isinstance(x, tuple)) else (((x[1] % 3) * 17) + (x[0] % 17))) for x in S] for S in ((((((A + B) + C) + D) + E) + F) + [list(range(51, 58))])]
elif (v == 70):
A = [(0, 0), (1, 0), (5, 1), (13, 1)]
B = [(0, 0), (4, 0), (20, 1), (10, 1)]
C = [(0, 0), (16, 0), (17, 1), (19, 1)]
D = [(0, 0), (2, 1), (8, 1), (11, 1)]
E = [(0, 0), (3, 2), (9, 1)]
F = [(0, 0), (7, 0), (14, 1)]
H = [(0, 0), (0, 1), (0, 2)]
A = [[((x + i), (y + j)) for (x, y) in A] for i in range(21) for j in range(3)]
B = [[((x + i), (y + j)) for (x, y) in B] for i in range(21) for j in range(3)]
C = [[((x + i), (y + j)) for (x, y) in C] for i in range(21) for j in range(3)]
D = [[((x + i), (y + j)) for (x, y) in D] for i in range(21) for j in range(3)]
E = [([((x + i), (y + j)) for (x, y) in E] + [(63 + j)]) for i in range(21) for j in range(3)]
F = [([(((x + (3 * i)) + j), ((y + ii) + j)) for (x, y) in F] + [(66 + j)]) for i in range(7) for j in range(3) for ii in range(3)]
H = [([((x + i), (y + i)) for (x, y) in H] + [69]) for i in range(21)]
blocks = [[(int(x) if (not isinstance(x, tuple)) else (((x[1] % 3) * 21) + (x[0] % 21))) for x in S] for S in (((((((A + B) + C) + D) + E) + F) + H) + [list(range(63, 70))])]
elif (v == 82):
from .group_divisible_designs import group_divisible_design
from .orthogonal_arrays import transversal_design
GDD = group_divisible_design((3 * 5), K=[4], G=[3], check=False)
TD = transversal_design(5, 5)
GDD2 = [[((3 * B[(x // 3)]) + (x % 3)) for x in BB] for B in TD for BB in GDD]
PBD22 = PBD_4_7((15 + 7))
S = next((SS for SS in PBD22 if (len(SS) == 7)))
PBD22.relabel({v: i for (i, v) in enumerate(([i for i in range((15 + 7)) if (i not in S)] + S))})
for B in PBD22:
if (B == S):
continue
for i in range(5):
GDD2.append([((x + (i * 15)) if (x < 15) else (x + 60)) for x in B])
GDD2.append(list(range(75, 82)))
blocks = GDD2
elif (v == 94):
from sage.combinat.designs.block_design import AffineGeometryDesign
AF = AffineGeometryDesign(2, 1, 7)
parall = []
plus_one = None
for S in AF:
if all(((x not in SS) for SS in parall for x in S)):
parall.append(S)
elif (plus_one is None):
plus_one = S
if ((len(parall) == 4) and (plus_one is not None)):
break
X = set(sum(parall, plus_one))
S_4_5_7 = [X.intersection(S) for S in AF]
S_4_5_7 = [S for S in S_4_5_7 if (len(S) > 1)]
S_4_5_7 = PairwiseBalancedDesign(X, blocks=S_4_5_7, K=[4, 5, 7], check=False)
S_4_5_7.relabel()
return PBD_4_7_from_Y(S_4_5_7, check=check)
elif ((v == 127) or (v == 142)):
points_to_add = (2 if (v == 127) else 7)
rBIBD4 = v_4_1_rbibd(40)
GDD = [((S + [(40 + i)]) if (i < points_to_add) else S) for (i, classs) in enumerate(rBIBD4._classes) for S in classs]
if (points_to_add == 7):
GDD.append(list(range(40, (40 + points_to_add))))
groups = [[x] for x in range((40 + points_to_add))]
else:
groups = [[x] for x in range(40)]
groups.append(list(range(40, (40 + points_to_add))))
GDD = GroupDivisibleDesign((40 + points_to_add), groups=groups, blocks=GDD, K=[2, 4, 5, 7], check=False, copy=False)
return PBD_4_7_from_Y(GDD, check=check)
elif (((v % 6) == 1) and (GDD_4_2(((v - 1) // 6), existence=True) is True)):
gdd = GDD_4_2(((v - 1) // 6))
return PBD_4_7_from_Y(gdd, check=check)
elif (v == 202):
PBD = PBD_4_7(22, check=False)
PBD = PBD_4_7_from_Y(PBD, check=False)
return PBD_4_7_from_Y(PBD, check=check)
elif (balanced_incomplete_block_design(v, 4, existence=True) is True):
return balanced_incomplete_block_design(v, 4)
elif (balanced_incomplete_block_design(v, 7, existence=True) is True):
return balanced_incomplete_block_design(v, 7)
else:
from sage.combinat.designs.orthogonal_arrays import orthogonal_array
vv = ((v - 1) // 3)
for g in range((((vv + 5) - 1) // 5), ((vv // 4) + 1)):
u = (vv - (4 * g))
if ((orthogonal_array(5, g, existence=True) is True) and (PBD_4_7(((3 * g) + 1), existence=True) is True) and (PBD_4_7(((3 * u) + 1), existence=True) is True)):
from .orthogonal_arrays import transversal_design
domain = set(range(vv))
GDD = transversal_design(5, g)
GDD = GroupDivisibleDesign(vv, groups=[[x for x in gr if (x in domain)] for gr in GDD.groups()], blocks=[[x for x in B if (x in domain)] for B in GDD], G=set([g, u]), K=[4, 5], check=False)
return PBD_4_7_from_Y(GDD, check=check)
return PairwiseBalancedDesign(v, blocks=blocks, K=[4, 7], check=check, copy=False)
|
def PBD_4_7_from_Y(gdd, check=True):
'\n Return a `(3v+1,\\{4,7\\})`-PBD from a `(v,\\{4,5,7\\},\\NN-\\{3,6,10\\})`-GDD.\n\n This implements Lemma IX.3.11 from [BJL99]_ (p.625). All points of the GDD\n are tripled, and a `+\\infty` point is added to the design.\n\n - A group of size `s\\in Y=\\NN-\\{3,6,10\\}` becomes a set of size `3s`. Adding\n `\\infty` to it gives it size `3s+1`, and this set is then replaced by a\n `(3s+1,\\{4,7\\})`-PBD.\n\n - A block of size `s\\in\\{4,5,7\\}` becomes a `(3s,\\{4,7\\},\\{3\\})`-GDD.\n\n This lemma is part of the existence proof of `(v,\\{4,7\\})`-PBD as explained\n in IX.4.5 from [BJL99]_).\n\n INPUT:\n\n - ``gdd`` -- a `(v,\\{4,5,7\\},Y)`-GDD where `Y=\\NN-\\{3,6,10\\}`.\n\n - ``check`` -- (boolean) Whether to check that output is correct before\n returning it. As this is expected to be useless (but we are cautious\n guys), you may want to disable it whenever you want speed. Set to ``True``\n by default.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.resolvable_bibd import PBD_4_7_from_Y\n sage: PBD_4_7_from_Y(designs.transversal_design(7,8)) # needs sage.schemes\n Pairwise Balanced Design on 169 points with sets of sizes in [4, 7]\n\n TESTS::\n\n sage: PBD_4_7_from_Y(designs.balanced_incomplete_block_design(10,10)) # needs sage.schemes\n Traceback (most recent call last):\n ...\n ValueError: The GDD should only contain blocks of size {4,5,7} but there are other: [10]\n sage: PBD_4_7_from_Y(designs.transversal_design(4,3)) # needs sage.schemes\n Traceback (most recent call last):\n ...\n RuntimeError: A group has size 3 but I do not know how to build a (10,[4,7])-PBD\n '
from .group_divisible_designs import group_divisible_design
from .bibd import PairwiseBalancedDesign
block_sizes = set(map(len, gdd._blocks))
group_sizes = set(map(len, gdd._groups))
if (not block_sizes.issubset([4, 5, 7])):
txt = list(block_sizes.difference([4, 5, 7]))
raise ValueError('The GDD should only contain blocks of size {{4,5,7}} but there are other: {}'.format(txt))
for gs in group_sizes:
if (not (PBD_4_7(((3 * gs) + 1), existence=True) is True)):
raise RuntimeError('A group has size {} but I do not know how to build a ({},[4,7])-PBD'.format(gs, ((3 * gs) + 1)))
GDD = {}
if (4 in block_sizes):
GDD[4] = group_divisible_design((3 * 4), K=[4], G=[3])
if (5 in block_sizes):
GDD[5] = group_divisible_design((3 * 5), K=[4], G=[3])
if (7 in block_sizes):
GDD[7] = PBD_4_7(22)
x = set(range(22)).difference(*[S for S in GDD[7] if (len(S) != 4)]).pop()
relabel = sum((S for S in GDD[7] if (x in S)), [])
relabel = ([xx for xx in relabel if (xx != x)] + [x])
GDD[7].relabel({v: i for (i, v) in enumerate(relabel)})
GDD[7] = [S for S in GDD[7] if (21 not in S)]
PBD = []
for B in gdd:
for B_GDD in GDD[len(B)]:
PBD.append([((3 * B[(x // 3)]) + (x % 3)) for x in B_GDD])
group_PBD = {gs: PBD_4_7(((3 * gs) + 1)) for gs in group_sizes}
for G in gdd.groups():
gs = len(G)
for B in group_PBD[gs]:
PBD.append([(((3 * G[(x // 3)]) + (x % 3)) if (x < (3 * gs)) else (3 * gdd.num_points())) for x in B])
return PairwiseBalancedDesign(((3 * gdd.num_points()) + 1), blocks=PBD, K=[4, 7], check=check, copy=False)
|
def two_n(B):
'\n Return a Steiner Quadruple System on `2n` points.\n\n INPUT:\n\n - ``B`` -- A Steiner Quadruple System on `n` points.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.steiner_quadruple_systems import two_n\n sage: for n in range(4, 30):\n ....: if (n%6) in [2,4]:\n ....: sqs = designs.steiner_quadruple_system(n)\n ....: if not two_n(sqs).is_t_design(3,2*n,4,1):\n ....: print("Something is wrong !")\n\n '
n = B.num_points()
Y = []
for (x, y, z, t) in B._blocks:
for a in range(2):
for b in range(2):
for c in range(2):
d = (((a + b) + c) % 2)
Y.append([(x + (a * n)), (y + (b * n)), (z + (c * n)), (t + (d * n))])
for j in range(n):
for jj in range((j + 1), n):
Y.append([j, jj, (n + j), (n + jj)])
return IncidenceStructure((2 * n), Y, check=False, copy=False)
|
def three_n_minus_two(B):
'\n Return a Steiner Quadruple System on `3n-2` points.\n\n INPUT:\n\n - ``B`` -- A Steiner Quadruple System on `n` points.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.steiner_quadruple_systems import three_n_minus_two\n sage: for n in range(4, 30):\n ....: if (n%6) in [2,4]:\n ....: sqs = designs.steiner_quadruple_system(n)\n ....: if not three_n_minus_two(sqs).is_t_design(3,3*n-2,4,1):\n ....: print("Something is wrong !")\n '
n = B.num_points()
A = (n - 1)
Y = []
r = (lambda i, x: (((i % 3) * (n - 1)) + x))
for (x, y, z, t) in B._blocks:
if (t == A):
for a in range(3):
for b in range(3):
c = ((- (a + b)) % 3)
Y.append([r(a, x), r(b, y), r(c, z), ((3 * n) - 3)])
Y.extend([[r(i, x), r(i, y), r((i + 1), z), r((i + 2), z)] for i in range(3)])
Y.extend([[r(i, x), r(i, z), r((i + 1), y), r((i + 2), y)] for i in range(3)])
Y.extend([[r(i, y), r(i, z), r((i + 1), x), r((i + 2), x)] for i in range(3)])
else:
for a in range(3):
for b in range(3):
for c in range(3):
d = ((- ((a + b) + c)) % 3)
Y.append([r(a, x), r(b, y), r(c, z), r(d, t)])
for j in range((n - 1)):
for jj in range((j + 1), (n - 1)):
Y.extend([[r(i, j), r(i, jj), r((i + 1), j), r((i + 1), jj)] for i in range(3)])
for j in range((n - 1)):
Y.append([r(0, j), r(1, j), r(2, j), ((3 * n) - 3)])
return IncidenceStructure(((3 * n) - 2), Y, check=False, copy=False)
|
def three_n_minus_eight(B):
'\n Return a Steiner Quadruple System on `3n-8` points.\n\n INPUT:\n\n - ``B`` -- A Steiner Quadruple System on `n` points.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.steiner_quadruple_systems import three_n_minus_eight\n sage: for n in range(4, 30):\n ....: if (n%12) == 2:\n ....: sqs = designs.steiner_quadruple_system(n)\n ....: if not three_n_minus_eight(sqs).is_t_design(3,3*n-8,4,1):\n ....: print("Something is wrong !")\n\n '
n = B.num_points()
if ((n % 12) != 2):
raise ValueError('n must be equal to 2 mod 12')
B = relabel_system(B)
r = (lambda i, x: (((i % 3) * (n - 4)) + (x % (n - 4))))
Y = [[(x + (2 * (n - 4))) for x in B._blocks[(- 1)]]]
for s in B._blocks[:(- 1)]:
for i in range(3):
Y.append([(r(i, x) if (x <= (n - 5)) else (x + (2 * (n - 4)))) for x in s])
for a in range(4):
for aa in range((n - 4)):
for aaa in range((n - 4)):
aaaa = ((- ((a + aa) + aaa)) % (n - 4))
Y.append([r(0, aa), r(1, aaa), r(2, aaaa), ((3 * (n - 4)) + a)])
k = ((n - 14) // 12)
for i in range(3):
for b in range((n - 4)):
for bb in range((n - 4)):
bbb = ((- (b + bb)) % (n - 4))
for d in range(((2 * k) + 1)):
Y.append([r((i + 2), bbb), r(i, ((((b + (2 * k)) + 1) + (i * ((4 * k) + 2))) - d)), r(i, ((((b + (2 * k)) + 2) + (i * ((4 * k) + 2))) + d)), r((i + 1), bb)])
for i in range(3):
for alpha in range(((4 * k) + 2), ((12 * k) + 9)):
for (ra, sa) in P(alpha, ((6 * k) + 5)):
for (raa, saa) in P(alpha, ((6 * k) + 5)):
Y.append([r(i, ra), r(i, sa), r((i + 1), raa), r((i + 1), saa)])
return IncidenceStructure(((3 * n) - 8), Y, check=False, copy=False)
|
def three_n_minus_four(B):
'\n Return a Steiner Quadruple System on `3n-4` points.\n\n INPUT:\n\n - ``B`` -- A Steiner Quadruple System on `n` points where `n\\equiv\n 10\\pmod{12}`.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.steiner_quadruple_systems import three_n_minus_four\n sage: for n in range(4, 30):\n ....: if n%12 == 10:\n ....: sqs = designs.steiner_quadruple_system(n)\n ....: if not three_n_minus_four(sqs).is_t_design(3,3*n-4,4,1):\n ....: print("Something is wrong !")\n\n '
n = B.num_points()
if ((n % 12) != 10):
raise ValueError('n must be equal to 10 mod 12')
B = relabel_system(B)
r = (lambda i, x: (((i % 3) * (n - 2)) + (x % (n - 2))))
Y = []
for s in B._blocks:
for i in range(3):
Y.append([(r(i, x) if (x <= (n - 3)) else (x + (2 * (n - 2)))) for x in s])
for a in range(2):
for aa in range((n - 2)):
for aaa in range((n - 2)):
aaaa = ((- ((a + aa) + aaa)) % (n - 2))
Y.append([r(0, aa), r(1, aaa), r(2, aaaa), ((3 * (n - 2)) + a)])
k = ((n - 10) // 12)
for i in range(3):
for b in range((n - 2)):
for bb in range((n - 2)):
bbb = ((- (b + bb)) % (n - 2))
for d in range(((2 * k) + 1)):
Y.append([r((i + 2), bbb), r(i, ((((b + (2 * k)) + 1) + (i * ((4 * k) + 2))) - d)), r(i, ((((b + (2 * k)) + 2) + (i * ((4 * k) + 2))) + d)), r((i + 1), bb)])
from sage.graphs.graph_coloring import round_robin
one_factorization = round_robin((2 * ((6 * k) + 4))).edges(sort=True)
color_classes = [[] for _ in repeat(None, ((2 * ((6 * k) + 4)) - 1))]
for (u, v, l) in one_factorization:
color_classes[l].append((u, v))
for i in range(3):
for alpha in range(((4 * k) + 2), (((12 * k) + 6) + 1)):
for (ra, sa) in P(alpha, ((6 * k) + 4)):
for (raa, saa) in P(alpha, ((6 * k) + 4)):
Y.append([r(i, ra), r(i, sa), r((i + 1), raa), r((i + 1), saa)])
return IncidenceStructure(((3 * n) - 4), Y, check=False, copy=False)
|
def four_n_minus_six(B):
'\n Return a Steiner Quadruple System on `4n-6` points.\n\n INPUT:\n\n - ``B`` -- A Steiner Quadruple System on `n` points.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.steiner_quadruple_systems import four_n_minus_six\n sage: for n in range(4, 20):\n ....: if (n%6) in [2,4]:\n ....: sqs = designs.steiner_quadruple_system(n)\n ....: if not four_n_minus_six(sqs).is_t_design(3,4*n-6,4,1):\n ....: print("Something is wrong !")\n\n '
n = B.num_points()
f = (n - 2)
r = (lambda i, ii, x: ((((2 * (i % 2)) + (ii % 2)) * (n - 2)) + (x % (n - 2))))
Y = []
for s in B._blocks:
for i in range(2):
for ii in range(2):
Y.append([(r(i, ii, x) if (x <= (n - 3)) else (x + (3 * (n - 2)))) for x in s])
k = (f // 2)
for l in range(2):
for eps in range(2):
for c in range(k):
for cc in range(k):
ccc = ((- (c + cc)) % k)
Y.append([((4 * (n - 2)) + l), r(0, 0, (2 * c)), r(0, 1, ((2 * cc) - eps)), r(1, eps, ((2 * ccc) + l))])
Y.append([((4 * (n - 2)) + l), r(0, 0, ((2 * c) + 1)), r(0, 1, (((2 * cc) - 1) - eps)), r(1, eps, (((2 * ccc) + 1) - l))])
Y.append([((4 * (n - 2)) + l), r(1, 0, (2 * c)), r(1, 1, ((2 * cc) - eps)), r(0, eps, (((2 * ccc) + 1) - l))])
Y.append([((4 * (n - 2)) + l), r(1, 0, ((2 * c) + 1)), r(1, 1, (((2 * cc) - 1) - eps)), r(0, eps, ((2 * ccc) + l))])
for h in range(2):
for eps in range(2):
for ccc in range(k):
assert (len(barP(ccc, k)) == (k - 1))
for (rc, sc) in barP(ccc, k):
for c in range(k):
cc = ((- (c + ccc)) % k)
Y.append([r(h, 0, ((2 * c) + eps)), r(h, 1, ((2 * cc) - eps)), r((h + 1), 0, rc), r((h + 1), 0, sc)])
Y.append([r(h, 0, (((2 * c) - 1) + eps)), r(h, 1, ((2 * cc) - eps)), r((h + 1), 1, rc), r((h + 1), 1, sc)])
for h in range(2):
for eps in range(2):
for ccc in range(k):
for (rc, sc) in barP((k + ccc), k):
for c in range(k):
cc = ((- (c + ccc)) % k)
Y.append([r(h, 0, ((2 * c) + eps)), r(h, 1, ((2 * cc) - eps)), r((h + 1), 1, rc), r((h + 1), 1, sc)])
Y.append([r(h, 0, (((2 * c) - 1) + eps)), r(h, 1, ((2 * cc) - eps)), r((h + 1), 0, rc), r((h + 1), 0, sc)])
for h in range(2):
for alpha in range((n - 3)):
for (ra, sa) in P(alpha, k):
for (raa, saa) in P(alpha, k):
Y.append([r(h, 0, ra), r(h, 0, sa), r(h, 1, raa), r(h, 1, saa)])
return IncidenceStructure(((4 * n) - 6), Y, check=False, copy=False)
|
def twelve_n_minus_ten(B):
'\n Return a Steiner Quadruple System on `12n-6` points.\n\n INPUT:\n\n - ``B`` -- A Steiner Quadruple System on `n` points.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.steiner_quadruple_systems import twelve_n_minus_ten\n sage: for n in range(4, 15):\n ....: if (n%6) in [2,4]:\n ....: sqs = designs.steiner_quadruple_system(n)\n ....: if not twelve_n_minus_ten(sqs).is_t_design(3,12*n-10,4,1):\n ....: print("Something is wrong !")\n\n '
n = B.num_points()
B14 = steiner_quadruple_system(14)
r = (lambda i, x: ((i % (n - 1)) + ((x % 12) * (n - 1))))
Y = []
for s in B14._blocks:
for i in range((n - 1)):
Y.append([(r(i, x) if (x <= 11) else ((r((n - 2), 11) + x) - 11)) for x in s])
for s in B._blocks:
if (s[(- 1)] == (n - 1)):
(u, v, w, B) = s
dd = {0: u, 1: v, 2: w}
d = (lambda x: dd[(x % 3)])
for b in range(12):
for bb in range(12):
bbb = ((- (b + bb)) % 12)
for h in range(2):
Y.append([((r((n - 2), 11) + 1) + h), r(u, b), r(v, bb), r(w, (bbb + (3 * h)))])
for i in range(3):
Y.append([r(d(i), ((b + 4) + i)), r(d(i), ((b + 7) + i)), r(d((i + 1)), bb), r(d((i + 2)), bbb)])
for j in range(12):
for eps in range(2):
for i in range(3):
Y.append([r(d(i), j), r(d((i + 1)), (j + (6 * eps))), r(d((i + 2)), (((6 * eps) - (2 * j)) + 1)), r(d((i + 2)), (((6 * eps) - (2 * j)) - 1))])
Y.append([r(d(i), j), r(d((i + 1)), (j + (6 * eps))), r(d((i + 2)), (((6 * eps) - (2 * j)) + 2)), r(d((i + 2)), (((6 * eps) - (2 * j)) - 2))])
Y.append([r(d(i), j), r(d((i + 1)), ((j + (6 * eps)) - 3)), r(d((i + 2)), (((6 * eps) - (2 * j)) + 1)), r(d((i + 2)), (((6 * eps) - (2 * j)) + 2))])
Y.append([r(d(i), j), r(d((i + 1)), ((j + (6 * eps)) + 3)), r(d((i + 2)), (((6 * eps) - (2 * j)) - 1)), r(d((i + 2)), (((6 * eps) - (2 * j)) - 2))])
for j in range(6):
for i in range(3):
for eps in range(2):
Y.append([r(d(i), j), r(d(i), (j + 6)), r(d((i + 1)), (j + (3 * eps))), r(d((i + 1)), ((j + 6) + (3 * eps)))])
for j in range(12):
for i in range(3):
for eps in range(4):
Y.append([r(d(i), j), r(d(i), (j + 1)), r(d((i + 1)), (j + (3 * eps))), r(d((i + 1)), ((j + (3 * eps)) + 1))])
Y.append([r(d(i), j), r(d(i), (j + 2)), r(d((i + 1)), (j + (3 * eps))), r(d((i + 1)), ((j + (3 * eps)) + 2))])
Y.append([r(d(i), j), r(d(i), (j + 4)), r(d((i + 1)), (j + (3 * eps))), r(d((i + 1)), ((j + (3 * eps)) + 4))])
for alpha in [4, 5]:
for (ra, sa) in P(alpha, 6):
for (raa, saa) in P(alpha, 6):
for i in range(3):
for ii in range((i + 1), 3):
Y.append([r(d(i), ra), r(d(i), sa), r(d(ii), raa), r(d(ii), saa)])
for g in range(6):
for eps in range(2):
for i in range(3):
for ii in range(3):
if (i == ii):
continue
Y.append([r(d(i), ((2 * g) + (3 * eps))), r(d(i), (((2 * g) + 6) + (3 * eps))), r(d(ii), ((2 * g) + 1)), r(d(ii), ((2 * g) + 5))])
Y.append([r(d(i), ((2 * g) + (3 * eps))), r(d(i), (((2 * g) + 6) + (3 * eps))), r(d(ii), ((2 * g) + 2)), r(d(ii), ((2 * g) + 4))])
else:
(x, y, z, t) = s
for a in range(12):
for aa in range(12):
for aaa in range(12):
aaaa = ((- ((a + aa) + aaa)) % 12)
Y.append([r(x, a), r(y, aa), r(z, aaa), r(t, aaaa)])
return IncidenceStructure(((12 * n) - 10), Y, check=False, copy=False)
|
def relabel_system(B):
'\n Relabels the set so that `\\{n-4, n-3, n-2, n-1\\}` is in `B`.\n\n INPUT:\n\n - ``B`` -- a list of 4-uples on `0,...,n-1`.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.steiner_quadruple_systems import relabel_system\n sage: SQS8 = designs.steiner_quadruple_system(8)\n sage: relabel_system(SQS8)\n Incidence structure with 8 points and 14 blocks\n '
n = B.num_points()
B0 = B._blocks[0]
label = {B0[0]: (n - 4), B0[1]: (n - 3), B0[2]: (n - 2), B0[3]: (n - 1)}
def get_label(x):
if (x in label):
return label[x]
else:
total = (len(label) - 4)
label[x] = total
return total
B = [[get_label(_) for _ in s] for s in B]
return IncidenceStructure(n, B)
|
def P(alpha, m):
'\n Return the collection of pairs `P_{\\alpha}(m)`\n\n For more information on this system, see [Han1960]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.steiner_quadruple_systems import P\n sage: P(3,4)\n [(0, 5), (2, 7), (4, 1), (6, 3)]\n '
if (alpha >= ((2 * m) - 1)):
raise Exception
if ((m % 2) == 0):
if (alpha < m):
if ((alpha % 2) == 0):
b = (alpha // 2)
return [((2 * a), ((((2 * a) + (2 * b)) + 1) % (2 * m))) for a in range(m)]
else:
b = ((alpha - 1) // 2)
return [((2 * a), ((((2 * a) - (2 * b)) - 1) % (2 * m))) for a in range(m)]
else:
y = (alpha - m)
pairs = [(b, (((2 * y) - b) % (2 * m))) for b in range(y)]
pairs += [(c, (((((2 * m) + (2 * y)) - c) - 2) % (2 * m))) for c in range(((2 * y) + 1), ((m + y) - 1))]
pairs += [(((2 * m) + int(((- 1.5) - (0.5 * ((- 1) ** y))))), y), (((2 * m) + int(((- 1.5) + (0.5 * ((- 1) ** y))))), ((m + y) - 1))]
return pairs
elif (alpha < (m - 1)):
if ((alpha % 2) == 0):
b = (alpha // 2)
return [((2 * a), ((((2 * a) + (2 * b)) + 1) % (2 * m))) for a in range(m)]
else:
b = ((alpha - 1) // 2)
return [((2 * a), ((((2 * a) - (2 * b)) - 1) % (2 * m))) for a in range(m)]
else:
y = ((alpha - m) + 1)
pairs = [(b, ((2 * y) - b)) for b in range(y)]
pairs += [(c, (((2 * m) + (2 * y)) - c)) for c in range(((2 * y) + 1), (m + y))]
pairs += [(y, (m + y))]
return pairs
|
def _missing_pair(n, l):
'\n Return the smallest `(x,x+1)` that is not contained in `l`.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.steiner_quadruple_systems import _missing_pair\n sage: _missing_pair(6, [(0,1), (4,5)])\n (2, 3)\n '
l = set((x for X in l for x in X))
for x in range(n):
if (x not in l):
break
assert (x not in l)
assert ((x + 1) not in l)
return (x, (x + 1))
|
def barP(eps, m):
'\n Return the collection of pairs `\\overline P_{\\alpha}(m)`\n\n For more information on this system, see [Han1960]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.steiner_quadruple_systems import barP\n sage: barP(3,4)\n [(0, 4), (3, 5), (1, 2)]\n '
return barP_system(m)[eps]
|
@cached_function
def barP_system(m):
'\n Return the 1-factorization of `K_{2m}` `\\overline P(m)`\n\n For more information on this system, see [Han1960]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.steiner_quadruple_systems import barP_system\n sage: barP_system(3)\n [[(4, 3), (2, 5)],\n [(0, 5), (4, 1)],\n [(0, 2), (1, 3)],\n [(1, 5), (4, 2), (0, 3)],\n [(0, 4), (3, 5), (1, 2)],\n [(0, 1), (2, 3), (4, 5)]]\n '
isequal = (lambda e1, e2: ((e1 == e2) or (e1 == tuple(reversed(e2)))))
pairs = []
last = []
if ((m % 2) == 0):
last = []
for n in range(1, (((m - 2) // 2) + 1)):
pairs.append([p for p in P((2 * n), m) if (not isequal(p, ((2 * n), (((4 * n) + 1) % (2 * m)))))])
last.append(((2 * n), (((4 * n) + 1) % (2 * m))))
pairs.append([p for p in P(((2 * n) - 1), m) if (not isequal(p, ((((2 * m) - 2) - (2 * n)), (((2 * m) - 1) - (4 * n)))))])
last.append(((((2 * m) - 2) - (2 * n)), (((2 * m) - 1) - (4 * n))))
pairs.append([p for p in P(m, m) if (not isequal(p, (((2 * m) - 2), 0)))])
last.append((((2 * m) - 2), 0))
pairs.append([p for p in P((m + 1), m) if (not isequal(p, (((2 * m) - 1), 1)))])
last.append((((2 * m) - 1), 1))
assert all(((len(pp) == (m - 1)) for pp in pairs))
assert (len(last) == m)
pairs.append(P(0, m))
pairs.append(P((m - 1), m))
for alpha in range((m + 2), ((2 * m) - 1)):
pairs.append(P(alpha, m))
pairs.append(last)
assert (len(pairs) == (2 * m))
relabel = {}
for n in range(1, (((m - 2) // 2) + 1)):
relabel[(2 * n)] = ((4 * n) % (2 * m))
relabel[((4 * n) + 1)] = (((4 * n) + 1) % (2 * m))
relabel[(((2 * m) - 2) - (2 * n))] = (((4 * n) - 2) % (2 * m))
relabel[(((2 * m) - 1) - (4 * n))] = (((4 * n) - 1) % (2 * m))
relabel[((2 * m) - 2)] = (1 % (2 * m))
relabel[0] = 0
relabel[((2 * m) - 1)] = ((2 * m) - 1)
relabel[1] = ((2 * m) - 2)
else:
last = []
for n in range((((m - 3) // 2) + 1)):
pairs.append([p for p in P((2 * n), m) if (not isequal(p, ((2 * n), (((4 * n) + 1) % (2 * m)))))])
last.append(((2 * n), (((4 * n) + 1) % (2 * m))))
pairs.append([p for p in P(((2 * n) + 1), m) if (not isequal(p, ((((2 * m) - 2) - (2 * n)), (((2 * m) - 3) - (4 * n)))))])
last.append(((((2 * m) - 2) - (2 * n)), (((2 * m) - 3) - (4 * n))))
pairs.append([p for p in P(((2 * m) - 2), m) if (not isequal(p, ((m - 1), ((2 * m) - 1))))])
last.append(((m - 1), ((2 * m) - 1)))
assert all(((len(pp) == (m - 1)) for pp in pairs))
assert (len(pairs) == m)
for alpha in range((m - 1), ((2 * m) - 2)):
pairs.append(P(alpha, m))
pairs.append(last)
assert (len(pairs) == (2 * m))
relabel = {}
for n in range((((m - 3) // 2) + 1)):
relabel[(2 * n)] = ((4 * n) % (2 * m))
relabel[((4 * n) + 1)] = (((4 * n) + 1) % (2 * m))
relabel[(((2 * m) - 2) - (2 * n))] = (((4 * n) + 2) % (2 * m))
relabel[(((2 * m) - 3) - (4 * n))] = (((4 * n) + 3) % (2 * m))
relabel[(m - 1)] = (((2 * m) - 2) % (2 * m))
relabel[((2 * m) - 1)] = ((2 * m) - 1)
assert (len(relabel) == (2 * m))
assert (len(pairs) == (2 * m))
pairs = [[(relabel[x], relabel[y]) for (x, y) in pp] for pp in pairs]
pairs.sort(key=(lambda x: _missing_pair(((2 * m) + 1), x)))
return pairs
|
@cached_function
def steiner_quadruple_system(n, check=False):
'\n Return a Steiner Quadruple System on `n` points.\n\n INPUT:\n\n - ``n`` -- an integer such that `n\\equiv 2,4\\pmod 6`\n\n - ``check`` (boolean) -- whether to check that the system is a Steiner\n Quadruple System before returning it (`False` by default)\n\n EXAMPLES::\n\n sage: sqs4 = designs.steiner_quadruple_system(4)\n sage: sqs4\n Incidence structure with 4 points and 1 blocks\n sage: sqs4.is_t_design(3,4,4,1)\n True\n\n sage: sqs8 = designs.steiner_quadruple_system(8)\n sage: sqs8\n Incidence structure with 8 points and 14 blocks\n sage: sqs8.is_t_design(3,8,4,1)\n True\n\n TESTS::\n\n sage: for n in range(4, 100): # long time\n ....: if (n%6) in [2,4]:\n ....: sqs = designs.steiner_quadruple_system(n, check=True)\n '
n = int(n)
if (not ((n % 6) in [2, 4])):
raise ValueError('n mod 6 must be equal to 2 or 4')
elif (n == 4):
sqs = IncidenceStructure(4, [[0, 1, 2, 3]], copy=False, check=False)
elif (n == 14):
sqs = IncidenceStructure(14, _SQS14(), copy=False, check=False)
elif (n == 38):
sqs = IncidenceStructure(38, _SQS38(), copy=False, check=False)
elif ((n % 12) in [4, 8]):
nn = (n // 2)
sqs = two_n(steiner_quadruple_system(nn, check=False))
elif ((n % 18) in [4, 10]):
nn = ((n + 2) // 3)
sqs = three_n_minus_two(steiner_quadruple_system(nn, check=False))
elif ((n % 36) == 34):
nn = ((n + 8) // 3)
sqs = three_n_minus_eight(steiner_quadruple_system(nn, check=False))
elif ((n % 36) == 26):
nn = ((n + 4) // 3)
sqs = three_n_minus_four(steiner_quadruple_system(nn, check=False))
elif ((n % 24) in [2, 10]):
nn = ((n + 6) // 4)
sqs = four_n_minus_six(steiner_quadruple_system(nn, check=False))
elif ((n % 72) in [14, 38]):
nn = ((n + 10) // 12)
sqs = twelve_n_minus_ten(steiner_quadruple_system(nn, check=False))
else:
raise ValueError('this should never happen')
if (check and (not sqs.is_t_design(3, n, 4, 1))):
raise RuntimeError('something is very very wrong')
return sqs
|
def _SQS14():
'\n Return a Steiner Quadruple System on 14 points.\n\n Obtained from the La Jolla Covering Repository.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.steiner_quadruple_systems import _SQS14\n sage: sqs14 = IncidenceStructure(_SQS14())\n sage: sqs14.is_t_design(3,14,4,1)\n True\n '
return [[0, 1, 2, 5], [0, 1, 3, 6], [0, 1, 4, 13], [0, 1, 7, 10], [0, 1, 8, 9], [0, 1, 11, 12], [0, 2, 3, 4], [0, 2, 6, 12], [0, 2, 7, 9], [0, 2, 8, 11], [0, 2, 10, 13], [0, 3, 5, 13], [0, 3, 7, 11], [0, 3, 8, 10], [0, 3, 9, 12], [0, 4, 5, 9], [0, 4, 6, 11], [0, 4, 7, 8], [0, 4, 10, 12], [0, 5, 6, 8], [0, 5, 7, 12], [0, 5, 10, 11], [0, 6, 7, 13], [0, 6, 9, 10], [0, 8, 12, 13], [0, 9, 11, 13], [1, 2, 3, 13], [1, 2, 4, 12], [1, 2, 6, 9], [1, 2, 7, 11], [1, 2, 8, 10], [1, 3, 4, 5], [1, 3, 7, 8], [1, 3, 9, 11], [1, 3, 10, 12], [1, 4, 6, 10], [1, 4, 7, 9], [1, 4, 8, 11], [1, 5, 6, 11], [1, 5, 7, 13], [1, 5, 8, 12], [1, 5, 9, 10], [1, 6, 7, 12], [1, 6, 8, 13], [1, 9, 12, 13], [1, 10, 11, 13], [2, 3, 5, 11], [2, 3, 6, 7], [2, 3, 8, 12], [2, 3, 9, 10], [2, 4, 5, 13], [2, 4, 6, 8], [2, 4, 7, 10], [2, 4, 9, 11], [2, 5, 6, 10], [2, 5, 7, 8], [2, 5, 9, 12], [2, 6, 11, 13], [2, 7, 12, 13], [2, 8, 9, 13], [2, 10, 11, 12], [3, 4, 6, 9], [3, 4, 7, 12], [3, 4, 8, 13], [3, 4, 10, 11], [3, 5, 6, 12], [3, 5, 7, 10], [3, 5, 8, 9], [3, 6, 8, 11], [3, 6, 10, 13], [3, 7, 9, 13], [3, 11, 12, 13], [4, 5, 6, 7], [4, 5, 8, 10], [4, 5, 11, 12], [4, 6, 12, 13], [4, 7, 11, 13], [4, 8, 9, 12], [4, 9, 10, 13], [5, 6, 9, 13], [5, 7, 9, 11], [5, 8, 11, 13], [5, 10, 12, 13], [6, 7, 8, 9], [6, 7, 10, 11], [6, 8, 10, 12], [6, 9, 11, 12], [7, 8, 10, 13], [7, 8, 11, 12], [7, 9, 10, 12], [8, 9, 10, 11]]
|
def _SQS38():
'\n Return a Steiner Quadruple System on 14 points.\n\n Obtained from the La Jolla Covering Repository.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.steiner_quadruple_systems import _SQS38\n sage: sqs38 = IncidenceStructure(_SQS38())\n sage: sqs38.is_t_design(3,38,4,1)\n True\n '
return [[0, 1, 2, 14], [0, 1, 3, 34], [0, 1, 4, 31], [0, 1, 5, 27], [0, 1, 6, 17], [0, 1, 7, 12], [0, 1, 8, 36], [0, 1, 9, 10], [0, 1, 11, 18], [0, 1, 13, 37], [0, 1, 15, 35], [0, 1, 16, 22], [0, 1, 19, 33], [0, 1, 20, 25], [0, 1, 21, 23], [0, 1, 24, 32], [0, 1, 26, 28], [0, 1, 29, 30], [0, 2, 3, 10], [0, 2, 4, 9], [0, 2, 5, 28], [0, 2, 6, 15], [0, 2, 7, 36], [0, 2, 8, 23], [0, 2, 11, 22], [0, 2, 12, 13], [0, 2, 16, 25], [0, 2, 17, 18], [0, 2, 19, 30], [0, 2, 20, 35], [0, 2, 21, 29], [0, 2, 24, 34], [0, 2, 26, 31], [0, 2, 27, 32], [0, 2, 33, 37], [0, 3, 4, 18], [0, 3, 5, 23], [0, 3, 6, 32], [0, 3, 7, 19], [0, 3, 8, 20], [0, 3, 9, 17], [0, 3, 11, 25], [0, 3, 12, 24], [0, 3, 13, 27], [0, 3, 14, 31], [0, 3, 15, 22], [0, 3, 16, 28], [0, 3, 21, 33], [0, 3, 26, 36], [0, 3, 29, 35], [0, 3, 30, 37], [0, 4, 5, 7], [0, 4, 6, 28], [0, 4, 8, 25], [0, 4, 10, 30], [0, 4, 11, 20], [0, 4, 12, 32], [0, 4, 13, 36], [0, 4, 14, 29], [0, 4, 15, 27], [0, 4, 16, 35], [0, 4, 17, 22], [0, 4, 19, 23], [0, 4, 21, 34], [0, 4, 24, 33], [0, 4, 26, 37], [0, 5, 6, 24], [0, 5, 8, 26], [0, 5, 9, 29], [0, 5, 10, 20], [0, 5, 11, 13], [0, 5, 12, 14], [0, 5, 15, 33], [0, 5, 16, 37], [0, 5, 17, 35], [0, 5, 18, 19], [0, 5, 21, 25], [0, 5, 22, 30], [0, 5, 31, 32], [0, 5, 34, 36], [0, 6, 7, 30], [0, 6, 8, 33], [0, 6, 9, 12], [0, 6, 10, 18], [0, 6, 11, 37], [0, 6, 13, 31], [0, 6, 14, 35], [0, 6, 16, 29], [0, 6, 19, 25], [0, 6, 20, 27], [0, 6, 21, 36], [0, 6, 22, 23], [0, 6, 26, 34], [0, 7, 8, 11], [0, 7, 9, 33], [0, 7, 10, 21], [0, 7, 13, 20], [0, 7, 14, 22], [0, 7, 15, 31], [0, 7, 16, 34], [0, 7, 17, 29], [0, 7, 18, 24], [0, 7, 23, 26], [0, 7, 25, 32], [0, 7, 27, 28], [0, 7, 35, 37], [0, 8, 9, 37], [0, 8, 10, 27], [0, 8, 12, 18], [0, 8, 13, 30], [0, 8, 14, 15], [0, 8, 16, 21], [0, 8, 17, 19], [0, 8, 22, 35], [0, 8, 24, 31], [0, 8, 28, 34], [0, 8, 29, 32], [0, 9, 11, 30], [0, 9, 13, 23], [0, 9, 14, 18], [0, 9, 15, 25], [0, 9, 16, 26], [0, 9, 19, 28], [0, 9, 20, 36], [0, 9, 21, 35], [0, 9, 22, 24], [0, 9, 27, 31], [0, 9, 32, 34], [0, 10, 11, 36], [0, 10, 12, 15], [0, 10, 13, 26], [0, 10, 14, 16], [0, 10, 17, 37], [0, 10, 19, 29], [0, 10, 22, 31], [0, 10, 23, 32], [0, 10, 24, 35], [0, 10, 25, 34], [0, 10, 28, 33], [0, 11, 12, 16], [0, 11, 14, 24], [0, 11, 15, 26], [0, 11, 17, 31], [0, 11, 19, 21], [0, 11, 23, 34], [0, 11, 27, 29], [0, 11, 28, 35], [0, 11, 32, 33], [0, 12, 17, 20], [0, 12, 19, 35], [0, 12, 21, 28], [0, 12, 22, 25], [0, 12, 23, 27], [0, 12, 26, 29], [0, 12, 30, 33], [0, 12, 31, 34], [0, 12, 36, 37], [0, 13, 14, 33], [0, 13, 15, 29], [0, 13, 16, 24], [0, 13, 17, 21], [0, 13, 18, 34], [0, 13, 19, 32], [0, 13, 22, 28], [0, 13, 25, 35], [0, 14, 17, 26], [0, 14, 19, 20], [0, 14, 21, 32], [0, 14, 23, 36], [0, 14, 25, 28], [0, 14, 27, 30], [0, 14, 34, 37], [0, 15, 16, 36], [0, 15, 17, 23], [0, 15, 18, 20], [0, 15, 19, 34], [0, 15, 21, 37], [0, 15, 24, 28], [0, 15, 30, 32], [0, 16, 17, 32], [0, 16, 18, 27], [0, 16, 19, 31], [0, 16, 20, 33], [0, 16, 23, 30], [0, 17, 24, 27], [0, 17, 25, 33], [0, 17, 28, 36], [0, 17, 30, 34], [0, 18, 21, 26], [0, 18, 22, 29], [0, 18, 23, 28], [0, 18, 25, 31], [0, 18, 30, 35], [0, 18, 32, 37], [0, 18, 33, 36], [0, 19, 22, 26], [0, 19, 24, 37], [0, 19, 27, 36], [0, 20, 21, 31], [0, 20, 22, 37], [0, 20, 23, 24], [0, 20, 26, 30], [0, 20, 28, 32], [0, 20, 29, 34], [0, 21, 22, 27], [0, 21, 24, 30], [0, 22, 32, 36], [0, 22, 33, 34], [0, 23, 25, 29], [0, 23, 31, 37], [0, 23, 33, 35], [0, 24, 25, 26], [0, 24, 29, 36], [0, 25, 27, 37], [0, 25, 30, 36], [0, 26, 27, 33], [0, 26, 32, 35], [0, 27, 34, 35], [0, 28, 29, 37], [0, 28, 30, 31], [0, 29, 31, 33], [0, 31, 35, 36], [1, 2, 3, 15], [1, 2, 4, 35], [1, 2, 5, 32], [1, 2, 6, 28], [1, 2, 7, 18], [1, 2, 8, 13], [1, 2, 9, 37], [1, 2, 10, 11], [1, 2, 12, 19], [1, 2, 16, 36], [1, 2, 17, 23], [1, 2, 20, 34], [1, 2, 21, 26], [1, 2, 22, 24], [1, 2, 25, 33], [1, 2, 27, 29], [1, 2, 30, 31], [1, 3, 4, 11], [1, 3, 5, 10], [1, 3, 6, 29], [1, 3, 7, 16], [1, 3, 8, 37], [1, 3, 9, 24], [1, 3, 12, 23], [1, 3, 13, 14], [1, 3, 17, 26], [1, 3, 18, 19], [1, 3, 20, 31], [1, 3, 21, 36], [1, 3, 22, 30], [1, 3, 25, 35], [1, 3, 27, 32], [1, 3, 28, 33], [1, 4, 5, 19], [1, 4, 6, 24], [1, 4, 7, 33], [1, 4, 8, 20], [1, 4, 9, 21], [1, 4, 10, 18], [1, 4, 12, 26], [1, 4, 13, 25], [1, 4, 14, 28], [1, 4, 15, 32], [1, 4, 16, 23], [1, 4, 17, 29], [1, 4, 22, 34], [1, 4, 27, 37], [1, 4, 30, 36], [1, 5, 6, 8], [1, 5, 7, 29], [1, 5, 9, 26], [1, 5, 11, 31], [1, 5, 12, 21], [1, 5, 13, 33], [1, 5, 14, 37], [1, 5, 15, 30], [1, 5, 16, 28], [1, 5, 17, 36], [1, 5, 18, 23], [1, 5, 20, 24], [1, 5, 22, 35], [1, 5, 25, 34], [1, 6, 7, 25], [1, 6, 9, 27], [1, 6, 10, 30], [1, 6, 11, 21], [1, 6, 12, 14], [1, 6, 13, 15], [1, 6, 16, 34], [1, 6, 18, 36], [1, 6, 19, 20], [1, 6, 22, 26], [1, 6, 23, 31], [1, 6, 32, 33], [1, 6, 35, 37], [1, 7, 8, 31], [1, 7, 9, 34], [1, 7, 10, 13], [1, 7, 11, 19], [1, 7, 14, 32], [1, 7, 15, 36], [1, 7, 17, 30], [1, 7, 20, 26], [1, 7, 21, 28], [1, 7, 22, 37], [1, 7, 23, 24], [1, 7, 27, 35], [1, 8, 9, 12], [1, 8, 10, 34], [1, 8, 11, 22], [1, 8, 14, 21], [1, 8, 15, 23], [1, 8, 16, 32], [1, 8, 17, 35], [1, 8, 18, 30], [1, 8, 19, 25], [1, 8, 24, 27], [1, 8, 26, 33], [1, 8, 28, 29], [1, 9, 11, 28], [1, 9, 13, 19], [1, 9, 14, 31], [1, 9, 15, 16], [1, 9, 17, 22], [1, 9, 18, 20], [1, 9, 23, 36], [1, 9, 25, 32], [1, 9, 29, 35], [1, 9, 30, 33], [1, 10, 12, 31], [1, 10, 14, 24], [1, 10, 15, 19], [1, 10, 16, 26], [1, 10, 17, 27], [1, 10, 20, 29], [1, 10, 21, 37], [1, 10, 22, 36], [1, 10, 23, 25], [1, 10, 28, 32], [1, 10, 33, 35], [1, 11, 12, 37], [1, 11, 13, 16], [1, 11, 14, 27], [1, 11, 15, 17], [1, 11, 20, 30], [1, 11, 23, 32], [1, 11, 24, 33], [1, 11, 25, 36], [1, 11, 26, 35], [1, 11, 29, 34], [1, 12, 13, 17], [1, 12, 15, 25], [1, 12, 16, 27], [1, 12, 18, 32], [1, 12, 20, 22], [1, 12, 24, 35], [1, 12, 28, 30], [1, 12, 29, 36], [1, 12, 33, 34], [1, 13, 18, 21], [1, 13, 20, 36], [1, 13, 22, 29], [1, 13, 23, 26], [1, 13, 24, 28], [1, 13, 27, 30], [1, 13, 31, 34], [1, 13, 32, 35], [1, 14, 15, 34], [1, 14, 16, 30], [1, 14, 17, 25], [1, 14, 18, 22], [1, 14, 19, 35], [1, 14, 20, 33], [1, 14, 23, 29], [1, 14, 26, 36], [1, 15, 18, 27], [1, 15, 20, 21], [1, 15, 22, 33], [1, 15, 24, 37], [1, 15, 26, 29], [1, 15, 28, 31], [1, 16, 17, 37], [1, 16, 18, 24], [1, 16, 19, 21], [1, 16, 20, 35], [1, 16, 25, 29], [1, 16, 31, 33], [1, 17, 18, 33], [1, 17, 19, 28], [1, 17, 20, 32], [1, 17, 21, 34], [1, 17, 24, 31], [1, 18, 25, 28], [1, 18, 26, 34], [1, 18, 29, 37], [1, 18, 31, 35], [1, 19, 22, 27], [1, 19, 23, 30], [1, 19, 24, 29], [1, 19, 26, 32], [1, 19, 31, 36], [1, 19, 34, 37], [1, 20, 23, 27], [1, 20, 28, 37], [1, 21, 22, 32], [1, 21, 24, 25], [1, 21, 27, 31], [1, 21, 29, 33], [1, 21, 30, 35], [1, 22, 23, 28], [1, 22, 25, 31], [1, 23, 33, 37], [1, 23, 34, 35], [1, 24, 26, 30], [1, 24, 34, 36], [1, 25, 26, 27], [1, 25, 30, 37], [1, 26, 31, 37], [1, 27, 28, 34], [1, 27, 33, 36], [1, 28, 35, 36], [1, 29, 31, 32], [1, 30, 32, 34], [1, 32, 36, 37], [2, 3, 4, 16], [2, 3, 5, 36], [2, 3, 6, 33], [2, 3, 7, 29], [2, 3, 8, 19], [2, 3, 9, 14], [2, 3, 11, 12], [2, 3, 13, 20], [2, 3, 17, 37], [2, 3, 18, 24], [2, 3, 21, 35], [2, 3, 22, 27], [2, 3, 23, 25], [2, 3, 26, 34], [2, 3, 28, 30], [2, 3, 31, 32], [2, 4, 5, 12], [2, 4, 6, 11], [2, 4, 7, 30], [2, 4, 8, 17], [2, 4, 10, 25], [2, 4, 13, 24], [2, 4, 14, 15], [2, 4, 18, 27], [2, 4, 19, 20], [2, 4, 21, 32], [2, 4, 22, 37], [2, 4, 23, 31], [2, 4, 26, 36], [2, 4, 28, 33], [2, 4, 29, 34], [2, 5, 6, 20], [2, 5, 7, 25], [2, 5, 8, 34], [2, 5, 9, 21], [2, 5, 10, 22], [2, 5, 11, 19], [2, 5, 13, 27], [2, 5, 14, 26], [2, 5, 15, 29], [2, 5, 16, 33], [2, 5, 17, 24], [2, 5, 18, 30], [2, 5, 23, 35], [2, 5, 31, 37], [2, 6, 7, 9], [2, 6, 8, 30], [2, 6, 10, 27], [2, 6, 12, 32], [2, 6, 13, 22], [2, 6, 14, 34], [2, 6, 16, 31], [2, 6, 17, 29], [2, 6, 18, 37], [2, 6, 19, 24], [2, 6, 21, 25], [2, 6, 23, 36], [2, 6, 26, 35], [2, 7, 8, 26], [2, 7, 10, 28], [2, 7, 11, 31], [2, 7, 12, 22], [2, 7, 13, 15], [2, 7, 14, 16], [2, 7, 17, 35], [2, 7, 19, 37], [2, 7, 20, 21], [2, 7, 23, 27], [2, 7, 24, 32], [2, 7, 33, 34], [2, 8, 9, 32], [2, 8, 10, 35], [2, 8, 11, 14], [2, 8, 12, 20], [2, 8, 15, 33], [2, 8, 16, 37], [2, 8, 18, 31], [2, 8, 21, 27], [2, 8, 22, 29], [2, 8, 24, 25], [2, 8, 28, 36], [2, 9, 10, 13], [2, 9, 11, 35], [2, 9, 12, 23], [2, 9, 15, 22], [2, 9, 16, 24], [2, 9, 17, 33], [2, 9, 18, 36], [2, 9, 19, 31], [2, 9, 20, 26], [2, 9, 25, 28], [2, 9, 27, 34], [2, 9, 29, 30], [2, 10, 12, 29], [2, 10, 14, 20], [2, 10, 15, 32], [2, 10, 16, 17], [2, 10, 18, 23], [2, 10, 19, 21], [2, 10, 24, 37], [2, 10, 26, 33], [2, 10, 30, 36], [2, 10, 31, 34], [2, 11, 13, 32], [2, 11, 15, 25], [2, 11, 16, 20], [2, 11, 17, 27], [2, 11, 18, 28], [2, 11, 21, 30], [2, 11, 23, 37], [2, 11, 24, 26], [2, 11, 29, 33], [2, 11, 34, 36], [2, 12, 14, 17], [2, 12, 15, 28], [2, 12, 16, 18], [2, 12, 21, 31], [2, 12, 24, 33], [2, 12, 25, 34], [2, 12, 26, 37], [2, 12, 27, 36], [2, 12, 30, 35], [2, 13, 14, 18], [2, 13, 16, 26], [2, 13, 17, 28], [2, 13, 19, 33], [2, 13, 21, 23], [2, 13, 25, 36], [2, 13, 29, 31], [2, 13, 30, 37], [2, 13, 34, 35], [2, 14, 19, 22], [2, 14, 21, 37], [2, 14, 23, 30], [2, 14, 24, 27], [2, 14, 25, 29], [2, 14, 28, 31], [2, 14, 32, 35], [2, 14, 33, 36], [2, 15, 16, 35], [2, 15, 17, 31], [2, 15, 18, 26], [2, 15, 19, 23], [2, 15, 20, 36], [2, 15, 21, 34], [2, 15, 24, 30], [2, 15, 27, 37], [2, 16, 19, 28], [2, 16, 21, 22], [2, 16, 23, 34], [2, 16, 27, 30], [2, 16, 29, 32], [2, 17, 19, 25], [2, 17, 20, 22], [2, 17, 21, 36], [2, 17, 26, 30], [2, 17, 32, 34], [2, 18, 19, 34], [2, 18, 20, 29], [2, 18, 21, 33], [2, 18, 22, 35], [2, 18, 25, 32], [2, 19, 26, 29], [2, 19, 27, 35], [2, 19, 32, 36], [2, 20, 23, 28], [2, 20, 24, 31], [2, 20, 25, 30], [2, 20, 27, 33], [2, 20, 32, 37], [2, 21, 24, 28], [2, 22, 23, 33], [2, 22, 25, 26], [2, 22, 28, 32], [2, 22, 30, 34], [2, 22, 31, 36], [2, 23, 24, 29], [2, 23, 26, 32], [2, 24, 35, 36], [2, 25, 27, 31], [2, 25, 35, 37], [2, 26, 27, 28], [2, 28, 29, 35], [2, 28, 34, 37], [2, 29, 36, 37], [2, 30, 32, 33], [2, 31, 33, 35], [3, 4, 5, 17], [3, 4, 6, 37], [3, 4, 7, 34], [3, 4, 8, 30], [3, 4, 9, 20], [3, 4, 10, 15], [3, 4, 12, 13], [3, 4, 14, 21], [3, 4, 19, 25], [3, 4, 22, 36], [3, 4, 23, 28], [3, 4, 24, 26], [3, 4, 27, 35], [3, 4, 29, 31], [3, 4, 32, 33], [3, 5, 6, 13], [3, 5, 7, 12], [3, 5, 8, 31], [3, 5, 9, 18], [3, 5, 11, 26], [3, 5, 14, 25], [3, 5, 15, 16], [3, 5, 19, 28], [3, 5, 20, 21], [3, 5, 22, 33], [3, 5, 24, 32], [3, 5, 27, 37], [3, 5, 29, 34], [3, 5, 30, 35], [3, 6, 7, 21], [3, 6, 8, 26], [3, 6, 9, 35], [3, 6, 10, 22], [3, 6, 11, 23], [3, 6, 12, 20], [3, 6, 14, 28], [3, 6, 15, 27], [3, 6, 16, 30], [3, 6, 17, 34], [3, 6, 18, 25], [3, 6, 19, 31], [3, 6, 24, 36], [3, 7, 8, 10], [3, 7, 9, 31], [3, 7, 11, 28], [3, 7, 13, 33], [3, 7, 14, 23], [3, 7, 15, 35], [3, 7, 17, 32], [3, 7, 18, 30], [3, 7, 20, 25], [3, 7, 22, 26], [3, 7, 24, 37], [3, 7, 27, 36], [3, 8, 9, 27], [3, 8, 11, 29], [3, 8, 12, 32], [3, 8, 13, 23], [3, 8, 14, 16], [3, 8, 15, 17], [3, 8, 18, 36], [3, 8, 21, 22], [3, 8, 24, 28], [3, 8, 25, 33], [3, 8, 34, 35], [3, 9, 10, 33], [3, 9, 11, 36], [3, 9, 12, 15], [3, 9, 13, 21], [3, 9, 16, 34], [3, 9, 19, 32], [3, 9, 22, 28], [3, 9, 23, 30], [3, 9, 25, 26], [3, 9, 29, 37], [3, 10, 11, 14], [3, 10, 12, 36], [3, 10, 13, 24], [3, 10, 16, 23], [3, 10, 17, 25], [3, 10, 18, 34], [3, 10, 19, 37], [3, 10, 20, 32], [3, 10, 21, 27], [3, 10, 26, 29], [3, 10, 28, 35], [3, 10, 30, 31], [3, 11, 13, 30], [3, 11, 15, 21], [3, 11, 16, 33], [3, 11, 17, 18], [3, 11, 19, 24], [3, 11, 20, 22], [3, 11, 27, 34], [3, 11, 31, 37], [3, 11, 32, 35], [3, 12, 14, 33], [3, 12, 16, 26], [3, 12, 17, 21], [3, 12, 18, 28], [3, 12, 19, 29], [3, 12, 22, 31], [3, 12, 25, 27], [3, 12, 30, 34], [3, 12, 35, 37], [3, 13, 15, 18], [3, 13, 16, 29], [3, 13, 17, 19], [3, 13, 22, 32], [3, 13, 25, 34], [3, 13, 26, 35], [3, 13, 28, 37], [3, 13, 31, 36], [3, 14, 15, 19], [3, 14, 17, 27], [3, 14, 18, 29], [3, 14, 20, 34], [3, 14, 22, 24], [3, 14, 26, 37], [3, 14, 30, 32], [3, 14, 35, 36], [3, 15, 20, 23], [3, 15, 24, 31], [3, 15, 25, 28], [3, 15, 26, 30], [3, 15, 29, 32], [3, 15, 33, 36], [3, 15, 34, 37], [3, 16, 17, 36], [3, 16, 18, 32], [3, 16, 19, 27], [3, 16, 20, 24], [3, 16, 21, 37], [3, 16, 22, 35], [3, 16, 25, 31], [3, 17, 20, 29], [3, 17, 22, 23], [3, 17, 24, 35], [3, 17, 28, 31], [3, 17, 30, 33], [3, 18, 20, 26], [3, 18, 21, 23], [3, 18, 22, 37], [3, 18, 27, 31], [3, 18, 33, 35], [3, 19, 20, 35], [3, 19, 21, 30], [3, 19, 22, 34], [3, 19, 23, 36], [3, 19, 26, 33], [3, 20, 27, 30], [3, 20, 28, 36], [3, 20, 33, 37], [3, 21, 24, 29], [3, 21, 25, 32], [3, 21, 26, 31], [3, 21, 28, 34], [3, 22, 25, 29], [3, 23, 24, 34], [3, 23, 26, 27], [3, 23, 29, 33], [3, 23, 31, 35], [3, 23, 32, 37], [3, 24, 25, 30], [3, 24, 27, 33], [3, 25, 36, 37], [3, 26, 28, 32], [3, 27, 28, 29], [3, 29, 30, 36], [3, 31, 33, 34], [3, 32, 34, 36], [4, 5, 6, 18], [4, 5, 8, 35], [4, 5, 9, 31], [4, 5, 10, 21], [4, 5, 11, 16], [4, 5, 13, 14], [4, 5, 15, 22], [4, 5, 20, 26], [4, 5, 23, 37], [4, 5, 24, 29], [4, 5, 25, 27], [4, 5, 28, 36], [4, 5, 30, 32], [4, 5, 33, 34], [4, 6, 7, 14], [4, 6, 8, 13], [4, 6, 9, 32], [4, 6, 10, 19], [4, 6, 12, 27], [4, 6, 15, 26], [4, 6, 16, 17], [4, 6, 20, 29], [4, 6, 21, 22], [4, 6, 23, 34], [4, 6, 25, 33], [4, 6, 30, 35], [4, 6, 31, 36], [4, 7, 8, 22], [4, 7, 9, 27], [4, 7, 10, 36], [4, 7, 11, 23], [4, 7, 12, 24], [4, 7, 13, 21], [4, 7, 15, 29], [4, 7, 16, 28], [4, 7, 17, 31], [4, 7, 18, 35], [4, 7, 19, 26], [4, 7, 20, 32], [4, 7, 25, 37], [4, 8, 9, 11], [4, 8, 10, 32], [4, 8, 12, 29], [4, 8, 14, 34], [4, 8, 15, 24], [4, 8, 16, 36], [4, 8, 18, 33], [4, 8, 19, 31], [4, 8, 21, 26], [4, 8, 23, 27], [4, 8, 28, 37], [4, 9, 10, 28], [4, 9, 12, 30], [4, 9, 13, 33], [4, 9, 14, 24], [4, 9, 15, 17], [4, 9, 16, 18], [4, 9, 19, 37], [4, 9, 22, 23], [4, 9, 25, 29], [4, 9, 26, 34], [4, 9, 35, 36], [4, 10, 11, 34], [4, 10, 12, 37], [4, 10, 13, 16], [4, 10, 14, 22], [4, 10, 17, 35], [4, 10, 20, 33], [4, 10, 23, 29], [4, 10, 24, 31], [4, 10, 26, 27], [4, 11, 12, 15], [4, 11, 13, 37], [4, 11, 14, 25], [4, 11, 17, 24], [4, 11, 18, 26], [4, 11, 19, 35], [4, 11, 21, 33], [4, 11, 22, 28], [4, 11, 27, 30], [4, 11, 29, 36], [4, 11, 31, 32], [4, 12, 14, 31], [4, 12, 16, 22], [4, 12, 17, 34], [4, 12, 18, 19], [4, 12, 20, 25], [4, 12, 21, 23], [4, 12, 28, 35], [4, 12, 33, 36], [4, 13, 15, 34], [4, 13, 17, 27], [4, 13, 18, 22], [4, 13, 19, 29], [4, 13, 20, 30], [4, 13, 23, 32], [4, 13, 26, 28], [4, 13, 31, 35], [4, 14, 16, 19], [4, 14, 17, 30], [4, 14, 18, 20], [4, 14, 23, 33], [4, 14, 26, 35], [4, 14, 27, 36], [4, 14, 32, 37], [4, 15, 16, 20], [4, 15, 18, 28], [4, 15, 19, 30], [4, 15, 21, 35], [4, 15, 23, 25], [4, 15, 31, 33], [4, 15, 36, 37], [4, 16, 21, 24], [4, 16, 25, 32], [4, 16, 26, 29], [4, 16, 27, 31], [4, 16, 30, 33], [4, 16, 34, 37], [4, 17, 18, 37], [4, 17, 19, 33], [4, 17, 20, 28], [4, 17, 21, 25], [4, 17, 23, 36], [4, 17, 26, 32], [4, 18, 21, 30], [4, 18, 23, 24], [4, 18, 25, 36], [4, 18, 29, 32], [4, 18, 31, 34], [4, 19, 21, 27], [4, 19, 22, 24], [4, 19, 28, 32], [4, 19, 34, 36], [4, 20, 21, 36], [4, 20, 22, 31], [4, 20, 23, 35], [4, 20, 24, 37], [4, 20, 27, 34], [4, 21, 28, 31], [4, 21, 29, 37], [4, 22, 25, 30], [4, 22, 26, 33], [4, 22, 27, 32], [4, 22, 29, 35], [4, 23, 26, 30], [4, 24, 25, 35], [4, 24, 27, 28], [4, 24, 30, 34], [4, 24, 32, 36], [4, 25, 26, 31], [4, 25, 28, 34], [4, 27, 29, 33], [4, 28, 29, 30], [4, 30, 31, 37], [4, 32, 34, 35], [4, 33, 35, 37], [5, 6, 7, 19], [5, 6, 9, 36], [5, 6, 10, 32], [5, 6, 11, 22], [5, 6, 12, 17], [5, 6, 14, 15], [5, 6, 16, 23], [5, 6, 21, 27], [5, 6, 25, 30], [5, 6, 26, 28], [5, 6, 29, 37], [5, 6, 31, 33], [5, 6, 34, 35], [5, 7, 8, 15], [5, 7, 9, 14], [5, 7, 10, 33], [5, 7, 11, 20], [5, 7, 13, 28], [5, 7, 16, 27], [5, 7, 17, 18], [5, 7, 21, 30], [5, 7, 22, 23], [5, 7, 24, 35], [5, 7, 26, 34], [5, 7, 31, 36], [5, 7, 32, 37], [5, 8, 9, 23], [5, 8, 10, 28], [5, 8, 11, 37], [5, 8, 12, 24], [5, 8, 13, 25], [5, 8, 14, 22], [5, 8, 16, 30], [5, 8, 17, 29], [5, 8, 18, 32], [5, 8, 19, 36], [5, 8, 20, 27], [5, 8, 21, 33], [5, 9, 10, 12], [5, 9, 11, 33], [5, 9, 13, 30], [5, 9, 15, 35], [5, 9, 16, 25], [5, 9, 17, 37], [5, 9, 19, 34], [5, 9, 20, 32], [5, 9, 22, 27], [5, 9, 24, 28], [5, 10, 11, 29], [5, 10, 13, 31], [5, 10, 14, 34], [5, 10, 15, 25], [5, 10, 16, 18], [5, 10, 17, 19], [5, 10, 23, 24], [5, 10, 26, 30], [5, 10, 27, 35], [5, 10, 36, 37], [5, 11, 12, 35], [5, 11, 14, 17], [5, 11, 15, 23], [5, 11, 18, 36], [5, 11, 21, 34], [5, 11, 24, 30], [5, 11, 25, 32], [5, 11, 27, 28], [5, 12, 13, 16], [5, 12, 15, 26], [5, 12, 18, 25], [5, 12, 19, 27], [5, 12, 20, 36], [5, 12, 22, 34], [5, 12, 23, 29], [5, 12, 28, 31], [5, 12, 30, 37], [5, 12, 32, 33], [5, 13, 15, 32], [5, 13, 17, 23], [5, 13, 18, 35], [5, 13, 19, 20], [5, 13, 21, 26], [5, 13, 22, 24], [5, 13, 29, 36], [5, 13, 34, 37], [5, 14, 16, 35], [5, 14, 18, 28], [5, 14, 19, 23], [5, 14, 20, 30], [5, 14, 21, 31], [5, 14, 24, 33], [5, 14, 27, 29], [5, 14, 32, 36], [5, 15, 17, 20], [5, 15, 18, 31], [5, 15, 19, 21], [5, 15, 24, 34], [5, 15, 27, 36], [5, 15, 28, 37], [5, 16, 17, 21], [5, 16, 19, 29], [5, 16, 20, 31], [5, 16, 22, 36], [5, 16, 24, 26], [5, 16, 32, 34], [5, 17, 22, 25], [5, 17, 26, 33], [5, 17, 27, 30], [5, 17, 28, 32], [5, 17, 31, 34], [5, 18, 20, 34], [5, 18, 21, 29], [5, 18, 22, 26], [5, 18, 24, 37], [5, 18, 27, 33], [5, 19, 22, 31], [5, 19, 24, 25], [5, 19, 26, 37], [5, 19, 30, 33], [5, 19, 32, 35], [5, 20, 22, 28], [5, 20, 23, 25], [5, 20, 29, 33], [5, 20, 35, 37], [5, 21, 22, 37], [5, 21, 23, 32], [5, 21, 24, 36], [5, 21, 28, 35], [5, 22, 29, 32], [5, 23, 26, 31], [5, 23, 27, 34], [5, 23, 28, 33], [5, 23, 30, 36], [5, 24, 27, 31], [5, 25, 26, 36], [5, 25, 28, 29], [5, 25, 31, 35], [5, 25, 33, 37], [5, 26, 27, 32], [5, 26, 29, 35], [5, 28, 30, 34], [5, 29, 30, 31], [5, 33, 35, 36], [6, 7, 8, 20], [6, 7, 10, 37], [6, 7, 11, 33], [6, 7, 12, 23], [6, 7, 13, 18], [6, 7, 15, 16], [6, 7, 17, 24], [6, 7, 22, 28], [6, 7, 26, 31], [6, 7, 27, 29], [6, 7, 32, 34], [6, 7, 35, 36], [6, 8, 9, 16], [6, 8, 10, 15], [6, 8, 11, 34], [6, 8, 12, 21], [6, 8, 14, 29], [6, 8, 17, 28], [6, 8, 18, 19], [6, 8, 22, 31], [6, 8, 23, 24], [6, 8, 25, 36], [6, 8, 27, 35], [6, 8, 32, 37], [6, 9, 10, 24], [6, 9, 11, 29], [6, 9, 13, 25], [6, 9, 14, 26], [6, 9, 15, 23], [6, 9, 17, 31], [6, 9, 18, 30], [6, 9, 19, 33], [6, 9, 20, 37], [6, 9, 21, 28], [6, 9, 22, 34], [6, 10, 11, 13], [6, 10, 12, 34], [6, 10, 14, 31], [6, 10, 16, 36], [6, 10, 17, 26], [6, 10, 20, 35], [6, 10, 21, 33], [6, 10, 23, 28], [6, 10, 25, 29], [6, 11, 12, 30], [6, 11, 14, 32], [6, 11, 15, 35], [6, 11, 16, 26], [6, 11, 17, 19], [6, 11, 18, 20], [6, 11, 24, 25], [6, 11, 27, 31], [6, 11, 28, 36], [6, 12, 13, 36], [6, 12, 15, 18], [6, 12, 16, 24], [6, 12, 19, 37], [6, 12, 22, 35], [6, 12, 25, 31], [6, 12, 26, 33], [6, 12, 28, 29], [6, 13, 14, 17], [6, 13, 16, 27], [6, 13, 19, 26], [6, 13, 20, 28], [6, 13, 21, 37], [6, 13, 23, 35], [6, 13, 24, 30], [6, 13, 29, 32], [6, 13, 33, 34], [6, 14, 16, 33], [6, 14, 18, 24], [6, 14, 19, 36], [6, 14, 20, 21], [6, 14, 22, 27], [6, 14, 23, 25], [6, 14, 30, 37], [6, 15, 17, 36], [6, 15, 19, 29], [6, 15, 20, 24], [6, 15, 21, 31], [6, 15, 22, 32], [6, 15, 25, 34], [6, 15, 28, 30], [6, 15, 33, 37], [6, 16, 18, 21], [6, 16, 19, 32], [6, 16, 20, 22], [6, 16, 25, 35], [6, 16, 28, 37], [6, 17, 18, 22], [6, 17, 20, 30], [6, 17, 21, 32], [6, 17, 23, 37], [6, 17, 25, 27], [6, 17, 33, 35], [6, 18, 23, 26], [6, 18, 27, 34], [6, 18, 28, 31], [6, 18, 29, 33], [6, 18, 32, 35], [6, 19, 21, 35], [6, 19, 22, 30], [6, 19, 23, 27], [6, 19, 28, 34], [6, 20, 23, 32], [6, 20, 25, 26], [6, 20, 31, 34], [6, 20, 33, 36], [6, 21, 23, 29], [6, 21, 24, 26], [6, 21, 30, 34], [6, 22, 24, 33], [6, 22, 25, 37], [6, 22, 29, 36], [6, 23, 30, 33], [6, 24, 27, 32], [6, 24, 28, 35], [6, 24, 29, 34], [6, 24, 31, 37], [6, 25, 28, 32], [6, 26, 27, 37], [6, 26, 29, 30], [6, 26, 32, 36], [6, 27, 28, 33], [6, 27, 30, 36], [6, 29, 31, 35], [6, 30, 31, 32], [6, 34, 36, 37], [7, 8, 9, 21], [7, 8, 12, 34], [7, 8, 13, 24], [7, 8, 14, 19], [7, 8, 16, 17], [7, 8, 18, 25], [7, 8, 23, 29], [7, 8, 27, 32], [7, 8, 28, 30], [7, 8, 33, 35], [7, 8, 36, 37], [7, 9, 10, 17], [7, 9, 11, 16], [7, 9, 12, 35], [7, 9, 13, 22], [7, 9, 15, 30], [7, 9, 18, 29], [7, 9, 19, 20], [7, 9, 23, 32], [7, 9, 24, 25], [7, 9, 26, 37], [7, 9, 28, 36], [7, 10, 11, 25], [7, 10, 12, 30], [7, 10, 14, 26], [7, 10, 15, 27], [7, 10, 16, 24], [7, 10, 18, 32], [7, 10, 19, 31], [7, 10, 20, 34], [7, 10, 22, 29], [7, 10, 23, 35], [7, 11, 12, 14], [7, 11, 13, 35], [7, 11, 15, 32], [7, 11, 17, 37], [7, 11, 18, 27], [7, 11, 21, 36], [7, 11, 22, 34], [7, 11, 24, 29], [7, 11, 26, 30], [7, 12, 13, 31], [7, 12, 15, 33], [7, 12, 16, 36], [7, 12, 17, 27], [7, 12, 18, 20], [7, 12, 19, 21], [7, 12, 25, 26], [7, 12, 28, 32], [7, 12, 29, 37], [7, 13, 14, 37], [7, 13, 16, 19], [7, 13, 17, 25], [7, 13, 23, 36], [7, 13, 26, 32], [7, 13, 27, 34], [7, 13, 29, 30], [7, 14, 15, 18], [7, 14, 17, 28], [7, 14, 20, 27], [7, 14, 21, 29], [7, 14, 24, 36], [7, 14, 25, 31], [7, 14, 30, 33], [7, 14, 34, 35], [7, 15, 17, 34], [7, 15, 19, 25], [7, 15, 20, 37], [7, 15, 21, 22], [7, 15, 23, 28], [7, 15, 24, 26], [7, 16, 18, 37], [7, 16, 20, 30], [7, 16, 21, 25], [7, 16, 22, 32], [7, 16, 23, 33], [7, 16, 26, 35], [7, 16, 29, 31], [7, 17, 19, 22], [7, 17, 20, 33], [7, 17, 21, 23], [7, 17, 26, 36], [7, 18, 19, 23], [7, 18, 21, 31], [7, 18, 22, 33], [7, 18, 26, 28], [7, 18, 34, 36], [7, 19, 24, 27], [7, 19, 28, 35], [7, 19, 29, 32], [7, 19, 30, 34], [7, 19, 33, 36], [7, 20, 22, 36], [7, 20, 23, 31], [7, 20, 24, 28], [7, 20, 29, 35], [7, 21, 24, 33], [7, 21, 26, 27], [7, 21, 32, 35], [7, 21, 34, 37], [7, 22, 24, 30], [7, 22, 25, 27], [7, 22, 31, 35], [7, 23, 25, 34], [7, 23, 30, 37], [7, 24, 31, 34], [7, 25, 28, 33], [7, 25, 29, 36], [7, 25, 30, 35], [7, 26, 29, 33], [7, 27, 30, 31], [7, 27, 33, 37], [7, 28, 29, 34], [7, 28, 31, 37], [7, 30, 32, 36], [7, 31, 32, 33], [8, 9, 10, 22], [8, 9, 13, 35], [8, 9, 14, 25], [8, 9, 15, 20], [8, 9, 17, 18], [8, 9, 19, 26], [8, 9, 24, 30], [8, 9, 28, 33], [8, 9, 29, 31], [8, 9, 34, 36], [8, 10, 11, 18], [8, 10, 12, 17], [8, 10, 13, 36], [8, 10, 14, 23], [8, 10, 16, 31], [8, 10, 19, 30], [8, 10, 20, 21], [8, 10, 24, 33], [8, 10, 25, 26], [8, 10, 29, 37], [8, 11, 12, 26], [8, 11, 13, 31], [8, 11, 15, 27], [8, 11, 16, 28], [8, 11, 17, 25], [8, 11, 19, 33], [8, 11, 20, 32], [8, 11, 21, 35], [8, 11, 23, 30], [8, 11, 24, 36], [8, 12, 13, 15], [8, 12, 14, 36], [8, 12, 16, 33], [8, 12, 19, 28], [8, 12, 22, 37], [8, 12, 23, 35], [8, 12, 25, 30], [8, 12, 27, 31], [8, 13, 14, 32], [8, 13, 16, 34], [8, 13, 17, 37], [8, 13, 18, 28], [8, 13, 19, 21], [8, 13, 20, 22], [8, 13, 26, 27], [8, 13, 29, 33], [8, 14, 17, 20], [8, 14, 18, 26], [8, 14, 24, 37], [8, 14, 27, 33], [8, 14, 28, 35], [8, 14, 30, 31], [8, 15, 16, 19], [8, 15, 18, 29], [8, 15, 21, 28], [8, 15, 22, 30], [8, 15, 25, 37], [8, 15, 26, 32], [8, 15, 31, 34], [8, 15, 35, 36], [8, 16, 18, 35], [8, 16, 20, 26], [8, 16, 22, 23], [8, 16, 24, 29], [8, 16, 25, 27], [8, 17, 21, 31], [8, 17, 22, 26], [8, 17, 23, 33], [8, 17, 24, 34], [8, 17, 27, 36], [8, 17, 30, 32], [8, 18, 20, 23], [8, 18, 21, 34], [8, 18, 22, 24], [8, 18, 27, 37], [8, 19, 20, 24], [8, 19, 22, 32], [8, 19, 23, 34], [8, 19, 27, 29], [8, 19, 35, 37], [8, 20, 25, 28], [8, 20, 29, 36], [8, 20, 30, 33], [8, 20, 31, 35], [8, 20, 34, 37], [8, 21, 23, 37], [8, 21, 24, 32], [8, 21, 25, 29], [8, 21, 30, 36], [8, 22, 25, 34], [8, 22, 27, 28], [8, 22, 33, 36], [8, 23, 25, 31], [8, 23, 26, 28], [8, 23, 32, 36], [8, 24, 26, 35], [8, 25, 32, 35], [8, 26, 29, 34], [8, 26, 30, 37], [8, 26, 31, 36], [8, 27, 30, 34], [8, 28, 31, 32], [8, 29, 30, 35], [8, 31, 33, 37], [8, 32, 33, 34], [9, 10, 11, 23], [9, 10, 14, 36], [9, 10, 15, 26], [9, 10, 16, 21], [9, 10, 18, 19], [9, 10, 20, 27], [9, 10, 25, 31], [9, 10, 29, 34], [9, 10, 30, 32], [9, 10, 35, 37], [9, 11, 12, 19], [9, 11, 13, 18], [9, 11, 14, 37], [9, 11, 15, 24], [9, 11, 17, 32], [9, 11, 20, 31], [9, 11, 21, 22], [9, 11, 25, 34], [9, 11, 26, 27], [9, 12, 13, 27], [9, 12, 14, 32], [9, 12, 16, 28], [9, 12, 17, 29], [9, 12, 18, 26], [9, 12, 20, 34], [9, 12, 21, 33], [9, 12, 22, 36], [9, 12, 24, 31], [9, 12, 25, 37], [9, 13, 14, 16], [9, 13, 15, 37], [9, 13, 17, 34], [9, 13, 20, 29], [9, 13, 24, 36], [9, 13, 26, 31], [9, 13, 28, 32], [9, 14, 15, 33], [9, 14, 17, 35], [9, 14, 19, 29], [9, 14, 20, 22], [9, 14, 21, 23], [9, 14, 27, 28], [9, 14, 30, 34], [9, 15, 18, 21], [9, 15, 19, 27], [9, 15, 28, 34], [9, 15, 29, 36], [9, 15, 31, 32], [9, 16, 17, 20], [9, 16, 19, 30], [9, 16, 22, 29], [9, 16, 23, 31], [9, 16, 27, 33], [9, 16, 32, 35], [9, 16, 36, 37], [9, 17, 19, 36], [9, 17, 21, 27], [9, 17, 23, 24], [9, 17, 25, 30], [9, 17, 26, 28], [9, 18, 22, 32], [9, 18, 23, 27], [9, 18, 24, 34], [9, 18, 25, 35], [9, 18, 28, 37], [9, 18, 31, 33], [9, 19, 21, 24], [9, 19, 22, 35], [9, 19, 23, 25], [9, 20, 21, 25], [9, 20, 23, 33], [9, 20, 24, 35], [9, 20, 28, 30], [9, 21, 26, 29], [9, 21, 30, 37], [9, 21, 31, 34], [9, 21, 32, 36], [9, 22, 25, 33], [9, 22, 26, 30], [9, 22, 31, 37], [9, 23, 26, 35], [9, 23, 28, 29], [9, 23, 34, 37], [9, 24, 26, 32], [9, 24, 27, 29], [9, 24, 33, 37], [9, 25, 27, 36], [9, 26, 33, 36], [9, 27, 30, 35], [9, 27, 32, 37], [9, 28, 31, 35], [9, 29, 32, 33], [9, 30, 31, 36], [9, 33, 34, 35], [10, 11, 12, 24], [10, 11, 15, 37], [10, 11, 16, 27], [10, 11, 17, 22], [10, 11, 19, 20], [10, 11, 21, 28], [10, 11, 26, 32], [10, 11, 30, 35], [10, 11, 31, 33], [10, 12, 13, 20], [10, 12, 14, 19], [10, 12, 16, 25], [10, 12, 18, 33], [10, 12, 21, 32], [10, 12, 22, 23], [10, 12, 26, 35], [10, 12, 27, 28], [10, 13, 14, 28], [10, 13, 15, 33], [10, 13, 17, 29], [10, 13, 18, 30], [10, 13, 19, 27], [10, 13, 21, 35], [10, 13, 22, 34], [10, 13, 23, 37], [10, 13, 25, 32], [10, 14, 15, 17], [10, 14, 18, 35], [10, 14, 21, 30], [10, 14, 25, 37], [10, 14, 27, 32], [10, 14, 29, 33], [10, 15, 16, 34], [10, 15, 18, 36], [10, 15, 20, 30], [10, 15, 21, 23], [10, 15, 22, 24], [10, 15, 28, 29], [10, 15, 31, 35], [10, 16, 19, 22], [10, 16, 20, 28], [10, 16, 29, 35], [10, 16, 30, 37], [10, 16, 32, 33], [10, 17, 18, 21], [10, 17, 20, 31], [10, 17, 23, 30], [10, 17, 24, 32], [10, 17, 28, 34], [10, 17, 33, 36], [10, 18, 20, 37], [10, 18, 22, 28], [10, 18, 24, 25], [10, 18, 26, 31], [10, 18, 27, 29], [10, 19, 23, 33], [10, 19, 24, 28], [10, 19, 25, 35], [10, 19, 26, 36], [10, 19, 32, 34], [10, 20, 22, 25], [10, 20, 23, 36], [10, 20, 24, 26], [10, 21, 22, 26], [10, 21, 24, 34], [10, 21, 25, 36], [10, 21, 29, 31], [10, 22, 27, 30], [10, 22, 32, 35], [10, 22, 33, 37], [10, 23, 26, 34], [10, 23, 27, 31], [10, 24, 27, 36], [10, 24, 29, 30], [10, 25, 27, 33], [10, 25, 28, 30], [10, 26, 28, 37], [10, 27, 34, 37], [10, 28, 31, 36], [10, 29, 32, 36], [10, 30, 33, 34], [10, 31, 32, 37], [10, 34, 35, 36], [11, 12, 13, 25], [11, 12, 17, 28], [11, 12, 18, 23], [11, 12, 20, 21], [11, 12, 22, 29], [11, 12, 27, 33], [11, 12, 31, 36], [11, 12, 32, 34], [11, 13, 14, 21], [11, 13, 15, 20], [11, 13, 17, 26], [11, 13, 19, 34], [11, 13, 22, 33], [11, 13, 23, 24], [11, 13, 27, 36], [11, 13, 28, 29], [11, 14, 15, 29], [11, 14, 16, 34], [11, 14, 18, 30], [11, 14, 19, 31], [11, 14, 20, 28], [11, 14, 22, 36], [11, 14, 23, 35], [11, 14, 26, 33], [11, 15, 16, 18], [11, 15, 19, 36], [11, 15, 22, 31], [11, 15, 28, 33], [11, 15, 30, 34], [11, 16, 17, 35], [11, 16, 19, 37], [11, 16, 21, 31], [11, 16, 22, 24], [11, 16, 23, 25], [11, 16, 29, 30], [11, 16, 32, 36], [11, 17, 20, 23], [11, 17, 21, 29], [11, 17, 30, 36], [11, 17, 33, 34], [11, 18, 19, 22], [11, 18, 21, 32], [11, 18, 24, 31], [11, 18, 25, 33], [11, 18, 29, 35], [11, 18, 34, 37], [11, 19, 23, 29], [11, 19, 25, 26], [11, 19, 27, 32], [11, 19, 28, 30], [11, 20, 24, 34], [11, 20, 25, 29], [11, 20, 26, 36], [11, 20, 27, 37], [11, 20, 33, 35], [11, 21, 23, 26], [11, 21, 24, 37], [11, 21, 25, 27], [11, 22, 23, 27], [11, 22, 25, 35], [11, 22, 26, 37], [11, 22, 30, 32], [11, 23, 28, 31], [11, 23, 33, 36], [11, 24, 27, 35], [11, 24, 28, 32], [11, 25, 28, 37], [11, 25, 30, 31], [11, 26, 28, 34], [11, 26, 29, 31], [11, 29, 32, 37], [11, 30, 33, 37], [11, 31, 34, 35], [11, 35, 36, 37], [12, 13, 14, 26], [12, 13, 18, 29], [12, 13, 19, 24], [12, 13, 21, 22], [12, 13, 23, 30], [12, 13, 28, 34], [12, 13, 32, 37], [12, 13, 33, 35], [12, 14, 15, 22], [12, 14, 16, 21], [12, 14, 18, 27], [12, 14, 20, 35], [12, 14, 23, 34], [12, 14, 24, 25], [12, 14, 28, 37], [12, 14, 29, 30], [12, 15, 16, 30], [12, 15, 17, 35], [12, 15, 19, 31], [12, 15, 20, 32], [12, 15, 21, 29], [12, 15, 23, 37], [12, 15, 24, 36], [12, 15, 27, 34], [12, 16, 17, 19], [12, 16, 20, 37], [12, 16, 23, 32], [12, 16, 29, 34], [12, 16, 31, 35], [12, 17, 18, 36], [12, 17, 22, 32], [12, 17, 23, 25], [12, 17, 24, 26], [12, 17, 30, 31], [12, 17, 33, 37], [12, 18, 21, 24], [12, 18, 22, 30], [12, 18, 31, 37], [12, 18, 34, 35], [12, 19, 20, 23], [12, 19, 22, 33], [12, 19, 25, 32], [12, 19, 26, 34], [12, 19, 30, 36], [12, 20, 24, 30], [12, 20, 26, 27], [12, 20, 28, 33], [12, 20, 29, 31], [12, 21, 25, 35], [12, 21, 26, 30], [12, 21, 27, 37], [12, 21, 34, 36], [12, 22, 24, 27], [12, 22, 26, 28], [12, 23, 24, 28], [12, 23, 26, 36], [12, 23, 31, 33], [12, 24, 29, 32], [12, 24, 34, 37], [12, 25, 28, 36], [12, 25, 29, 33], [12, 26, 31, 32], [12, 27, 29, 35], [12, 27, 30, 32], [12, 32, 35, 36], [13, 14, 15, 27], [13, 14, 19, 30], [13, 14, 20, 25], [13, 14, 22, 23], [13, 14, 24, 31], [13, 14, 29, 35], [13, 14, 34, 36], [13, 15, 16, 23], [13, 15, 17, 22], [13, 15, 19, 28], [13, 15, 21, 36], [13, 15, 24, 35], [13, 15, 25, 26], [13, 15, 30, 31], [13, 16, 17, 31], [13, 16, 18, 36], [13, 16, 20, 32], [13, 16, 21, 33], [13, 16, 22, 30], [13, 16, 25, 37], [13, 16, 28, 35], [13, 17, 18, 20], [13, 17, 24, 33], [13, 17, 30, 35], [13, 17, 32, 36], [13, 18, 19, 37], [13, 18, 23, 33], [13, 18, 24, 26], [13, 18, 25, 27], [13, 18, 31, 32], [13, 19, 22, 25], [13, 19, 23, 31], [13, 19, 35, 36], [13, 20, 21, 24], [13, 20, 23, 34], [13, 20, 26, 33], [13, 20, 27, 35], [13, 20, 31, 37], [13, 21, 25, 31], [13, 21, 27, 28], [13, 21, 29, 34], [13, 21, 30, 32], [13, 22, 26, 36], [13, 22, 27, 31], [13, 22, 35, 37], [13, 23, 25, 28], [13, 23, 27, 29], [13, 24, 25, 29], [13, 24, 27, 37], [13, 24, 32, 34], [13, 25, 30, 33], [13, 26, 29, 37], [13, 26, 30, 34], [13, 27, 32, 33], [13, 28, 30, 36], [13, 28, 31, 33], [13, 33, 36, 37], [14, 15, 16, 28], [14, 15, 20, 31], [14, 15, 21, 26], [14, 15, 23, 24], [14, 15, 25, 32], [14, 15, 30, 36], [14, 15, 35, 37], [14, 16, 17, 24], [14, 16, 18, 23], [14, 16, 20, 29], [14, 16, 22, 37], [14, 16, 25, 36], [14, 16, 26, 27], [14, 16, 31, 32], [14, 17, 18, 32], [14, 17, 19, 37], [14, 17, 21, 33], [14, 17, 22, 34], [14, 17, 23, 31], [14, 17, 29, 36], [14, 18, 19, 21], [14, 18, 25, 34], [14, 18, 31, 36], [14, 18, 33, 37], [14, 19, 24, 34], [14, 19, 25, 27], [14, 19, 26, 28], [14, 19, 32, 33], [14, 20, 23, 26], [14, 20, 24, 32], [14, 20, 36, 37], [14, 21, 22, 25], [14, 21, 24, 35], [14, 21, 27, 34], [14, 21, 28, 36], [14, 22, 26, 32], [14, 22, 28, 29], [14, 22, 30, 35], [14, 22, 31, 33], [14, 23, 27, 37], [14, 23, 28, 32], [14, 24, 26, 29], [14, 24, 28, 30], [14, 25, 26, 30], [14, 25, 33, 35], [14, 26, 31, 34], [14, 27, 31, 35], [14, 28, 33, 34], [14, 29, 31, 37], [14, 29, 32, 34], [15, 16, 17, 29], [15, 16, 21, 32], [15, 16, 22, 27], [15, 16, 24, 25], [15, 16, 26, 33], [15, 16, 31, 37], [15, 17, 18, 25], [15, 17, 19, 24], [15, 17, 21, 30], [15, 17, 26, 37], [15, 17, 27, 28], [15, 17, 32, 33], [15, 18, 19, 33], [15, 18, 22, 34], [15, 18, 23, 35], [15, 18, 24, 32], [15, 18, 30, 37], [15, 19, 20, 22], [15, 19, 26, 35], [15, 19, 32, 37], [15, 20, 25, 35], [15, 20, 26, 28], [15, 20, 27, 29], [15, 20, 33, 34], [15, 21, 24, 27], [15, 21, 25, 33], [15, 22, 23, 26], [15, 22, 25, 36], [15, 22, 28, 35], [15, 22, 29, 37], [15, 23, 27, 33], [15, 23, 29, 30], [15, 23, 31, 36], [15, 23, 32, 34], [15, 24, 29, 33], [15, 25, 27, 30], [15, 25, 29, 31], [15, 26, 27, 31], [15, 26, 34, 36], [15, 27, 32, 35], [15, 28, 32, 36], [15, 29, 34, 35], [15, 30, 33, 35], [16, 17, 18, 30], [16, 17, 22, 33], [16, 17, 23, 28], [16, 17, 25, 26], [16, 17, 27, 34], [16, 18, 19, 26], [16, 18, 20, 25], [16, 18, 22, 31], [16, 18, 28, 29], [16, 18, 33, 34], [16, 19, 20, 34], [16, 19, 23, 35], [16, 19, 24, 36], [16, 19, 25, 33], [16, 20, 21, 23], [16, 20, 27, 36], [16, 21, 26, 36], [16, 21, 27, 29], [16, 21, 28, 30], [16, 21, 34, 35], [16, 22, 25, 28], [16, 22, 26, 34], [16, 23, 24, 27], [16, 23, 26, 37], [16, 23, 29, 36], [16, 24, 28, 34], [16, 24, 30, 31], [16, 24, 32, 37], [16, 24, 33, 35], [16, 25, 30, 34], [16, 26, 28, 31], [16, 26, 30, 32], [16, 27, 28, 32], [16, 27, 35, 37], [16, 28, 33, 36], [16, 29, 33, 37], [16, 30, 35, 36], [16, 31, 34, 36], [17, 18, 19, 31], [17, 18, 23, 34], [17, 18, 24, 29], [17, 18, 26, 27], [17, 18, 28, 35], [17, 19, 20, 27], [17, 19, 21, 26], [17, 19, 23, 32], [17, 19, 29, 30], [17, 19, 34, 35], [17, 20, 21, 35], [17, 20, 24, 36], [17, 20, 25, 37], [17, 20, 26, 34], [17, 21, 22, 24], [17, 21, 28, 37], [17, 22, 27, 37], [17, 22, 28, 30], [17, 22, 29, 31], [17, 22, 35, 36], [17, 23, 26, 29], [17, 23, 27, 35], [17, 24, 25, 28], [17, 24, 30, 37], [17, 25, 29, 35], [17, 25, 31, 32], [17, 25, 34, 36], [17, 26, 31, 35], [17, 27, 29, 32], [17, 27, 31, 33], [17, 28, 29, 33], [17, 29, 34, 37], [17, 31, 36, 37], [17, 32, 35, 37], [18, 19, 20, 32], [18, 19, 24, 35], [18, 19, 25, 30], [18, 19, 27, 28], [18, 19, 29, 36], [18, 20, 21, 28], [18, 20, 22, 27], [18, 20, 24, 33], [18, 20, 30, 31], [18, 20, 35, 36], [18, 21, 22, 36], [18, 21, 25, 37], [18, 21, 27, 35], [18, 22, 23, 25], [18, 23, 29, 31], [18, 23, 30, 32], [18, 23, 36, 37], [18, 24, 27, 30], [18, 24, 28, 36], [18, 25, 26, 29], [18, 26, 30, 36], [18, 26, 32, 33], [18, 26, 35, 37], [18, 27, 32, 36], [18, 28, 30, 33], [18, 28, 32, 34], [18, 29, 30, 34], [19, 20, 21, 33], [19, 20, 25, 36], [19, 20, 26, 31], [19, 20, 28, 29], [19, 20, 30, 37], [19, 21, 22, 29], [19, 21, 23, 28], [19, 21, 25, 34], [19, 21, 31, 32], [19, 21, 36, 37], [19, 22, 23, 37], [19, 22, 28, 36], [19, 23, 24, 26], [19, 24, 30, 32], [19, 24, 31, 33], [19, 25, 28, 31], [19, 25, 29, 37], [19, 26, 27, 30], [19, 27, 31, 37], [19, 27, 33, 34], [19, 28, 33, 37], [19, 29, 31, 34], [19, 29, 33, 35], [19, 30, 31, 35], [20, 21, 22, 34], [20, 21, 26, 37], [20, 21, 27, 32], [20, 21, 29, 30], [20, 22, 23, 30], [20, 22, 24, 29], [20, 22, 26, 35], [20, 22, 32, 33], [20, 23, 29, 37], [20, 24, 25, 27], [20, 25, 31, 33], [20, 25, 32, 34], [20, 26, 29, 32], [20, 27, 28, 31], [20, 28, 34, 35], [20, 30, 32, 35], [20, 30, 34, 36], [20, 31, 32, 36], [21, 22, 23, 35], [21, 22, 28, 33], [21, 22, 30, 31], [21, 23, 24, 31], [21, 23, 25, 30], [21, 23, 27, 36], [21, 23, 33, 34], [21, 25, 26, 28], [21, 26, 32, 34], [21, 26, 33, 35], [21, 27, 30, 33], [21, 28, 29, 32], [21, 29, 35, 36], [21, 31, 33, 36], [21, 31, 35, 37], [21, 32, 33, 37], [22, 23, 24, 36], [22, 23, 29, 34], [22, 23, 31, 32], [22, 24, 25, 32], [22, 24, 26, 31], [22, 24, 28, 37], [22, 24, 34, 35], [22, 26, 27, 29], [22, 27, 33, 35], [22, 27, 34, 36], [22, 28, 31, 34], [22, 29, 30, 33], [22, 30, 36, 37], [22, 32, 34, 37], [23, 24, 25, 37], [23, 24, 30, 35], [23, 24, 32, 33], [23, 25, 26, 33], [23, 25, 27, 32], [23, 25, 35, 36], [23, 27, 28, 30], [23, 28, 34, 36], [23, 28, 35, 37], [23, 29, 32, 35], [23, 30, 31, 34], [24, 25, 31, 36], [24, 25, 33, 34], [24, 26, 27, 34], [24, 26, 28, 33], [24, 26, 36, 37], [24, 28, 29, 31], [24, 29, 35, 37], [24, 30, 33, 36], [24, 31, 32, 35], [25, 26, 32, 37], [25, 26, 34, 35], [25, 27, 28, 35], [25, 27, 29, 34], [25, 29, 30, 32], [25, 31, 34, 37], [25, 32, 33, 36], [26, 27, 35, 36], [26, 28, 29, 36], [26, 28, 30, 35], [26, 30, 31, 33], [26, 33, 34, 37], [27, 28, 36, 37], [27, 29, 30, 37], [27, 29, 31, 36], [27, 31, 32, 34], [28, 30, 32, 37], [28, 32, 33, 35], [29, 33, 34, 36], [30, 34, 35, 37]]
|
class TwoGraph(IncidenceStructure):
'\n Two-graphs class.\n\n A two-graph on `n` points is a 3-uniform hypergraph, i.e. a family `T\n \\subset \\binom {[n]}{3}` of `3`-sets, such that any `4`-set `S\\subset [n]`\n of size four contains an even number of elements of `T`. For more\n information, see the documentation of the\n :mod:`~sage.combinat.designs.twographs` module.\n\n '
def __init__(self, points=None, blocks=None, incidence_matrix=None, name=None, check=False, copy=True):
'\n Constructor of the class\n\n TESTS::\n\n sage: from sage.combinat.designs.twographs import TwoGraph\n sage: TwoGraph([[1,2]])\n Incidence structure with 2 points and 1 blocks\n sage: TwoGraph([[1,2]], check=True)\n Traceback (most recent call last):\n ...\n AssertionError: the structure is not a 2-graph!\n sage: p = graphs.PetersenGraph().twograph() # needs sage.modules\n sage: TwoGraph(p, check=True) # needs sage.modules\n Incidence structure with 10 points and 60 blocks\n '
IncidenceStructure.__init__(self, points=points, blocks=blocks, incidence_matrix=incidence_matrix, name=name, check=False, copy=copy)
if check:
assert is_twograph(self), 'the structure is not a 2-graph!'
def is_regular_twograph(self, alpha=False):
'\n Test if the :class:`TwoGraph` is regular, i.e. is a 2-design.\n\n Namely, each pair of elements of :meth:`ground_set` is contained in\n exactly ``alpha`` triples.\n\n INPUT:\n\n - ``alpha`` -- (optional, default is ``False``) return the value of\n ``alpha``, if possible.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: p = graphs.PetersenGraph().twograph()\n sage: p.is_regular_twograph(alpha=True)\n 4\n sage: p.is_regular_twograph()\n True\n sage: p = graphs.PathGraph(5).twograph()\n sage: p.is_regular_twograph(alpha=True)\n False\n sage: p.is_regular_twograph()\n False\n '
(r, (_, _, _, a)) = self.is_t_design(t=2, k=3, return_parameters=True)
if (r and alpha):
return a
return r
def descendant(self, v):
'\n The descendant :class:`graph <sage.graphs.graph.Graph>` at ``v``\n\n The :mod:`switching class of graphs <sage.combinat.designs.twographs>`\n corresponding to ``self`` contains a graph ``D`` with ``v`` its own connected\n component; removing ``v`` from ``D``, one obtains the descendant graph of\n ``self`` at ``v``, which is constructed by this method.\n\n INPUT:\n\n - ``v`` -- an element of :meth:`ground_set`\n\n EXAMPLES::\n\n sage: p = graphs.PetersenGraph().twograph().descendant(0) # needs sage.modules\n sage: p.is_strongly_regular(parameters=True) # needs sage.modules\n (9, 4, 1, 2)\n '
from sage.graphs.graph import Graph
return Graph([[z for z in x if (z != v)] for x in self.blocks() if (v in x)])
def complement(self):
'\n The two-graph which is the complement of ``self``\n\n That is, the two-graph consisting exactly of triples not in ``self``.\n Note that this is different from :meth:`complement\n <sage.combinat.designs.incidence_structures.IncidenceStructure.complement>`\n of the :class:`parent class\n <sage.combinat.designs.incidence_structures.IncidenceStructure>`.\n\n EXAMPLES::\n\n sage: p = graphs.CompleteGraph(8).line_graph().twograph() # needs sage.modules\n sage: pc = p.complement(); pc # needs sage.modules\n Incidence structure with 28 points and 1260 blocks\n\n TESTS::\n\n sage: from sage.combinat.designs.twographs import is_twograph\n sage: is_twograph(pc) # needs sage.modules\n True\n '
return super().complement(uniform=True)
|
def taylor_twograph(q):
"\n constructing Taylor's two-graph for `U_3(q)`, `q` odd prime power\n\n The Taylor's two-graph `T` has the `q^3+1` points of the projective plane over `F_{q^2}`\n singular w.r.t. the non-degenerate Hermitean form `S` preserved by `U_3(q)` as its ground set;\n the triples are `\\{x,y,z\\}` satisfying the condition that `S(x,y)S(y,z)S(z,x)` is square\n (respectively non-square) if `q \\cong 1 \\mod 4` (respectively if `q \\cong 3 \\mod 4`).\n See §7E of [BL1984]_.\n\n There is also a `2-(q^3+1,q+1,1)`-design on these `q^3+1` points, known as the unital of\n order `q`, also invariant under `U_3(q)`.\n\n INPUT:\n\n - ``q`` -- a power of an odd prime\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.twographs import taylor_twograph\n sage: T = taylor_twograph(3); T # needs sage.rings.finite_rings\n Incidence structure with 28 points and 1260 blocks\n "
from sage.graphs.generators.classical_geometries import TaylorTwographSRG
return TaylorTwographSRG(q).twograph()
|
def is_twograph(T) -> bool:
'\n Check whether the incidence system `T` is a two-graph.\n\n INPUT:\n\n - ``T`` -- an :class:`incidence structure <sage.combinat.designs.IncidenceStructure>`\n\n EXAMPLES:\n\n a two-graph from a graph::\n\n sage: from sage.combinat.designs.twographs import (is_twograph, TwoGraph)\n sage: p = graphs.PetersenGraph().twograph() # needs sage.modules\n sage: is_twograph(p) # needs sage.modules\n True\n\n a non-regular 2-uniform hypergraph which is a two-graph::\n\n sage: is_twograph(TwoGraph([[1,2,3],[1,2,4]]))\n True\n\n TESTS:\n\n wrong size of blocks::\n\n sage: is_twograph(designs.projective_plane(3)) # needs sage.schemes\n False\n\n a triple system which is not a two-graph::\n\n sage: is_twograph(designs.projective_plane(2)) # needs sage.schemes\n False\n '
if (not T.is_uniform(3)):
return False
v_to_blocks = {v: set() for v in range(T.num_points())}
for B in T._blocks:
B = frozenset(B)
for x in B:
v_to_blocks[x].add(B)
def has_triple(x_y_z):
(x, y, z) = x_y_z
return bool(((v_to_blocks[x] & v_to_blocks[y]) & v_to_blocks[z]))
for quad in combinations(range(T.num_points()), 4):
if ((sum(map(has_triple, combinations(quad, 3))) % 2) == 1):
return False
return True
|
def twograph_descendant(G, v, name=None):
"\n Return the descendant graph w.r.t. vertex `v` of the two-graph of `G`\n\n In the :mod:`switching class <sage.combinat.designs.twographs>` of `G`,\n construct a graph `\\Delta` with `v` an isolated vertex, and return the subgraph\n `\\Delta \\setminus v`. It is equivalent to, although much faster than, computing the\n :meth:`TwoGraph.descendant` of :meth:`two-graph of G <sage.graphs.graph.Graph.twograph>`, as the\n intermediate two-graph is not constructed.\n\n INPUT:\n\n - ``G`` -- a :class:`graph <sage.graphs.graph.Graph>`\n\n - ``v`` -- a vertex of ``G``\n\n - ``name`` -- (optional) ``None`` - no name, otherwise derive from the construction\n\n EXAMPLES:\n\n one of s.r.g.'s from the :mod:`database <sage.graphs.strongly_regular_db>`::\n\n sage: from sage.combinat.designs.twographs import twograph_descendant\n sage: A = graphs.strongly_regular_graph(280,135,70) # optional - gap_package_design internet\n sage: twograph_descendant(A, 0).is_strongly_regular(parameters=True) # optional - gap_package_design internet\n (279, 150, 85, 75)\n\n TESTS::\n\n sage: T8 = graphs.CompleteGraph(8).line_graph()\n sage: v = T8.vertices(sort=True)[0]\n sage: twograph_descendant(T8, v) == T8.twograph().descendant(v) # needs sage.modules\n True\n sage: twograph_descendant(T8, v).is_strongly_regular(parameters=True)\n (27, 16, 10, 8)\n sage: p = graphs.PetersenGraph()\n sage: twograph_descendant(p, 5)\n Graph on 9 vertices\n sage: twograph_descendant(p, 5, name=True)\n descendant of Petersen graph at 5: Graph on 9 vertices\n "
G = G.seidel_switching(G.neighbors(v), inplace=False)
G.delete_vertex(v)
if name:
G.name(((('descendant of ' + G.name()) + ' at ') + str(v)))
else:
G.name('')
return G
|
class Diagram(ClonableArray, metaclass=InheritComparisonClasscallMetaclass):
"\n Combinatorial diagrams with positions indexed by rows and columns.\n\n The positions are indexed by rows and columns as in a matrix. For example,\n a Ferrers diagram is a diagram obtained from a partition\n `\\lambda = (\\lambda_0, \\lambda_1, \\ldots, \\lambda_{\\ell})`, where the\n cells are in rows `i` for `0 \\leq i \\leq \\ell` and the cells in row `i`\n consist of `(i,j)` for `0 \\leq j < \\lambda_i`. In English notation, the\n indices are read from top left to bottom right as in a matrix.\n\n Indexing conventions are the same as\n :class:`~sage.combinat.partition.Partition`. Printing the diagram of a\n partition, however, will always be in English notation.\n\n EXAMPLES:\n\n To create an arbitrary diagram, pass a list of all cells::\n\n sage: from sage.combinat.diagram import Diagram\n sage: cells = [(0,0), (0,1), (1,0), (1,1), (4,4), (4,5), (4,6), (5,4), (7, 6)]\n sage: D = Diagram(cells); D\n [(0, 0), (0, 1), (1, 0), (1, 1), (4, 4), (4, 5), (4, 6), (5, 4), (7, 6)]\n\n We can visualize the diagram by printing ``O``'s and ``.``'s. ``O``'s are\n present in the cells which are present in the diagram and a ``.`` represents\n the absence of a cell in the diagram::\n\n sage: D.pp()\n O O . . . . .\n O O . . . . .\n . . . . . . .\n . . . . . . .\n . . . . O O O\n . . . . O . .\n . . . . . . .\n . . . . . . O\n\n We can also check if certain cells are contained in a given diagram::\n\n sage: (1, 0) in D\n True\n sage: (2, 2) in D\n False\n\n If you know that there are entire empty rows or columns at the end of the\n diagram, you can manually pass them with keyword arguments ``n_rows=`` or\n ``n_cols=``::\n\n sage: Diagram([(0,0), (0,3), (2,2), (2,4)]).pp()\n O . . O .\n . . . . .\n . . O . O\n sage: Diagram([(0,0), (0,3), (2,2), (2,4)], n_rows=6, n_cols=6).pp()\n O . . O . .\n . . . . . .\n . . O . O .\n . . . . . .\n . . . . . .\n . . . . . .\n "
@staticmethod
def __classcall_private__(self, cells, n_rows=None, n_cols=None, check=True):
'\n Normalize the input so that it lives in the correct parent.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagram\n sage: D = Diagram([(0,0), (0,3), (2,2), (2,4)])\n sage: D.parent()\n Combinatorial diagrams\n '
return Diagrams()(cells, n_rows, n_cols, check)
def __init__(self, parent, cells, n_rows=None, n_cols=None, check=True):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagram\n sage: D1 = Diagram([(0,2),(0,3),(1,1),(3,2)])\n sage: D1.cells()\n [(0, 2), (0, 3), (1, 1), (3, 2)]\n sage: D1.nrows()\n 4\n sage: D1.ncols()\n 4\n sage: TestSuite(D1).run()\n\n We can specify the number of rows and columns explicitly,\n in case they are supposed to be empty::\n\n sage: D2 = Diagram([(0,2),(0,3),(1,1),(3,2)], n_cols=5)\n sage: D2.cells()\n [(0, 2), (0, 3), (1, 1), (3, 2)]\n sage: D2.ncols()\n 5\n sage: D2.pp()\n . . O O .\n . O . . .\n . . . . .\n . . O . .\n sage: TestSuite(D2).run()\n '
self._cells = frozenset(cells)
if self._cells:
N_rows = max((c[0] for c in self._cells))
N_cols = max((c[1] for c in self._cells))
else:
N_rows = (- 1)
N_cols = (- 1)
if (n_rows is not None):
if (n_rows <= N_rows):
raise ValueError('n_rows is too small')
self._n_rows = n_rows
else:
self._n_rows = (N_rows + 1)
if (n_cols is not None):
if (n_cols <= N_cols):
raise ValueError('n_cols is too small')
self._n_cols = n_cols
else:
self._n_cols = (N_cols + 1)
self._n_nonempty_rows = len(set((i for (i, j) in self._cells)))
self._n_nonempty_cols = len(set((j for (i, j) in self._cells)))
ClonableArray.__init__(self, parent, sorted(cells), check)
def pp(self):
'\n Return a visualization of the diagram.\n\n Cells which are present in the\n diagram are filled with a ``O``. Cells which are not present in the\n diagram are filled with a ``.``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagram\n sage: Diagram([(0,0), (0,3), (2,2), (2,4)]).pp()\n O . . O .\n . . . . .\n . . O . O\n sage: Diagram([(0,0), (0,3), (2,2), (2,4)], n_rows=6, n_cols=6).pp()\n O . . O . .\n . . . . . .\n . . O . O .\n . . . . . .\n . . . . . .\n . . . . . .\n sage: Diagram([]).pp()\n -\n '
if ((self._n_rows == 0) or (self._n_cols == 0)):
print('-')
return
print('\n'.join(self._pretty_print()))
def _ascii_art_(self):
'\n Return a visualization of the diagram.\n\n Cells which are present in the\n diagram are filled with a ``O``. Cells which are not present in the\n diagram are filled with a ``.``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagram\n sage: ascii_art(Diagram([(0,0), (0,3), (2,2), (2,4)]))\n O . . O .\n . . . . .\n . . O . O\n sage: ascii_art(Diagram([(0,0), (0,3), (2,2), (2,4)], n_rows=6, n_cols=6))\n O . . O . .\n . . . . . .\n . . O . O .\n . . . . . .\n . . . . . .\n . . . . . .\n sage: ascii_art(Diagram([]))\n -\n '
from sage.typeset.ascii_art import ascii_art
if ((self._n_rows == 0) or (self._n_cols == 0)):
return ascii_art('-')
return ascii_art('\n'.join(self._pretty_print()))
def _unicode_art_(self):
'\n Return a unicode visualization of the diagram.\n\n Cells which are present in the\n diagram are filled with a crossed box. Cells which are not present in the\n diagram are filled with an empty box.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagram\n sage: unicode_art(Diagram([(0,0), (0,3), (2,2), (2,4)]))\n ┌─┬─┬─┬─┬─┐\n │X│ │ │X│ │\n ├─┼─┼─┼─┼─┤\n │ │ │ │ │ │\n ├─┼─┼─┼─┼─┤\n │ │ │X│ │X│\n └─┴─┴─┴─┴─┘\n sage: unicode_art(Diagram([(0,0), (0,3), (2,2), (2,4)], n_rows=6, n_cols=6))\n ┌─┬─┬─┬─┬─┬─┐\n │X│ │ │X│ │ │\n ├─┼─┼─┼─┼─┼─┤\n │ │ │ │ │ │ │\n ├─┼─┼─┼─┼─┼─┤\n │ │ │X│ │X│ │\n ├─┼─┼─┼─┼─┼─┤\n │ │ │ │ │ │ │\n ├─┼─┼─┼─┼─┼─┤\n │ │ │ │ │ │ │\n ├─┼─┼─┼─┼─┼─┤\n │ │ │ │ │ │ │\n └─┴─┴─┴─┴─┴─┘\n sage: unicode_art(Diagram([]))\n ∅\n '
from sage.typeset.unicode_art import unicode_art
if ((self._n_rows == 0) or (self._n_cols == 0)):
return unicode_art('∅')
ndivs = (self._n_cols - 1)
cell = '│X'
empty = '│ '
it = self._pretty_print(cell, empty)
ret = (('┌─' + ('┬─' * ndivs)) + '┐')
ret += (('\n' + next(it)) + '│')
for row in it:
ret += (('\n├─' + ('┼─' * ndivs)) + '┤')
ret += (('\n' + row) + '│')
ret += (('\n└─' + ('┴─' * ndivs)) + '┘')
return unicode_art(ret)
def _pretty_print(self, cell='O ', empty='. '):
'\n Return a visualization of the diagram.\n\n Cells which are present in the\n diagram are filled with ``cell``. Cells which are not present in the\n diagram are filled with ``empty``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagram\n sage: "\\n".join(Diagram([(0,0), (0,3), (2,2), (2,4)])._pretty_print(\'x \',\'. \'))\n \'x . . x . \\n. . . . . \\n. . x . x \'\n sage: "\\n".join(Diagram([(0,0), (0,3), (2,2), (2,4)], n_rows=6, n_cols=6)._pretty_print(\'x \',\'. \'))\n \'x . . x . . \\n. . . . . . \\n. . x . x . \\n. . . . . . \\n. . . . . . \\n. . . . . . \'\n '
for i in range(self._n_rows):
output_str = ''
for j in range(self._n_cols):
if ((i, j) in self):
output_str += cell
else:
output_str += empty
(yield output_str)
def _latex_(self):
'\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagram\n sage: latex(Diagram([]))\n {\\emptyset}\n sage: latex(Diagram([(0,0), (0,3), (2,2), (2,4)]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{5}{p{0.6ex}}}\\cline{1-1}\\cline{4-4}\n \\lr{\\phantom{x}}&&&\\lr{\\phantom{x}}&\\\\\\cline{1-1}\\cline{4-4}\n &&&&\\\\\\cline{3-3}\\cline{5-5}\n &&\\lr{\\phantom{x}}&&\\lr{\\phantom{x}}\\\\\\cline{3-3}\\cline{5-5}\n \\end{array}$}\n }\n '
if ((self._n_rows == 0) or (self._n_cols == 0)):
return '{\\emptyset}'
lr = '\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}'
array = []
for i in range(self._n_rows):
row = []
for j in range(self._n_cols):
row.append(('\\phantom{x}' if ((i, j) in self) else None))
array.append(row)
def end_line(r):
if (r == 0):
return ''.join((('\\cline{%s-%s}' % ((i + 1), (i + 1))) for (i, j) in enumerate(array[0]) if (j is not None)))
elif (r == len(array)):
return ('\\\\' + ''.join((('\\cline{%s-%s}' % ((i + 1), (i + 1))) for (i, j) in enumerate(array[(r - 1)]) if (j is not None))))
else:
out = ('\\\\' + ''.join((('\\cline{%s-%s}' % ((i + 1), (i + 1))) for (i, j) in enumerate(array[(r - 1)]) if (j is not None))))
out += ''.join((('\\cline{%s-%s}' % ((i + 1), (i + 1))) for (i, j) in enumerate(array[r]) if (j is not None)))
return out
tex = ('\\raisebox{-.6ex}{$\\begin{array}[b]{*{%s}{p{0.6ex}}}' % max(map(len, array)))
tex += (end_line(0) + '\n')
for r in range(len(array)):
tex += '&'.join((('' if (c is None) else ('\\lr{%s}' % (c,))) for c in array[r]))
tex += (end_line((r + 1)) + '\n')
return ('{%s\n%s\n}' % (lr, (tex + '\\end{array}$}')))
def number_of_rows(self):
'\n Return the total number of rows of ``self``.\n\n EXAMPLES:\n\n The following example has three rows which are filled, but they\n are contained in rows 0 to 3 (for a total of four)::\n\n sage: from sage.combinat.diagram import Diagram\n sage: D1 = Diagram([(0,2),(0,3),(1,1),(3,2)])\n sage: D1.number_of_rows()\n 4\n sage: D1.nrows()\n 4\n\n The total number of rows includes including those which are empty.\n We can also include empty rows at the end::\n\n sage: from sage.combinat.diagram import Diagram\n sage: D = Diagram([(0,2),(0,3),(1,1),(3,2)], n_rows=6)\n sage: D.number_of_rows()\n 6\n sage: D.pp()\n . . O O\n . O . .\n . . . .\n . . O .\n . . . .\n . . . .\n '
return self._n_rows
nrows = number_of_rows
def number_of_cols(self):
'\n Return the total number of rows of ``self``.\n\n EXAMPLES:\n\n The following example has three columns which are filled, but they\n are contained in rows 0 to 3 (for a total of four)::\n\n sage: from sage.combinat.diagram import Diagram\n sage: D = Diagram([(0,2),(0,3),(1,1),(3,2)])\n sage: D.number_of_cols()\n 4\n sage: D.ncols()\n 4\n\n We can also include empty columns at the end::\n\n sage: from sage.combinat.diagram import Diagram\n sage: D = Diagram([(0,2),(0,3),(1,1),(3,2)], n_cols=6)\n sage: D.number_of_cols()\n 6\n sage: D.pp()\n . . O O . .\n . O . . . .\n . . . . . .\n . . O . . .\n '
return self._n_cols
ncols = number_of_cols
def cells(self):
'\n Return a ``list`` of the cells contained in the diagram ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagram\n sage: D1 = Diagram([(0,2),(0,3),(1,1),(3,2)])\n sage: D1.cells()\n [(0, 2), (0, 3), (1, 1), (3, 2)]\n '
return sorted(self._cells)
def number_of_cells(self):
'\n Return the total number of cells contained in the diagram ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagram\n sage: D1 = Diagram([(0,2),(0,3),(1,1),(3,2)])\n sage: D1.number_of_cells()\n 4\n sage: D1.n_cells()\n 4\n '
return len(self._cells)
n_cells = number_of_cells
size = number_of_cells
def check(self):
'\n Check that this is a valid diagram.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagram\n sage: D = Diagram([(0,0), (0,3), (2,2), (2,4)])\n sage: D.check()\n\n In the next two examples, a bad diagram is passed.\n The first example fails because one cell is indexed by negative\n integers::\n\n sage: D = Diagram([(0,0), (0,-3), (2,2), (2,4)])\n Traceback (most recent call last):\n ...\n ValueError: diagrams must be indexed by non-negative integers\n\n The next example fails because one cell is indexed by rational\n numbers::\n\n sage: D = Diagram([(0,0), (0,3), (2/3,2), (2,4)])\n Traceback (most recent call last):\n ...\n ValueError: diagrams must be indexed by non-negative integers\n '
from sage.sets.non_negative_integers import NonNegativeIntegers
NN = NonNegativeIntegers()
if (not all(((i in NN) for c in self._cells for i in c))):
raise ValueError('diagrams must be indexed by non-negative integers')
def specht_module(self, base_ring=None):
'\n Return the Specht module corresponding to ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagram\n sage: D = Diagram([(0,0), (1,1), (2,2), (2,3)])\n sage: SM = D.specht_module(QQ) # needs sage.modules\n sage: s = SymmetricFunctions(QQ).s() # needs sage.modules\n sage: s(SM.frobenius_image()) # needs sage.modules\n s[2, 1, 1] + s[2, 2] + 2*s[3, 1] + s[4]\n '
from sage.combinat.specht_module import SpechtModule
from sage.combinat.symmetric_group_algebra import SymmetricGroupAlgebra
if (base_ring is None):
from sage.rings.rational_field import QQ
base_ring = QQ
R = SymmetricGroupAlgebra(base_ring, len(self))
return SpechtModule(R, self)
def specht_module_dimension(self, base_ring=None):
'\n Return the dimension of the Specht module corresponding to ``self``.\n\n INPUT:\n\n - ``base_ring`` -- (default: `\\QQ`) the base ring\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagram\n sage: D = Diagram([(0,0), (1,1), (2,2), (2,3)])\n sage: D.specht_module_dimension() # needs sage.modules\n 12\n sage: D.specht_module(QQ).dimension() # needs sage.modules\n 12\n '
from sage.combinat.specht_module import specht_module_rank
return specht_module_rank(self, base_ring)
|
class Diagrams(UniqueRepresentation, Parent):
'\n The class of combinatorial diagrams.\n\n A *combinatorial diagram* is a set of cells indexed by pairs of natural\n numbers. Calling an instance of :class:`Diagrams` is one way to construct\n diagrams.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagrams\n sage: Dgms = Diagrams()\n sage: D = Dgms([(0,0), (0,3), (2,2), (2,4)])\n sage: D.parent()\n Combinatorial diagrams\n\n '
def __init__(self, category=None):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagrams\n sage: Dgms = Diagrams(); Dgms\n Combinatorial diagrams\n\n TESTS::\n\n sage: TestSuite(Dgms).run()\n '
Parent.__init__(self, category=InfiniteEnumeratedSets().or_subcategory(category))
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagrams\n sage: I = iter(Diagrams())\n sage: for i in range(10):\n ....: print(next(I))\n []\n [(0, 0)]\n [(1, 0)]\n [(0, 0), (1, 0)]\n [(0, 1)]\n [(0, 0), (0, 1)]\n [(0, 1), (1, 0)]\n [(0, 0), (0, 1), (1, 0)]\n [(2, 0)]\n [(0, 0), (2, 0)]\n sage: next(I).parent()\n Combinatorial diagrams\n\n sage: from sage.combinat.diagram import NorthwestDiagrams\n sage: I = iter(NorthwestDiagrams())\n sage: for i in range(20):\n ....: print(next(I))\n []\n [(0, 0)]\n [(1, 0)]\n [(0, 0), (1, 0)]\n [(0, 1)]\n [(0, 0), (0, 1)]\n [(0, 0), (0, 1), (1, 0)]\n [(2, 0)]\n [(0, 0), (2, 0)]\n [(1, 0), (2, 0)]\n [(0, 0), (1, 0), (2, 0)]\n [(0, 0), (0, 1), (2, 0)]\n [(0, 0), (0, 1), (1, 0), (2, 0)]\n [(1, 1)]\n [(0, 0), (1, 1)]\n [(1, 0), (1, 1)]\n [(0, 0), (1, 0), (1, 1)]\n [(0, 1), (1, 1)]\n [(0, 0), (0, 1), (1, 1)]\n [(0, 0), (0, 1), (1, 0), (1, 1)]\n '
from sage.sets.non_negative_integers import NonNegativeIntegers
from sage.categories.cartesian_product import cartesian_product
from sage.combinat.subset import subsets
N = NonNegativeIntegers()
NxN = cartesian_product([N, N])
X = subsets(NxN)
while True:
cells = next(X)
try:
(yield self.element_class(self, tuple(((i, j) for (i, j) in cells))))
except ValueError:
pass
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagrams\n sage: Dgms = Diagrams(); Dgms\n Combinatorial diagrams\n '
return 'Combinatorial diagrams'
def _element_constructor_(self, cells, n_rows=None, n_cols=None, check=True):
'\n Cosntruct an element of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagrams\n sage: Dgms = Diagrams()\n sage: Dgms([(0,1),(2,2)]).pp()\n . O .\n . . .\n . . O\n\n\n sage: from sage.combinat.tiling import Polyomino # needs sage.modules\n sage: p = Polyomino([(0,0),(1,0),(1,1),(1,2)]) # needs sage.modules\n sage: Dgms(p).pp() # needs sage.modules\n O . .\n O O O\n\n sage: from sage.combinat.composition import Composition\n sage: a = Composition([4,2,0,2,4])\n sage: Dgms(a).pp()\n O O O O\n O O . .\n . . . .\n O O . .\n O O O O\n\n sage: M = Matrix([[1,1,1,1],[1,1,0,0],[0,0,0,0],[1,1,0,0],[1,1,1,1]]) # needs sage.modules\n sage: Dgms(M).pp() # needs sage.modules\n O O O O\n O O . .\n . . . .\n O O . .\n O O O O\n\n TESTS::\n\n sage: TestSuite(Dgms).run()\n '
if isinstance(cells, Polyomino):
return self.from_polyomino(cells)
if isinstance(cells, Composition):
return self.from_composition(cells)
if isinstance(cells, (Matrix_dense, Matrix_sparse)):
return self.from_zero_one_matrix(cells)
return self.element_class(self, cells, n_rows, n_cols, check)
def _an_element_(self):
'\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import Diagrams\n sage: Dgms = Diagrams()\n sage: D = Dgms.an_element(); D\n [(0, 2), (1, 1), (2, 3)]\n sage: D.pp()\n . . O .\n . O . .\n . . . O\n '
return self([(0, 2), (1, 1), (2, 3)])
def from_polyomino(self, p):
"\n Create the diagram corresponding to a 2d\n :class:`~sage.combinat.tiling.Polyomino`\n\n EXAMPLES::\n\n sage: from sage.combinat.tiling import Polyomino # needs sage.modules\n sage: p = Polyomino([(0,0),(1,0),(1,1),(1,2)]) # needs sage.modules\n sage: from sage.combinat.diagram import Diagrams\n sage: Diagrams()(p).pp() # needs sage.modules\n O . .\n O O O\n\n We can also call this method directly::\n\n sage: Diagrams().from_polyomino(p).pp() # needs sage.modules\n O . .\n O O O\n\n This only works for a 2d :class:`~sage.combinat.tiling.Polyomino`::\n\n sage: p = Polyomino([(0,0,0), (0,1,0), (1,1,0), (1,1,1)], color='blue') # needs sage.modules\n sage: Diagrams().from_polyomino(p) # needs sage.modules\n Traceback (most recent call last):\n ...\n ValueError: the polyomino must be 2 dimensional\n "
if (not (p._dimension == 2)):
raise ValueError('the polyomino must be 2 dimensional')
cells = list(map(tuple, p))
return self.element_class(self, cells)
def from_composition(self, alpha):
'\n Create the diagram corresponding to a weak composition `\\alpha \\vDash n`.\n\n EXAMPLES::\n\n sage: alpha = Composition([3,0,2,1,4,4])\n sage: from sage.combinat.diagram import Diagrams\n sage: Diagrams()(alpha).pp()\n O O O .\n . . . .\n O O . .\n O . . .\n O O O O\n O O O O\n sage: Diagrams().from_composition(alpha).pp()\n O O O .\n . . . .\n O O . .\n O . . .\n O O O O\n O O O O\n '
cells = []
for (i, n) in enumerate(alpha):
cells.extend(((i, j) for j in range(n)))
return self.element_class(self, cells, check=False)
def from_zero_one_matrix(self, M, check=True):
"\n Get a diagram from a matrix with entries in `\\{0, 1\\}`, where\n positions of cells are indicated by the `1`'s.\n\n EXAMPLES::\n\n sage: M = matrix([[1,0,1,1],[0,1,1,0]]) # needs sage.modules\n sage: from sage.combinat.diagram import Diagrams\n sage: Diagrams()(M).pp() # needs sage.modules\n O . O O\n . O O .\n sage: Diagrams().from_zero_one_matrix(M).pp() # needs sage.modules\n O . O O\n . O O .\n\n sage: M = matrix([[1, 0, 0], [1, 0, 0], [0, 0, 0]]) # needs sage.modules\n sage: Diagrams()(M).pp() # needs sage.modules\n O . .\n O . .\n . . .\n "
(n_rows, n_cols) = M.dimensions()
if check:
zero = M.base_ring().zero()
one = M.base_ring().one()
for i in range(n_rows):
for j in range(n_cols):
if (not ((M[(i, j)] == zero) or (M[(i, j)] == one))):
raise ValueError('matrix entries must be 0 or 1')
cells = [(i, j) for i in range(n_rows) for j in range(n_cols) if M[(i, j)]]
return self.element_class(self, cells, n_rows, n_cols, check=False)
Element = Diagram
|
class NorthwestDiagram(Diagram, metaclass=InheritComparisonClasscallMetaclass):
'\n Diagrams with the northwest property.\n\n A diagram is a set of cells indexed by natural numbers. Such a diagram\n has the *northwest property* if the presence of cells `(i1, j1)` and\n `(i2, j2)` implies the presence of the cell\n `(\\min(i1, i2), \\min(j1, j2))`. Diagrams with the northwest property are\n called *northwest diagrams*.\n\n For general diagrams see :class:`Diagram`.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import NorthwestDiagram\n sage: N = NorthwestDiagram([(0,0), (0, 2), (2,0)])\n\n To visualize them, use the ``.pp()`` method::\n\n sage: N.pp()\n O . O\n . . .\n O . .\n '
@staticmethod
def __classcall_private__(self, cells, n_rows=None, n_cols=None, check=True):
'\n Normalize input to ensure a correct parent. This method also allows\n one to specify whether or not to check the northwest property for the\n provided cells.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import NorthwestDiagram, NorthwestDiagrams\n sage: N1 = NorthwestDiagram([(0,1), (0,2)])\n sage: N2 = NorthwestDiagram([(0,1), (0,3)])\n sage: N1.parent() is N2.parent()\n True\n sage: N3 = NorthwestDiagrams()([(0,1), (0,2)])\n sage: N3.parent() is NorthwestDiagrams()\n True\n sage: N1.parent() is NorthwestDiagrams()\n True\n '
return NorthwestDiagrams()(cells, n_rows, n_cols, check)
def check(self):
'\n A diagram has the northwest property if the presence of cells\n `(i1, j1)` and `(i2, j2)` implies the presence of the cell\n `(min(i1, i2), min(j1, j2))`. This method checks if the northwest\n property is satisfied for ``self``\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import NorthwestDiagram\n sage: N = NorthwestDiagram([(0,0), (0,3), (3,0)])\n sage: N.check()\n\n Here is a non-example::\n\n sage: notN = NorthwestDiagram([(0,1), (1,0)]) #.check() is implicit\n Traceback (most recent call last):\n ...\n ValueError: diagram is not northwest\n\n TESTS::\n\n sage: NorthwestDiagram([(0,1/2)])\n Traceback (most recent call last):\n ...\n ValueError: diagrams must be indexed by non-negative integers\n '
from itertools import combinations
Diagram.check(self)
if (not all((((min(i1, i2), min(j1, j2)) in self) for ((i1, j1), (i2, j2)) in combinations(self._cells, 2)))):
raise ValueError('diagram is not northwest')
def peelable_tableaux(self):
'\n Return the set of peelable tableaux whose diagram is ``self``.\n\n For a fixed northwest diagram `D`, we say that a Young tableau `T` is\n `D`-peelable if:\n\n 1. the row indices of the cells in the first column of `D` are\n the entries in an initial segment in the first column of `T` and\n 2. the tableau `Q` obtained by removing those cells from `T` and playing\n jeu de taquin is `(D-C)`-peelable, where `D-C` is the diagram formed\n by forgetting the first column of `D`.\n\n Reiner and Shimozono [RS1995]_ showed that the number\n `\\operatorname{red}(w)` of reduced words of a permutation `w` may be\n computed using the peelable tableaux of the Rothe diagram `D(w)`.\n Explicitly,\n\n .. MATH::\n\n \\operatorname{red}(w) = \\sum_{T} f_{\\operatorname{shape} T},\n\n where the sum runs over the `D(w)`-peelable tableaux `T` and `f_\\lambda`\n is the number of standard Young tableaux of shape `\\lambda` (which may\n be computed using the hook-length formula).\n\n EXAMPLES:\n\n We can compute the `D`-peelable diagrams for a northwest diagram `D`::\n\n sage: from sage.combinat.diagram import NorthwestDiagram\n sage: cells = [(0,0), (0,1), (0,2), (1,0), (2,0), (2,2), (2,4),\n ....: (4,0), (4,2)]\n sage: D = NorthwestDiagram(cells); D.pp()\n O O O . .\n O . . . .\n O . O . O\n . . . . .\n O . O . .\n sage: D.peelable_tableaux()\n {[[1, 1, 1], [2, 3, 3], [3, 5], [5]],\n [[1, 1, 1, 3], [2, 3], [3, 5], [5]]}\n\n EXAMPLES:\n\n If the diagram is only one column, there is only one peelable tableau::\n\n sage: from sage.combinat.diagram import NorthwestDiagram\n sage: NWD = NorthwestDiagram([(0,0), (2,0)])\n sage: NWD.peelable_tableaux()\n {[[1], [3]]}\n\n From [RS1995]_, we know that there is only one peelable tableau for the\n Rothe diagram of the permutation (in one line notation) `251643`::\n\n sage: D = NorthwestDiagram([(1, 2), (1, 3), (3, 2), (3, 3), (4, 2)])\n sage: D.pp()\n . . . .\n . . O O\n . . . .\n . . O O\n . . O .\n\n sage: D.peelable_tableaux()\n {[[2, 2], [4, 4], [5]]}\n\n Here are all the intermediate steps to compute the peelables for the\n Rothe diagram of (in one-line notation) `64817235`. They are listed from\n deepest in the recursion to the final step. The recursion has depth five\n in this case so we will label the intermediate tableaux by `D_i` where\n `i` is the step in the recursion at which they appear.\n\n Start with the one that has a single column::\n\n sage: D5 = NorthwestDiagram([(2,0)]); D5.pp()\n .\n .\n O\n sage: D5.peelable_tableaux()\n {[[3]]}\n\n Now we know all of the `D_5` peelables, so we can compute the `D_4`\n peelables::\n\n sage: D4 = NorthwestDiagram([(0, 0), (2,0), (4, 0), (2, 2)])\n sage: D4.pp()\n O . .\n . . .\n O . O\n . . .\n O . .\n\n sage: D4.peelable_tableaux()\n {[[1, 3], [3], [5]]}\n\n There is only one `D_4` peelable, so we can compute the `D_3`\n peelables::\n\n sage: D3 = NorthwestDiagram([(0,0), (0,1), (2, 1), (2, 3), (4,1)])\n sage: D3.pp()\n O O . .\n . . . .\n . O . O\n . . . .\n . O . .\n\n sage: D3.peelable_tableaux()\n {[[1, 1], [3, 3], [5]], [[1, 1, 3], [3], [5]]}\n\n Now compute the `D_2` peelables::\n\n sage: cells = [(0,0), (0,1), (0,2), (1,0), (2,0), (2,2), (2,4),\n ....: (4,0), (4,2)]\n sage: D2 = NorthwestDiagram(cells); D2.pp()\n O O O . .\n O . . . .\n O . O . O\n . . . . .\n O . O . .\n\n sage: D2.peelable_tableaux()\n {[[1, 1, 1], [2, 3, 3], [3, 5], [5]],\n [[1, 1, 1, 3], [2, 3], [3, 5], [5]]}\n\n And the `D_1` peelables::\n\n sage: cells = [(0,0), (0,1), (0,2), (0,3), (1,0), (1,1), (2,0),\n ....: (2,1), (2,3), (2,5), (4,0), (4,1), (4,3)]\n sage: D1 = NorthwestDiagram(cells); D1.pp()\n O O O O . .\n O O . . . .\n O O . O . O\n . . . . . .\n O O . O . .\n\n sage: D1.peelable_tableaux()\n {[[1, 1, 1, 1], [2, 2, 3, 3], [3, 3, 5], [5, 5]],\n [[1, 1, 1, 1, 3], [2, 2, 3], [3, 3, 5], [5, 5]]}\n\n Which we can use to get the `D` peelables::\n\n sage: cells = [(0,0), (0,1), (0,2), (0,3), (0,4),\n ....: (1,0), (1,1), (1,2),\n ....: (2,0), (2,1), (2,2), (2,4), (2,6),\n ....: (4,1), (4,2), (4,4)]\n sage: D = NorthwestDiagram(cells); D.pp()\n O O O O O . .\n O O O . . . .\n O O O . O . O\n . . . . . . .\n . O O . O . .\n sage: D.peelable_tableaux()\n {[[1, 1, 1, 1, 1], [2, 2, 2, 3, 3], [3, 3, 3], [5, 5, 5]],\n [[1, 1, 1, 1, 1], [2, 2, 2, 3, 3], [3, 3, 3, 5], [5, 5]],\n [[1, 1, 1, 1, 1, 3], [2, 2, 2, 3], [3, 3, 3], [5, 5, 5]],\n [[1, 1, 1, 1, 1, 3], [2, 2, 2, 3], [3, 3, 3, 5], [5, 5]]}\n\n ALGORITHM:\n\n This implementation uses the algorithm suggested in Remark 25\n of [RS1995]_.\n\n TESTS:\n\n Corner case::\n\n sage: from sage.combinat.diagram import NorthwestDiagram\n sage: D = NorthwestDiagram([])\n sage: D.peelable_tableaux()\n {[]}\n '
if (not self):
return set([Tableau([])])
if (self._n_nonempty_cols == 1):
return set([Tableau([[(i + 1)] for (i, j) in self.cells()])])
first_col = min((j for (i, j) in self._cells))
dhat_cells = []
new_vals_cells = []
for (i, j) in self._cells:
if (j != first_col):
dhat_cells.append((i, j))
else:
new_vals_cells.append((i + 1))
new_vals = sorted(new_vals_cells)
Dhat = NorthwestDiagram(dhat_cells)
k = (self.n_cells() - Dhat.n_cells())
peelables = set()
for Q in Dhat.peelable_tableaux():
mu = Q.shape()
vertical_strip_cells = mu.vertical_border_strip_cells(k)
for s in vertical_strip_cells:
sQ = SkewTableaux()(Q)
for c in s:
sQ = sQ.backward_slide(c)
sQ_new = sQ.to_list()
for n in range(k):
sQ_new[n][0] = new_vals[n]
T = Tableau(sQ_new)
if T.is_column_strict():
peelables.add(T)
return peelables
|
class NorthwestDiagrams(Diagrams):
'\n Diagrams satisfying the northwest property.\n\n A diagram `D` is a *northwest diagram* if for every two cells `(i_1, j_1)`\n and `(i_2, j_2)` in `D` then there exists the cell\n `(\\min(i_1, i_2), \\min(j_1, j_2)) \\in D`.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import NorthwestDiagram\n sage: N = NorthwestDiagram([(0,0), (0, 10), (5,0)]); N.pp()\n O . . . . . . . . . O\n . . . . . . . . . . .\n . . . . . . . . . . .\n . . . . . . . . . . .\n . . . . . . . . . . .\n O . . . . . . . . . .\n\n Note that checking whether or not the northwest property is satisfied is\n automatically checked. The diagram found by adding the cell `(1,1)` to the\n diagram above is *not* a northwest diagram. The cell `(1,0)` should be\n present due to the presence of `(5,0)` and `(1,1)`::\n\n sage: from sage.combinat.diagram import Diagram\n sage: Diagram([(0, 0), (0, 10), (5, 0), (1, 1)]).pp()\n O . . . . . . . . . O\n . O . . . . . . . . .\n . . . . . . . . . . .\n . . . . . . . . . . .\n . . . . . . . . . . .\n O . . . . . . . . . .\n sage: NorthwestDiagram([(0, 0), (0, 10), (5, 0), (1, 1)])\n Traceback (most recent call last):\n ...\n ValueError: diagram is not northwest\n\n However, this behavior can be turned off if you are confident that\n you are providing a northwest diagram::\n\n sage: N = NorthwestDiagram([(0, 0), (0, 10), (5, 0),\n ....: (1, 1), (0, 1), (1, 0)],\n ....: check=False)\n sage: N.pp()\n O O . . . . . . . . O\n O O . . . . . . . . .\n . . . . . . . . . . .\n . . . . . . . . . . .\n . . . . . . . . . . .\n O . . . . . . . . . .\n\n Note that arbitrary diagrams which happen to be northwest diagrams\n only live in the parent of :class:`Diagrams`::\n\n sage: D = Diagram([(0, 0), (0, 10), (5, 0), (1, 1), (0, 1), (1, 0)])\n sage: D.pp()\n O O . . . . . . . . O\n O O . . . . . . . . .\n . . . . . . . . . . .\n . . . . . . . . . . .\n . . . . . . . . . . .\n O . . . . . . . . . .\n sage: from sage.combinat.diagram import NorthwestDiagrams\n sage: D in NorthwestDiagrams()\n False\n\n Here are some more examples::\n\n sage: from sage.combinat.diagram import NorthwestDiagram, NorthwestDiagrams\n sage: D = NorthwestDiagram([(0,1), (0,2), (1,1)]); D.pp()\n . O O\n . O .\n sage: NWDgms = NorthwestDiagrams()\n sage: D = NWDgms([(1,1), (1,2), (2,1)]); D.pp()\n . . .\n . O O\n . O .\n sage: D.parent()\n Combinatorial northwest diagrams\n\n Additionally, there are natural constructions of a northwest diagram\n given the data of a permutation (Rothe diagrams are the protypical example\n of northwest diagrams), or the data of a partition of an integer, or a\n skew partition.\n\n The Rothe diagram `D(\\omega)` of a permutation `\\omega` is specified by\n the cells\n\n .. MATH::\n\n D(\\omega) = \\{(\\omega_j, i) : i<j,\\, \\omega_i > \\omega_j \\}.\n\n We can construct one by calling :meth:`rothe_diagram` method on the set\n of all :class:`~sage.combinat.diagram.NorthwestDiagrams`::\n\n sage: w = Permutations(4)([4,3,2,1])\n sage: NorthwestDiagrams().rothe_diagram(w).pp()\n O O O .\n O O . .\n O . . .\n . . . .\n\n To turn a Ferrers diagram into a northwest diagram, we may call\n :meth:`from_partition`. This will return a Ferrer\'s diagram in the\n set of all northwest diagrams. For many use-cases it is probably better\n to get Ferrer\'s diagrams by the corresponding method on partitons, namely\n :meth:`sage.combinat.partitions.Partitions.ferrers_diagram`::\n\n sage: mu = Partition([7,3,1,1])\n sage: mu.pp()\n *******\n ***\n *\n *\n sage: NorthwestDiagrams().from_partition(mu).pp()\n O O O O O O O\n O O O . . . .\n O . . . . . .\n O . . . . . .\n\n It is also possible to turn a Ferrers diagram of a skew partition into a\n northwest diagram, altough it is more subtle than just using the skew\n diagram itself. One must first reflect the partition about a vertical axis\n so that the skew partition looks "backwards"::\n\n sage: mu, nu = Partition([5,4,3,2,1]), Partition([3,2,1])\n sage: s = mu/nu; s.pp()\n **\n **\n **\n **\n *\n sage: NorthwestDiagrams().from_skew_partition(s).pp()\n O O . . .\n . O O . .\n . . O O .\n . . . O O\n . . . . O\n '
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import NorthwestDiagrams\n sage: NWDgms = NorthwestDiagrams(); NWDgms\n Combinatorial northwest diagrams\n '
return 'Combinatorial northwest diagrams'
def _an_element_(self):
'\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import NorthwestDiagrams\n sage: NWDgms = NorthwestDiagrams()\n sage: NWD = NWDgms.an_element(); NWD\n [(0, 1), (0, 2), (1, 1), (2, 3)]\n sage: NWD.pp()\n . O O .\n . O . .\n . . . O\n sage: NWD.parent() is NWDgms\n True\n '
return self([(0, 1), (0, 2), (1, 1), (2, 3)])
def rothe_diagram(self, w):
'\n Return the Rothe diagram of ``w``.\n\n We construct a northwest diagram from a permutation by\n constructing its Rothe diagram. Formally, if `\\omega` is\n a :class:`~sage.combinat.permutation.Permutation`\n then the Rothe diagram `D(\\omega)` is the diagram whose cells are\n\n .. MATH::\n\n D(\\omega) = \\{(\\omega_j, i) : i<j,\\, \\omega_i > \\omega_j \\}.\n\n Informally, one can construct the Rothe diagram by starting with all\n `n^2` possible cells, and then deleting the cells `(i, \\omega(i))` as\n well as all cells to the right and below. (These are sometimes called\n "death rays".)\n\n .. SEEALSO::\n\n :func:`~sage.combinat.diagram.RotheDiagram`\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram import NorthwestDiagrams\n sage: w = Permutations(3)([2,1,3])\n sage: NorthwestDiagrams().rothe_diagram(w).pp()\n O . .\n . . .\n . . .\n sage: NorthwestDiagrams().from_permutation(w).pp()\n O . .\n . . .\n . . .\n\n sage: w = Permutations(8)([2,5,4,1,3,6,7,8])\n sage: NorthwestDiagrams().rothe_diagram(w).pp()\n O . . . . . . .\n O . O O . . . .\n O . O . . . . .\n . . . . . . . .\n . . . . . . . .\n . . . . . . . .\n . . . . . . . .\n . . . . . . . .\n '
return RotheDiagram(w)
from_permutation = rothe_diagram
def from_partition(self, mu):
'\n Return the Ferrer\'s diagram of ``mu`` as a northwest diagram.\n\n EXAMPLES::\n\n sage: mu = Partition([5,2,1]); mu.pp()\n *****\n **\n *\n sage: mu.parent()\n Partitions\n sage: from sage.combinat.diagram import NorthwestDiagrams\n sage: D = NorthwestDiagrams().from_partition(mu)\n sage: D.pp()\n O O O O O\n O O . . .\n O . . . .\n sage: D.parent()\n Combinatorial northwest diagrams\n\n This will print in English notation even if the notation is set to\n French for the partition::\n\n sage: Partitions.options.convention="french"\n sage: mu.pp()\n *\n **\n *****\n sage: D.pp()\n O O O O O\n O O . . .\n O . . . .\n\n TESTS::\n\n sage: from sage.combinat.diagram import NorthwestDiagrams\n sage: mu = [5, 2, 1]\n sage: D = NorthwestDiagrams().from_partition(mu)\n Traceback (most recent call last):\n ...\n ValueError: mu must be a Partition\n '
if (not isinstance(mu, Partition)):
raise ValueError('mu must be a Partition')
return self.element_class(self, mu.cells(), check=False)
def from_skew_partition(self, s):
'\n Get the northwest diagram found by reflecting a skew shape across\n a vertical plane.\n\n EXAMPLES::\n\n sage: mu, nu = Partition([3,2,1]), Partition([2,1])\n sage: s = mu/nu; s.pp()\n *\n *\n *\n sage: from sage.combinat.diagram import NorthwestDiagrams\n sage: D = NorthwestDiagrams().from_skew_partition(s)\n sage: D.pp()\n O . .\n . O .\n . . O\n\n sage: mu, nu = Partition([3,3,2]), Partition([2,2,2])\n sage: s = mu/nu; s.pp()\n *\n *\n sage: NorthwestDiagrams().from_skew_partition(s).pp()\n O . .\n O . .\n . . .\n\n TESTS::\n\n sage: mu = Partition([3,2,1])\n sage: NorthwestDiagrams().from_skew_partition(mu)\n Traceback (most recent call last):\n ...\n ValueError: mu must be a SkewPartition\n '
if (not isinstance(s, SkewPartition)):
raise ValueError('mu must be a SkewPartition')
n_cols = s.outer()[0]
n_rows = len(s.outer())
cells = [(i, ((n_cols - 1) - j)) for (i, j) in s.cells()]
return self.element_class(self, cells, n_rows, n_cols, check=False)
def from_parallelogram_polyomino(self, p):
'\n Create the diagram corresponding to a\n :class:`~sage.combinat.parallelogram_polyomino.ParallelogramPolyomino`.\n\n EXAMPLES::\n\n sage: p = ParallelogramPolyomino([[0, 0, 1, 0, 0, 0, 1, 1], # needs sage.modules\n ....: [1, 1, 0, 1, 0, 0, 0, 0]])\n sage: from sage.combinat.diagram import NorthwestDiagrams\n sage: NorthwestDiagrams().from_parallelogram_polyomino(p).pp() # needs sage.modules\n O O .\n O O O\n . O O\n . O O\n . O O\n '
from sage.matrix.constructor import Matrix
M = Matrix(p.get_array())
return self.from_zero_one_matrix(M)
Element = NorthwestDiagram
|
def RotheDiagram(w):
'\n The Rothe diagram of a permutation ``w``.\n\n EXAMPLES::\n\n sage: w = Permutations(9)([1, 7, 4, 5, 9, 3, 2, 8, 6])\n sage: from sage.combinat.diagram import RotheDiagram\n sage: D = RotheDiagram(w); D.pp()\n . . . . . . . . .\n . O O O O O . . .\n . O O . . . . . .\n . O O . . . . . .\n . O O . . O . O .\n . O . . . . . . .\n . . . . . . . . .\n . . . . . O . . .\n . . . . . . . . .\n\n The Rothe diagram is a northwest diagram::\n\n sage: D.parent()\n Combinatorial northwest diagrams\n\n Some other examples::\n\n sage: RotheDiagram([2, 1, 4, 3]).pp()\n O . . .\n . . . .\n . . O .\n . . . .\n\n sage: RotheDiagram([4, 1, 3, 2]).pp()\n O O O .\n . . . .\n . O . .\n . . . .\n\n Currently, only elements of the set of\n :class:`sage.combinat.permutations.Permutations` are supported. In\n particular, elements of permutation groups are not supported::\n\n sage: w = SymmetricGroup(9).an_element() # needs sage.groups\n sage: RotheDiagram(w) # needs sage.groups\n Traceback (most recent call last):\n ...\n ValueError: w must be a permutation\n\n TESTS::\n\n sage: w = Permutations(5)([1,2,3,4,5])\n sage: from sage.combinat.diagram import RotheDiagram\n sage: RotheDiagram(w).pp()\n . . . . .\n . . . . .\n . . . . .\n . . . . .\n . . . . .\n '
P = Permutations()
if (w not in P):
raise ValueError('w must be a permutation')
w = P(w)
N = w.size()
winv = w.inverse()
cells = [c for c in product(range(N), range(N)) if (((c[0] + 1) < winv((c[1] + 1))) and ((c[1] + 1) < w((c[0] + 1))))]
return NorthwestDiagram(cells, n_rows=N, n_cols=N, check=False)
|
def partition_diagrams(k):
'\n Return a generator of all partition diagrams of order ``k``.\n\n A partition diagram of order `k \\in \\ZZ` to is a set partition of\n `\\{1, \\ldots, k, -1, \\ldots, -k\\}`. If we have `k - 1/2 \\in ZZ`, then\n a partition diagram of order `k \\in 1/2 \\ZZ` is a set partition of\n `\\{1, \\ldots, k+1/2, -1, \\ldots, -(k+1/2)\\}` with `k+1/2` and `-(k+1/2)`\n in the same block. See [HR2005]_.\n\n INPUT:\n\n - ``k`` -- the order of the partition diagrams\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: [SetPartition(p) for p in da.partition_diagrams(2)]\n [{{-2, -1, 1, 2}},\n {{-2, 1, 2}, {-1}},\n {{-2}, {-1, 1, 2}},\n {{-2, -1}, {1, 2}},\n {{-2}, {-1}, {1, 2}},\n {{-2, -1, 1}, {2}},\n {{-2, 1}, {-1, 2}},\n {{-2, 1}, {-1}, {2}},\n {{-2, 2}, {-1, 1}},\n {{-2, -1, 2}, {1}},\n {{-2, 2}, {-1}, {1}},\n {{-2}, {-1, 1}, {2}},\n {{-2}, {-1, 2}, {1}},\n {{-2, -1}, {1}, {2}},\n {{-2}, {-1}, {1}, {2}}]\n sage: [SetPartition(p) for p in da.partition_diagrams(3/2)]\n [{{-2, -1, 1, 2}},\n {{-2, 1, 2}, {-1}},\n {{-2, 2}, {-1, 1}},\n {{-2, -1, 2}, {1}},\n {{-2, 2}, {-1}, {1}}]\n '
if (k in ZZ):
S = set_partition_iterator((list(range(1, (k + 1))) + list(range((- k), 0))))
for p in S:
(yield p)
elif ((k + (ZZ(1) / ZZ(2))) in ZZ):
k = ZZ((k + (ZZ(1) / ZZ(2))))
S = set_partition_iterator((list(range(1, (k + 1))) + list(range(((- k) + 1), 0))))
for p in S:
(yield [((b + [(- k)]) if (k in b) else b) for b in p])
else:
raise ValueError(('argument %s must be a half-integer' % k))
|
def brauer_diagrams(k):
'\n Return a generator of all Brauer diagrams of order ``k``.\n\n A Brauer diagram of order `k` is a partition diagram of order `k`\n with block size 2.\n\n INPUT:\n\n - ``k`` -- the order of the Brauer diagrams\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: [SetPartition(p) for p in da.brauer_diagrams(2)]\n [{{-2, -1}, {1, 2}}, {{-2, 1}, {-1, 2}}, {{-2, 2}, {-1, 1}}]\n sage: [SetPartition(p) for p in da.brauer_diagrams(5/2)]\n [{{-3, 3}, {-2, -1}, {1, 2}},\n {{-3, 3}, {-2, 1}, {-1, 2}},\n {{-3, 3}, {-2, 2}, {-1, 1}}]\n '
if (k in ZZ):
s = (list(range(1, (k + 1))) + list(range((- k), 0)))
for p in perfect_matchings_iterator(k):
(yield [(s[a], s[b]) for (a, b) in p])
elif ((k + (ZZ(1) / ZZ(2))) in ZZ):
k = ZZ((k + (ZZ(1) / ZZ(2))))
s = (list(range(1, k)) + list(range(((- k) + 1), 0)))
for p in perfect_matchings_iterator((k - 1)):
(yield ([(s[a], s[b]) for (a, b) in p] + [[k, (- k)]]))
|
def temperley_lieb_diagrams(k):
'\n Return a generator of all Temperley--Lieb diagrams of order ``k``.\n\n A Temperley--Lieb diagram of order `k` is a partition diagram of order `k`\n with block size 2 and is planar.\n\n INPUT:\n\n - ``k`` -- the order of the Temperley--Lieb diagrams\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: [SetPartition(p) for p in da.temperley_lieb_diagrams(2)]\n [{{-2, -1}, {1, 2}}, {{-2, 2}, {-1, 1}}]\n sage: [SetPartition(p) for p in da.temperley_lieb_diagrams(5/2)]\n [{{-3, 3}, {-2, -1}, {1, 2}}, {{-3, 3}, {-2, 2}, {-1, 1}}]\n '
for i in brauer_diagrams(k):
if is_planar(i):
(yield i)
|
def planar_diagrams(k):
'\n Return a generator of all planar diagrams of order ``k``.\n\n A planar diagram of order `k` is a partition diagram of order `k`\n that has no crossings.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: all_diagrams = [SetPartition(p) for p in da.partition_diagrams(2)]\n sage: da2 = [SetPartition(p) for p in da.planar_diagrams(2)]\n sage: [p for p in all_diagrams if p not in da2]\n [{{-2, 1}, {-1, 2}}]\n sage: all_diagrams = [SetPartition(p) for p in da.partition_diagrams(5/2)]\n sage: da5o2 = [SetPartition(p) for p in da.planar_diagrams(5/2)]\n sage: [p for p in all_diagrams if p not in da5o2]\n [{{-3, -1, 3}, {-2, 1, 2}},\n {{-3, -2, 1, 3}, {-1, 2}},\n {{-3, -1, 1, 3}, {-2, 2}},\n {{-3, 1, 3}, {-2, -1, 2}},\n {{-3, 1, 3}, {-2, 2}, {-1}},\n {{-3, 1, 3}, {-2}, {-1, 2}},\n {{-3, -1, 2, 3}, {-2, 1}},\n {{-3, 3}, {-2, 1}, {-1, 2}},\n {{-3, -1, 3}, {-2, 1}, {2}},\n {{-3, -1, 3}, {-2, 2}, {1}}]\n '
if (k in ZZ):
X = (list(range(1, (k + 1))) + list(range((- k), 0)))
(yield from planar_partitions_rec(X))
elif ((k + (ZZ(1) / ZZ(2))) in ZZ):
k = ZZ((k + (ZZ(1) / ZZ(2))))
X = (list(range(1, (k + 1))) + list(range(((- k) + 1), 0)))
for Y in planar_partitions_rec(X):
Y = list(Y)
for part in Y:
if (k in part):
part.append((- k))
break
(yield Y)
else:
raise ValueError(('argument %s must be a half-integer' % k))
|
def planar_partitions_rec(X):
'\n Iterate over all planar set partitions of ``X`` by using a\n recursive algorithm.\n\n ALGORITHM:\n\n To construct the set partition `\\rho = \\{\\rho_1, \\ldots, \\rho_k\\}` of\n `[n]`, we remove the part of the set partition containing the last\n element of ``X``, which, we consider to be `\\rho_k = \\{i_1, \\ldots, i_m\\}`\n without loss of generality. The remaining parts come from the planar set\n partitions of `\\{1, \\ldots, i_1-1\\}, \\{i_1+1, \\ldots, i_2-1\\}, \\ldots,\n \\{i_m+1, \\ldots, n\\}`.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: list(da.planar_partitions_rec([1,2,3]))\n [([1, 2], [3]), ([1], [2], [3]), ([2], [1, 3]), ([1], [2, 3]), ([1, 2, 3],)]\n '
if (not X):
return
if (len(X) <= 2):
(yield (X,))
if (len(X) > 1):
(yield ([X[0]], [X[1]]))
return
from sage.combinat.subset import powerset
from itertools import product
for S in powerset(range((len(X) - 1))):
if (not S):
for Y in planar_partitions_rec(X[:(- 1)]):
(yield (Y + ([X[(- 1)]],)))
continue
last = [X[i] for i in S]
last.append(X[(- 1)])
pt = []
if (S[0] != 0):
pt += [X[:S[0]]]
pt = [X[(S[i] + 1):S[(i + 1)]] for i in range((len(S) - 1)) if ((S[i] + 1) != S[(i + 1)])]
if ((S[(- 1)] + 1) != (len(X) - 1)):
pt += [X[(S[(- 1)] + 1):(- 1)]]
parts = [planar_partitions_rec(X[(S[i] + 1):S[(i + 1)]]) for i in range((len(S) - 1)) if ((S[i] + 1) != S[(i + 1)])]
if (S[0] != 0):
parts.append(planar_partitions_rec(X[:S[0]]))
if ((S[(- 1)] + 1) != (len(X) - 1)):
parts.append(planar_partitions_rec(X[(S[(- 1)] + 1):(- 1)]))
for Y in product(*parts):
(yield (sum(Y, ()) + (last,)))
|
def ideal_diagrams(k):
'\n Return a generator of all "ideal" diagrams of order ``k``.\n\n An ideal diagram of order `k` is a partition diagram of order `k` with\n propagating number less than `k`.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: all_diagrams = da.partition_diagrams(2)\n sage: [SetPartition(p) for p in all_diagrams if p not in da.ideal_diagrams(2)]\n [{{-2, 1}, {-1, 2}}, {{-2, 2}, {-1, 1}}]\n\n sage: all_diagrams = da.partition_diagrams(3/2)\n sage: [SetPartition(p) for p in all_diagrams if p not in da.ideal_diagrams(3/2)]\n [{{-2, 2}, {-1, 1}}]\n '
for i in partition_diagrams(k):
if (propagating_number(i) < k):
(yield i)
|
class AbstractPartitionDiagram(AbstractSetPartition):
'\n Abstract base class for partition diagrams.\n\n This class represents a single partition diagram, that is used as a\n basis key for a diagram algebra element. A partition diagram should\n be a partition of the set `\\{1, \\ldots, k, -1, \\ldots, -k\\}`. Each\n such set partition is regarded as a graph on nodes\n `\\{1, \\ldots, k, -1, \\ldots, -k\\}` arranged in two rows, with nodes\n `1, \\ldots, k` in the top row from left to right and with nodes\n `-1, \\ldots, -k` in the bottom row from left to right, and an edge\n connecting two nodes if and only if the nodes lie in the same\n subset of the set partition.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.AbstractPartitionDiagrams(2)\n sage: pd1 = da.AbstractPartitionDiagram(pd, [[1,2],[-1,-2]])\n sage: pd2 = da.AbstractPartitionDiagram(pd, [[1,2],[-1,-2]])\n sage: pd1\n {{-2, -1}, {1, 2}}\n sage: pd1 == pd2\n True\n sage: pd1 == [[1,2],[-1,-2]]\n True\n sage: pd1 == ((-2,-1),(2,1))\n True\n sage: pd1 == SetPartition([[1,2],[-1,-2]])\n True\n sage: pd3 = da.AbstractPartitionDiagram(pd, [[1,-2],[-1,2]])\n sage: pd1 == pd3\n False\n sage: pd4 = da.AbstractPartitionDiagram(pd, [[1,2],[3,4]])\n Traceback (most recent call last):\n ...\n ValueError: {{1, 2}, {3, 4}} does not represent two rows of vertices of order 2\n '
def __init__(self, parent, d, check=True):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.AbstractPartitionDiagrams(2)\n sage: pd1 = da.AbstractPartitionDiagram(pd, ((-2,-1),(1,2)) )\n '
self._base_diagram = tuple(sorted((tuple(sorted(i)) for i in d)))
super().__init__(parent, self._base_diagram, check=check)
def check(self):
"\n Check the validity of the input for the diagram.\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.AbstractPartitionDiagrams(2)\n sage: pd1 = da.AbstractPartitionDiagram(pd, [[1,2],[-1,-2]]) # indirect doctest\n sage: pd2 = da.AbstractPartitionDiagram(pd, [[1,2],[3,4]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: {{1, 2}, {3, 4}} does not represent two rows of vertices of order 2\n sage: pd2 = da.AbstractPartitionDiagram(pd, [[1],[-1]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: {{-1}, {1}} does not represent two rows of vertices of order 2\n\n sage: pd2 = da.AbstractPartitionDiagram(pd, [[[1,2],[-1,-2]]]) # indirect doctest\n Traceback (most recent call last):\n ...\n TypeError: unhashable type: 'list'\n "
if self._base_diagram:
tst = frozenset((e for B in self._base_diagram for e in B))
if (tst != self.parent()._set):
raise ValueError('{} does not represent two rows of vertices of order {}'.format(self, self.parent().order))
def __hash__(self):
'\n Return the hash of ``self``.\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.AbstractPartitionDiagrams(2)\n sage: pd1 = da.AbstractPartitionDiagram(pd, [[1,2],[-1,-2]])\n sage: pd2 = da.AbstractPartitionDiagram(pd, [[1,2],[-1,-2]])\n sage: hash(pd1) == hash(pd2)\n True\n sage: hash(pd1) == hash( ((-2,-1), (1,2)) )\n True\n '
return hash(self._base_diagram)
def __eq__(self, other):
'\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.AbstractPartitionDiagrams(2)\n sage: pd1 = da.AbstractPartitionDiagram(pd, [[1,2],[-1,-2]])\n sage: pd2 = da.AbstractPartitionDiagram(pd, [[1,2],[-1,-2]])\n sage: pd1 == pd2\n True\n sage: pd1 == [[1,2],[-1,-2]]\n True\n sage: pd1 == ((-2,-1),(2,1))\n True\n sage: pd1 == SetPartition([[1,2],[-1,-2]])\n True\n sage: pd3 = da.AbstractPartitionDiagram(pd, [[1,-2],[-1,2]])\n sage: pd1 == pd3\n False\n\n Check the inherited inequality::\n\n sage: pd1 = da.AbstractPartitionDiagram(pd, [[1,2],[-1,-2]])\n sage: pd2 = da.AbstractPartitionDiagram(pd, [[1,-2],[-1,2]])\n sage: pd1 != pd2\n True\n sage: pd1 != ((-2,-1),(2,1))\n False\n '
try:
return (self._base_diagram == other._base_diagram)
except AttributeError:
pass
try:
other2 = self.parent(other)
return (self._base_diagram == other2._base_diagram)
except (TypeError, ValueError, AttributeError):
return False
def __lt__(self, other):
'\n Compare less than.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.AbstractPartitionDiagrams(2)\n sage: pd1 = da.AbstractPartitionDiagram(pd, [[1,2],[-1,-2]])\n sage: pd2 = da.AbstractPartitionDiagram(pd, [[1,-2],[-1,2]])\n sage: pd1 < pd2\n True\n sage: pd2 < pd1\n False\n sage: pd2 > pd1\n True\n sage: pd1 > pd2\n False\n '
if (not isinstance(other, AbstractPartitionDiagram)):
return False
return (self._base_diagram < other._base_diagram)
def base_diagram(self):
'\n Return the underlying implementation of the diagram.\n\n OUTPUT:\n\n - tuple of tuples of integers\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.AbstractPartitionDiagrams(2)\n sage: pd([[1,2],[-1,-2]]).base_diagram() == ((-2,-1),(1,2))\n True\n '
return self._base_diagram
diagram = base_diagram
def set_partition(self):
'\n Return the underlying implementation of the diagram as a set of sets.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.AbstractPartitionDiagrams(2)\n sage: X = pd([[1,2],[-1,-2]]).set_partition(); X\n {{-2, -1}, {1, 2}}\n sage: X.parent()\n Set partitions\n '
return SetPartitions()(self)
def compose(self, other, check=True):
'\n Compose ``self`` with ``other``.\n\n The composition of two diagrams `X` and `Y` is given by placing\n `X` on top of `Y` and removing all loops.\n\n OUTPUT:\n\n A tuple where the first entry is the composite diagram and the\n second entry is how many loop were removed.\n\n .. NOTE::\n\n This is not really meant to be called directly, but it works\n to call it this way if desired.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.AbstractPartitionDiagrams(2)\n sage: pd([[1,2],[-1,-2]]).compose(pd([[1,2],[-1,-2]]))\n ({{-2, -1}, {1, 2}}, 1)\n '
(composite_diagram, loops_removed) = set_partition_composition(self._base_diagram, other._base_diagram)
return (self.__class__(self.parent(), composite_diagram, check=check), loops_removed)
def propagating_number(self):
'\n Return the propagating number of the diagram.\n\n The propagating number is the number of blocks with both a\n positive and negative number.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.AbstractPartitionDiagrams(2)\n sage: d1 = pd([[1,-2],[2,-1]])\n sage: d1.propagating_number()\n 2\n sage: d2 = pd([[1,2],[-2,-1]])\n sage: d2.propagating_number()\n 0\n '
return ZZ(sum((1 for part in self._base_diagram if ((min(part) < 0) and (max(part) > 0)))))
def count_blocks_of_size(self, n):
'\n Count the number of blocks of a given size.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import PartitionDiagram\n sage: pd = PartitionDiagram([[1,-3,-5],[2,4],[3,-1,-2],[5],[-4]])\n sage: pd.count_blocks_of_size(1)\n 2\n sage: pd.count_blocks_of_size(2)\n 1\n sage: pd.count_blocks_of_size(3)\n 2\n '
return sum((ZZ((len(block) == n)) for block in self))
def order(self):
'\n Return the maximum entry in the diagram element.\n\n A diagram element will be a partition of the set\n `\\{-1, -2, \\ldots, -k, 1, 2, \\ldots, k\\}`. The order of\n the diagram element is the value `k`.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import PartitionDiagram\n sage: PartitionDiagram([[1,-1],[2,-2,-3],[3]]).order()\n 3\n sage: PartitionDiagram([[1,-1]]).order()\n 1\n sage: PartitionDiagram([[1,-3,-5],[2,4],[3,-1,-2],[5],[-4]]).order()\n 5\n '
return self.parent().order
def is_planar(self):
'\n Test if the diagram ``self`` is planar.\n\n A diagram element is planar if the graph of the nodes is planar.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import BrauerDiagram\n sage: BrauerDiagram([[1,-2],[2,-1]]).is_planar()\n False\n sage: BrauerDiagram([[1,-1],[2,-2]]).is_planar()\n True\n '
return is_planar(self)
def dual(self):
'\n Return the dual diagram of ``self`` by flipping it top-to-bottom.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import PartitionDiagram\n sage: D = PartitionDiagram([[1,-1],[2,-2,-3],[3]])\n sage: D.dual()\n {{-3}, {-2, 2, 3}, {-1, 1}}\n '
return self.parent([[(- i) for i in part] for part in self])
|
class IdealDiagram(AbstractPartitionDiagram):
'\n The element class for a ideal diagram.\n\n An ideal diagram for an integer `k` is a partition of the set\n `\\{1, \\ldots, k, -1, \\ldots, -k\\}` where the propagating number is\n strictly smaller than the order.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import IdealDiagrams as IDs\n sage: IDs(2)\n Ideal diagrams of order 2\n sage: IDs(2).list()\n [{{-2, -1, 1, 2}},\n {{-2, 1, 2}, {-1}},\n {{-2}, {-1, 1, 2}},\n {{-2, -1}, {1, 2}},\n {{-2}, {-1}, {1, 2}},\n {{-2, -1, 1}, {2}},\n {{-2, 1}, {-1}, {2}},\n {{-2, -1, 2}, {1}},\n {{-2, 2}, {-1}, {1}},\n {{-2}, {-1, 1}, {2}},\n {{-2}, {-1, 2}, {1}},\n {{-2, -1}, {1}, {2}},\n {{-2}, {-1}, {1}, {2}}]\n\n sage: from sage.combinat.diagram_algebras import PartitionDiagrams as PDs\n sage: PDs(4).cardinality() == factorial(4) + IDs(4).cardinality()\n True\n '
@staticmethod
def __classcall_private__(cls, diag):
'\n Normalize input to initialize diagram.\n\n The order of the diagram element is the maximum value found in\n the list of lists.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import IdealDiagram\n sage: IdealDiagram([[1],[-1]])\n {{-1}, {1}}\n sage: IdealDiagram([[1], [-1]]).parent()\n Ideal diagrams of order 1\n '
order = max((v for p in diag for v in p))
return IdealDiagrams(order)(diag)
def check(self):
'\n Check the validity of the input for ``self``.\n\n TESTS::\n\n sage: from sage.combinat.diagram_algebras import IdealDiagram\n sage: pd1 = IdealDiagram([[1,2],[-1,-2]]) # indirect doctest\n sage: pd2 = IdealDiagram([[1,-2],[2,-1]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: the diagram {{-2, 1}, {-1, 2}} must have a propagating number smaller than the order\n sage: pd3 = IdealDiagram([[1,2,-1,-3]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: {{-3, -1, 1, 2}} does not represent two rows of vertices of order 2\n sage: pd4 = IdealDiagram([[1,-2,-1],[2]]) # indirect doctest\n '
super().check()
if (self.propagating_number() >= self.order()):
raise ValueError(('the diagram %s must have a propagating number smaller than the order' % self))
|
class PlanarDiagram(AbstractPartitionDiagram):
'\n The element class for a planar diagram.\n\n A planar diagram for an integer `k` is a partition of the set\n `\\{1, \\ldots, k, -1, \\ldots, -k\\}` so that the diagram is non-crossing.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import PlanarDiagrams\n sage: PlanarDiagrams(2)\n Planar diagrams of order 2\n sage: PlanarDiagrams(2).list()\n [{{-2}, {-1}, {1, 2}},\n {{-2}, {-1}, {1}, {2}},\n {{-2, 1}, {-1}, {2}},\n {{-2, 2}, {-1}, {1}},\n {{-2, 1, 2}, {-1}},\n {{-2, 2}, {-1, 1}},\n {{-2}, {-1, 1}, {2}},\n {{-2}, {-1, 2}, {1}},\n {{-2}, {-1, 1, 2}},\n {{-2, -1}, {1, 2}},\n {{-2, -1}, {1}, {2}},\n {{-2, -1, 1}, {2}},\n {{-2, -1, 2}, {1}},\n {{-2, -1, 1, 2}}]\n '
@staticmethod
def __classcall_private__(cls, diag):
'\n Normalize input to initialize diagram.\n\n The order of the diagram element is the maximum value found in\n the list of lists.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import PlanarDiagram\n sage: PlanarDiagram([[1,-1]])\n {{-1, 1}}\n sage: PlanarDiagram([[1, -1]]).parent()\n Planar diagrams of order 1\n '
order = max((v for p in diag for v in p))
PD = PlanarDiagrams(order)
return PD(diag)
def check(self):
'\n Check the validity of the input for ``self``.\n\n TESTS::\n\n sage: from sage.combinat.diagram_algebras import PlanarDiagram\n sage: pd1 = PlanarDiagram([[1,2],[-1,-2]]) # indirect doctest\n sage: pd2 = PlanarDiagram([[1,-2],[2,-1]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: the diagram {{-2, 1}, {-1, 2}} must be planar\n sage: pd3 = PlanarDiagram([[1,2,-1,-3]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: {{-3, -1, 1, 2}} does not represent two rows of vertices of order 2\n sage: pd4 = PlanarDiagram([[1,-2,-1],[2]]) # indirect doctest\n '
super().check()
if (not self.is_planar()):
raise ValueError(('the diagram %s must be planar' % self))
|
class TemperleyLiebDiagram(AbstractPartitionDiagram):
'\n The element class for a Temperley-Lieb diagram.\n\n A Temperley-Lieb diagram for an integer `k` is a partition of the set\n `\\{1, \\ldots, k, -1, \\ldots, -k\\}` so that the blocks are all of size\n 2 and the diagram is planar.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import TemperleyLiebDiagrams\n sage: TemperleyLiebDiagrams(2)\n Temperley Lieb diagrams of order 2\n sage: TemperleyLiebDiagrams(2).list()\n [{{-2, -1}, {1, 2}}, {{-2, 2}, {-1, 1}}]\n '
@staticmethod
def __classcall_private__(cls, diag):
'\n Normalize input to initialize diagram.\n\n The order of the diagram element is the maximum value found in\n the list of lists.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import TemperleyLiebDiagram\n sage: TemperleyLiebDiagram([[1,-1]])\n {{-1, 1}}\n sage: TemperleyLiebDiagram([[1, -1]]).parent()\n Temperley Lieb diagrams of order 1\n '
order = max((v for p in diag for v in p))
TLD = TemperleyLiebDiagrams(order)
return TLD(diag)
def check(self):
'\n Check the validity of the input for ``self``.\n\n TESTS::\n\n sage: from sage.combinat.diagram_algebras import TemperleyLiebDiagram\n sage: pd1 = TemperleyLiebDiagram([[1,2],[-1,-2]]) # indirect doctest\n sage: pd2 = TemperleyLiebDiagram([[1,-2],[2,-1]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: the diagram {{-2, 1}, {-1, 2}} must be planar\n sage: pd3 = TemperleyLiebDiagram([[1,2,-1,-3]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: {{-3, -1, 1, 2}} does not represent two rows of vertices of order 2\n sage: pd4 = TemperleyLiebDiagram([[1,-2,-1],[2]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: all blocks of {{-2, -1, 1}, {2}} must be of size 2\n '
super().check()
if any(((len(block) != 2) for block in self)):
raise ValueError(('all blocks of %s must be of size 2' % self))
if (not self.is_planar()):
raise ValueError(('the diagram %s must be planar' % self))
|
class PartitionDiagram(AbstractPartitionDiagram):
'\n The element class for a partition diagram.\n\n A partition diagram for an integer `k` is a partition of the set\n `\\{1, \\ldots, k, -1, \\ldots, -k\\}`\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import PartitionDiagram, PartitionDiagrams\n sage: PartitionDiagrams(1)\n Partition diagrams of order 1\n sage: PartitionDiagrams(1).list()\n [{{-1, 1}}, {{-1}, {1}}]\n sage: PartitionDiagram([[1,-1]])\n {{-1, 1}}\n sage: PartitionDiagram(((1,-2),(2,-1))).parent()\n Partition diagrams of order 2\n '
@staticmethod
def __classcall_private__(cls, diag):
'\n Normalize input to initialize diagram.\n\n The order of the diagram element is the maximum value found in\n the list of lists.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import PartitionDiagram\n sage: PartitionDiagram([[1],[-1]])\n {{-1}, {1}}\n sage: PartitionDiagram([[1],[-1]]).parent()\n Partition diagrams of order 1\n '
order = max((v for p in diag for v in p))
PD = PartitionDiagrams(order)
return PD(diag)
|
class BrauerDiagram(AbstractPartitionDiagram):
'\n A Brauer diagram.\n\n A Brauer diagram for an integer `k` is a partition of the set\n `\\{1, \\ldots, k, -1, \\ldots, -k\\}` with block size 2.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(2)\n sage: bd1 = bd([[1,2],[-1,-2]])\n sage: bd2 = bd([[1,2,-1,-2]])\n Traceback (most recent call last):\n ...\n ValueError: all blocks of {{-2, -1, 1, 2}} must be of size 2\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(2)( ((-2,-1),(1,2)) )\n sage: TestSuite(bd).run()\n '
@staticmethod
def __classcall_private__(cls, diag):
'\n Normalize input to initialize diagram.\n\n The order of the diagram element is the maximum value found in\n the list of lists.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import BrauerDiagram\n sage: bd = BrauerDiagram([[1,-1]]); bd\n {{-1, 1}}\n sage: bd.parent()\n Brauer diagrams of order 1\n '
order = max((v for p in diag for v in p))
BD = BrauerDiagrams(order)
return BD(diag)
def check(self):
'\n Check the validity of the input for ``self``.\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(2)\n sage: bd1 = bd([[1,2],[-1,-2]]) # indirect doctest\n sage: bd2 = bd([[1,2,-1,-2]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: all blocks of {{-2, -1, 1, 2}} must be of size 2\n '
super().check()
if any(((len(i) != 2) for i in self)):
raise ValueError(('all blocks of %s must be of size 2' % self))
def _repr_(self):
'\n Return a string representation of a Brauer diagram.\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(2)\n sage: bd1 = bd([[1,2],[-1,-2]]); bd1\n {{-2, -1}, {1, 2}}\n '
return self.parent().options._dispatch(self, '_repr_', 'display')
class options(GlobalOptions):
'\n Set and display the global options for Brauer diagram (algebras). If no\n parameters are set, then the function returns a copy of the options\n dictionary.\n\n The ``options`` to diagram algebras can be accessed as the method\n :obj:`BrauerAlgebra.options` of :class:`BrauerAlgebra` and\n related classes.\n\n @OPTIONS@\n\n The compact representation ``[A/B;pi]`` of the Brauer algebra diagram\n (see [GL1996]_) has the following components:\n\n - ``A`` -- is a list of pairs of positive elements (upper row) that\n are connected,\n\n - ``B`` -- is a list of pairs of negative elements (lower row) that\n are connected, and\n\n - ``pi`` -- is a permutation that is to be interpreted as the relative\n order of the remaining elements in the top row and the bottom row.\n\n EXAMPLES::\n\n sage: R.<q> = QQ[]\n sage: BA = BrauerAlgebra(2, q)\n sage: E = BA([[1,2],[-1,-2]])\n sage: E\n B{{-2, -1}, {1, 2}}\n sage: BA8 = BrauerAlgebra(8, q)\n sage: BA8([[1,-4],[2,4],[3,8],[-7,-2],[5,7],[6,-1],[-3,-5],[-6,-8]])\n B{{-8, -6}, {-7, -2}, {-5, -3}, {-4, 1}, {-1, 6}, {2, 4}, {3, 8}, {5, 7}}\n sage: BrauerAlgebra.options.display = "compact"\n sage: E\n B[12/12;]\n sage: BA8([[1,-4],[2,4],[3,8],[-7,-2],[5,7],[6,-1],[-3,-5],[-6,-8]])\n B[24.38.57/35.27.68;21]\n sage: BrauerAlgebra.options._reset()\n '
NAME = 'Brauer diagram'
module = 'sage.combinat.diagram_algebras'
option_class = 'BrauerDiagram'
display = dict(default='normal', description='Specifies how the Brauer diagrams should be printed', values=dict(normal='Using the normal representation', compact='Using the compact representation'), case_sensitive=False)
def _repr_normal(self):
"\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(2)\n sage: bd([[1,2],[-1,-2]])._repr_normal()\n '{{-2, -1}, {1, 2}}'\n "
return super()._repr_()
def _repr_compact(self):
"\n Return a compact string representation of ``self``.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(2)\n sage: bd([[1,2],[-1,-2]])._repr_compact()\n '[12/12;]'\n sage: bd([[1,-2],[2,-1]])._repr_compact()\n '[/;21]'\n sage: bd = da.BrauerDiagrams(7)\n sage: bd([[1,4],[6,7], [-2,-6],[-5,-7], [2,-4],[3,-1],[5,-3]])._repr_compact()\n '[14.67/26.57;312]'\n "
(top, bot, thru) = self.involution_permutation_triple()
bot.reverse()
s1 = '.'.join((''.join((str(b) for b in block)) for block in top))
s2 = '.'.join((''.join((str(abs(k)) for k in sorted(block, reverse=True))) for block in bot))
s3 = ''.join((str(x) for x in thru))
return '[{}/{};{}]'.format(s1, s2, s3)
def involution_permutation_triple(self, curt=True):
'\n Return the involution permutation triple of ``self``.\n\n From Graham-Lehrer (see :class:`BrauerDiagrams`), a Brauer diagram\n is a triple `(D_1, D_2, \\pi)`, where:\n\n - `D_1` is a partition of the top nodes;\n - `D_2` is a partition of the bottom nodes;\n - `\\pi` is the induced permutation on the free nodes.\n\n INPUT:\n\n - ``curt`` -- (default: ``True``) if ``True``, then return bijection\n on free nodes as a one-line notation (standardized to look like a\n permutation), else, return the honest mapping, a list of pairs\n `(i, -j)` describing the bijection on free nodes\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(3)\n sage: elm = bd([[1,2],[-2,-3],[3,-1]])\n sage: elm.involution_permutation_triple()\n ([(1, 2)], [(-3, -2)], [1])\n sage: elm.involution_permutation_triple(curt=False)\n ([(1, 2)], [(-3, -2)], [[3, -1]])\n '
top = []
bottom = []
for v in self.diagram():
if (min(v) > 0):
top += [v]
if (max(v) < 0):
bottom += [v]
if curt:
perm = self.perm()
else:
perm = self.bijection_on_free_nodes()
return (top, bottom, perm)
def bijection_on_free_nodes(self, two_line=False):
'\n Return the induced bijection - as a list of `(x,f(x))` values -\n from the free nodes on the top at the Brauer diagram to the free\n nodes at the bottom of ``self``.\n\n OUTPUT:\n\n If ``two_line`` is ``True``, then the output is the induced\n bijection as a two-row list ``(inputs, outputs)``.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(3)\n sage: elm = bd([[1,2],[-2,-3],[3,-1]])\n sage: elm.bijection_on_free_nodes()\n [[3, -1]]\n sage: elm2 = bd([[1,-2],[2,-3],[3,-1]])\n sage: elm2.bijection_on_free_nodes(two_line=True)\n [[1, 2, 3], [-2, -3, -1]]\n '
terms = sorted((sorted(list(v), reverse=True) for v in self.diagram() if ((max(v) > 0) and (min(v) < 0))))
if two_line:
terms = [[t[i] for t in terms] for i in range(2)]
return terms
def perm(self):
'\n Return the induced bijection on the free nodes of ``self`` in\n one-line notation, re-indexed and treated as a permutation.\n\n .. SEEALSO::\n\n :meth:`bijection_on_free_nodes`\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(3)\n sage: elm = bd([[1,2],[-2,-3],[3,-1]])\n sage: elm.perm()\n [1]\n '
long_form = self.bijection_on_free_nodes()
if (not long_form):
return long_form
short_form = [abs(v[1]) for v in long_form]
std = list(range(1, (len(short_form) + 1)))
j = 0
for i in range((max(short_form) + 1)):
if (i in short_form):
j += 1
std[short_form.index(i)] = j
return std
def is_elementary_symmetric(self):
'\n Check if is elementary symmetric.\n\n Let `(D_1, D_2, \\pi)` be the Graham-Lehrer representation\n of the Brauer diagram `d`. We say `d` is *elementary symmetric*\n if `D_1 = D_2` and `\\pi` is the identity.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(3)\n sage: elm = bd([[1,2],[-1,-2],[3,-3]])\n sage: elm.is_elementary_symmetric()\n True\n sage: elm2 = bd([[1,2],[-1,-3],[3,-2]])\n sage: elm2.is_elementary_symmetric()\n False\n '
(D1, D2, pi) = self.involution_permutation_triple()
D1 = sorted((sorted((abs(y) for y in x)) for x in D1))
D2 = sorted((sorted((abs(y) for y in x)) for x in D2))
return ((D1 == D2) and (pi == list(range(1, (len(pi) + 1)))))
|
class AbstractPartitionDiagrams(Parent, UniqueRepresentation):
'\n This is an abstract base class for partition diagrams.\n\n The primary use of this class is to serve as basis keys for\n diagram algebras, but diagrams also have properties in their\n own right. Furthermore, this class is meant to be extended to\n create more efficient contains methods.\n\n INPUT:\n\n - ``order`` -- integer or integer `+ 1/2`; the order of the diagrams\n - ``category`` -- (default: ``FiniteEnumeratedSets()``); the category\n\n All concrete classes should implement attributes\n\n - ``_name`` -- the name of the class\n - ``_diagram_func`` -- an iterator function that takes the order\n as its only input\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.PartitionDiagrams(2)\n sage: pd\n Partition diagrams of order 2\n sage: pd.an_element() in pd\n True\n sage: elm = pd([[1,2],[-1,-2]])\n sage: elm in pd\n True\n '
Element = AbstractPartitionDiagram
def __init__(self, order, category=None):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.AbstractPartitionDiagrams(2)\n sage: pd.category()\n Category of finite enumerated sets\n sage: pd = da.AbstractPartitionDiagrams(2, Sets().Finite())\n sage: pd.category()\n Category of finite sets\n\n sage: pd = da.PartitionDiagrams(2)\n sage: TestSuite(pd).run()\n\n sage: bd = da.BrauerDiagrams(2)\n sage: TestSuite(bd).run()\n\n sage: td = da.TemperleyLiebDiagrams(2)\n sage: TestSuite(td).run()\n\n sage: pld = da.PlanarDiagrams(2)\n sage: TestSuite(pld).run()\n\n sage: id = da.IdealDiagrams(2)\n sage: TestSuite(id).run()\n '
if (category is None):
category = FiniteEnumeratedSets()
Parent.__init__(self, category=category)
if (order in ZZ):
self.order = ZZ(order)
base_set = frozenset((list(range(1, (order + 1))) + list(range((- order), 0))))
else:
self.order = QQ(order)
base_set = frozenset((list(range(1, (ZZ(((ZZ(1) / ZZ(2)) + order)) + 1))) + list(range(ZZ((((- ZZ(1)) / ZZ(2)) - order)), 0))))
self._set = base_set
def _repr_(self):
'\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: da.PartitionDiagrams(2)\n Partition diagrams of order 2\n '
return '{} diagrams of order {}'.format(self._name, self.order)
def __iter__(self):
'\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: list(da.PartitionDiagrams(2))\n [{{-2, -1, 1, 2}},\n {{-2, 1, 2}, {-1}},\n {{-2}, {-1, 1, 2}},\n {{-2, -1}, {1, 2}},\n {{-2}, {-1}, {1, 2}},\n {{-2, -1, 1}, {2}},\n {{-2, 1}, {-1, 2}},\n {{-2, 1}, {-1}, {2}},\n {{-2, 2}, {-1, 1}},\n {{-2, -1, 2}, {1}},\n {{-2, 2}, {-1}, {1}},\n {{-2}, {-1, 1}, {2}},\n {{-2}, {-1, 2}, {1}},\n {{-2, -1}, {1}, {2}},\n {{-2}, {-1}, {1}, {2}}]\n\n sage: list(da.PartitionDiagrams(3/2))\n [{{-2, -1, 1, 2}},\n {{-2, 1, 2}, {-1}},\n {{-2, 2}, {-1, 1}},\n {{-2, -1, 2}, {1}},\n {{-2, 2}, {-1}, {1}}]\n\n sage: list(da.BrauerDiagrams(5/2))\n [{{-3, 3}, {-2, -1}, {1, 2}},\n {{-3, 3}, {-2, 1}, {-1, 2}},\n {{-3, 3}, {-2, 2}, {-1, 1}}]\n sage: list(da.BrauerDiagrams(2))\n [{{-2, -1}, {1, 2}}, {{-2, 1}, {-1, 2}}, {{-2, 2}, {-1, 1}}]\n\n sage: list(da.TemperleyLiebDiagrams(5/2))\n [{{-3, 3}, {-2, -1}, {1, 2}}, {{-3, 3}, {-2, 2}, {-1, 1}}]\n sage: list(da.TemperleyLiebDiagrams(2))\n [{{-2, -1}, {1, 2}}, {{-2, 2}, {-1, 1}}]\n\n sage: list(da.PlanarDiagrams(3/2))\n [{{-2, 1, 2}, {-1}},\n {{-2, 2}, {-1}, {1}},\n {{-2, 2}, {-1, 1}},\n {{-2, -1, 2}, {1}},\n {{-2, -1, 1, 2}}]\n\n sage: list(da.PlanarDiagrams(2))\n [{{-2}, {-1}, {1, 2}},\n {{-2}, {-1}, {1}, {2}},\n {{-2, 1}, {-1}, {2}},\n {{-2, 2}, {-1}, {1}},\n {{-2, 1, 2}, {-1}},\n {{-2, 2}, {-1, 1}},\n {{-2}, {-1, 1}, {2}},\n {{-2}, {-1, 2}, {1}},\n {{-2}, {-1, 1, 2}},\n {{-2, -1}, {1, 2}},\n {{-2, -1}, {1}, {2}},\n {{-2, -1, 1}, {2}},\n {{-2, -1, 2}, {1}},\n {{-2, -1, 1, 2}}]\n\n sage: list(da.IdealDiagrams(3/2))\n [{{-2, -1, 1, 2}},\n {{-2, 1, 2}, {-1}},\n {{-2, -1, 2}, {1}},\n {{-2, 2}, {-1}, {1}}]\n sage: list(da.IdealDiagrams(2))\n [{{-2, -1, 1, 2}},\n {{-2, 1, 2}, {-1}},\n {{-2}, {-1, 1, 2}},\n {{-2, -1}, {1, 2}},\n {{-2}, {-1}, {1, 2}},\n {{-2, -1, 1}, {2}},\n {{-2, 1}, {-1}, {2}},\n {{-2, -1, 2}, {1}},\n {{-2, 2}, {-1}, {1}},\n {{-2}, {-1, 1}, {2}},\n {{-2}, {-1, 2}, {1}},\n {{-2, -1}, {1}, {2}},\n {{-2}, {-1}, {1}, {2}}]\n '
for i in self._diagram_func.__func__(self.order):
(yield self.element_class(self, i, check=False))
def __contains__(self, obj):
'\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.PartitionDiagrams(2)\n sage: pd.an_element() in pd\n True\n sage: elm = pd([[1,2],[-1,-2]])\n sage: elm in pd # indirect doctest\n True\n '
if (not hasattr(obj, '_base_diagram')):
try:
obj = self._element_constructor_(obj)
except (ValueError, TypeError):
return False
if obj.base_diagram():
tst = sorted(flatten(obj.base_diagram()))
if ((len(tst) % 2) or (tst != (list(range(((- len(tst)) // 2), 0)) + list(range(1, ((len(tst) // 2) + 1)))))):
return False
return True
return (self.order == 0)
def _element_constructor_(self, d):
'\n Construct an element of ``self``.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.AbstractPartitionDiagrams(2)\n sage: elm = pd( [[1,2], [-1,-2]] ); elm\n {{-2, -1}, {1, 2}}\n sage: pd( [{1,2}, {-1,-2}] ) == elm\n True\n sage: pd( ((1,2), (-1,-2)) ) == elm\n True\n sage: pd( SetPartition([[1,2], [-1,-2]]) ) == elm\n True\n\n sage: bd = da.BrauerDiagrams(2)\n sage: bd( [[1,2],[-1,-2]] )\n {{-2, -1}, {1, 2}}\n '
return self.element_class(self, d)
|
class PartitionDiagrams(AbstractPartitionDiagrams):
'\n This class represents all partition diagrams of integer or integer\n `+ 1/2` order.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.PartitionDiagrams(1); pd\n Partition diagrams of order 1\n sage: pd.list()\n [{{-1, 1}}, {{-1}, {1}}]\n\n sage: pd = da.PartitionDiagrams(3/2); pd\n Partition diagrams of order 3/2\n sage: pd.list()\n [{{-2, -1, 1, 2}},\n {{-2, 1, 2}, {-1}},\n {{-2, 2}, {-1, 1}},\n {{-2, -1, 2}, {1}},\n {{-2, 2}, {-1}, {1}}]\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.PartitionDiagrams(3)\n sage: pd.an_element() in pd\n True\n sage: pd.cardinality() == len(pd.list())\n True\n\n sage: pd = da.PartitionDiagrams(5/2)\n sage: pd.an_element() in pd\n True\n sage: pd.cardinality() == len(pd.list())\n True\n '
Element = PartitionDiagram
_name = 'Partition'
_diagram_func = partition_diagrams
def cardinality(self):
'\n The cardinality of partition diagrams of half-integer order `n` is\n the `2n`-th Bell number.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pd = da.PartitionDiagrams(3)\n sage: pd.cardinality()\n 203\n\n sage: pd = da.PartitionDiagrams(7/2)\n sage: pd.cardinality()\n 877\n '
return bell_number(ZZ((2 * self.order)))
|
class BrauerDiagrams(AbstractPartitionDiagrams):
'\n This class represents all Brauer diagrams of integer or integer\n `+1/2` order. For more information on Brauer diagrams,\n see :class:`BrauerAlgebra`.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(2); bd\n Brauer diagrams of order 2\n sage: bd.list()\n [{{-2, -1}, {1, 2}}, {{-2, 1}, {-1, 2}}, {{-2, 2}, {-1, 1}}]\n\n sage: bd = da.BrauerDiagrams(5/2); bd\n Brauer diagrams of order 5/2\n sage: bd.list()\n [{{-3, 3}, {-2, -1}, {1, 2}},\n {{-3, 3}, {-2, 1}, {-1, 2}},\n {{-3, 3}, {-2, 2}, {-1, 1}}]\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(3)\n sage: bd.an_element() in bd\n True\n sage: bd.cardinality() == len(bd.list())\n True\n\n sage: bd = da.BrauerDiagrams(5/2)\n sage: bd.an_element() in bd\n True\n sage: bd.cardinality() == len(bd.list())\n True\n\n These diagrams also come equipped with a compact representation based\n on their bipartition triple representation. See the\n :meth:`from_involution_permutation_triple` method for more information.\n\n ::\n\n sage: bd = da.BrauerDiagrams(3)\n sage: bd.options.display="compact"\n sage: bd.list()\n [[12/12;1],\n [13/12;1],\n [23/12;1],\n [23/13;1],\n [23/23;1],\n [/;132],\n [/;231],\n [/;321],\n [13/13;1],\n [12/13;1],\n [12/23;1],\n [13/23;1],\n [/;312],\n [/;213],\n [/;123]]\n sage: bd.options._reset()\n '
Element = BrauerDiagram
options = BrauerDiagram.options
_name = 'Brauer'
_diagram_func = brauer_diagrams
def __contains__(self, obj):
'\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(2)\n sage: bd.an_element() in bd\n True\n sage: bd([[1,2],[-1,-2]]) in bd\n True\n sage: [[1,2,-1,-2]] in bd\n False\n sage: bd = da.BrauerDiagrams(3/2)\n sage: bd.an_element() in bd\n True\n\n '
if (self.order in ZZ):
r = ZZ(self.order)
else:
r = ZZ((self.order + (ZZ(1) / ZZ(2))))
return (super().__contains__(obj) and ([len(i) for i in obj] == ([2] * r)))
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n The number of Brauer diagrams of integer order `k` is `(2k-1)!!`.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(3)\n sage: bd.cardinality()\n 15\n\n sage: bd = da.BrauerDiagrams(7/2)\n sage: bd.cardinality()\n 15\n '
if (self.order in ZZ):
return ((2 * ZZ(self.order)) - 1).multifactorial(2)
else:
return ((2 * ZZ((self.order - (1 / 2)))) - 1).multifactorial(2)
def symmetric_diagrams(self, l=None, perm=None):
'\n Return the list of Brauer diagrams with symmetric placement of `l` arcs,\n and with free nodes permuted according to `perm`.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(4)\n sage: bd.symmetric_diagrams(l=1, perm=[2,1])\n [{{-4, -2}, {-3, 1}, {-1, 3}, {2, 4}},\n {{-4, -3}, {-2, 1}, {-1, 2}, {3, 4}},\n {{-4, -1}, {-3, 2}, {-2, 3}, {1, 4}},\n {{-4, 2}, {-3, -1}, {-2, 4}, {1, 3}},\n {{-4, 3}, {-3, 4}, {-2, -1}, {1, 2}},\n {{-4, 1}, {-3, -2}, {-1, 4}, {2, 3}}]\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(3/2)\n sage: bd.symmetric_diagrams(l=1, perm=[2,1])\n Traceback (most recent call last):\n ...\n NotImplementedError: only implemented for integer order, not for order 3/2\n '
if (self.order not in ZZ):
raise NotImplementedError(('only implemented for integer order, not for order %s' % self.order))
n = ZZ(self.order)
if (l is None):
l = 0
if (perm is None):
perm = list(range(1, ((n + 1) - (2 * l))))
out = []
partition_shape = (([2] * l) + ([1] * (n - (2 * l))))
for sp in SetPartitions(n, partition_shape):
sp0 = [block for block in sp if (len(block) == 2)]
diag = self.from_involution_permutation_triple((sp0, sp0, perm))
out.append(diag)
return out
def from_involution_permutation_triple(self, D1_D2_pi):
'\n Construct a Brauer diagram of ``self`` from an involution\n permutation triple.\n\n A Brauer diagram can be represented as a triple where the first\n entry is a list of arcs on the top row of the diagram, the second\n entry is a list of arcs on the bottom row of the diagram, and the\n third entry is a permutation on the remaining nodes. This triple\n is called the *involution permutation triple*. For more\n information, see [GL1996]_.\n\n INPUT:\n\n - ``D1_D2_pi``-- a list or tuple where the first entry is a list of\n arcs on the top of the diagram, the second entry is a list of arcs\n on the bottom of the diagram, and the third entry is a permutation\n on the free nodes.\n\n REFERENCES:\n\n .. [GL1996] \\J.J. Graham and G.I. Lehrer, Cellular algebras.\n Inventiones mathematicae 123 (1996), 1--34.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(4)\n sage: bd.from_involution_permutation_triple([[[1,2]],[[3,4]],[2,1]])\n {{-4, -3}, {-2, 3}, {-1, 4}, {1, 2}}\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: bd = da.BrauerDiagrams(5/2)\n sage: bd.from_involution_permutation_triple([[[1,2]],[[3,4]],[2,1]])\n Traceback (most recent call last):\n ...\n NotImplementedError: only implemented for integer order, not for order 5/2\n '
if (self.order not in ZZ):
raise NotImplementedError(('only implemented for integer order, not for order %s' % self.order))
try:
(D1, D2, pi) = tuple(D1_D2_pi)
except ValueError:
raise ValueError(('argument %s not in correct form; must be a tuple (D1, D2, pi)' % D1_D2_pi))
D1 = [[abs(x) for x in b] for b in D1 if (len(b) == 2)]
D2 = [[abs(x) for x in b] for b in D2 if (len(b) == 2)]
nD2 = [[(- i) for i in b] for b in D2]
pi = list(pi)
nn = set(range(1, (self.order + 1)))
dom = sorted(nn.difference(flatten([list(x) for x in D1])))
rng = sorted(nn.difference(flatten([list(x) for x in D2])))
SP0 = (D1 + nD2)
if ((len(pi) != len(dom)) or (pi not in Permutations())):
raise ValueError('in the tuple (D1, D2, pi)={}, pi must be a permutation of {} (indicating a permutation on the free nodes of the diagram)'.format((D1, D2, pi), (self.order - (2 * len(D1)))))
Perm = [[dom[i], (- rng[(val - 1)])] for (i, val) in enumerate(pi)]
SP = (SP0 + Perm)
return self(SP)
|
class TemperleyLiebDiagrams(AbstractPartitionDiagrams):
'\n All Temperley-Lieb diagrams of integer or integer `+1/2` order.\n\n For more information on Temperley-Lieb diagrams, see\n :class:`TemperleyLiebAlgebra`.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: td = da.TemperleyLiebDiagrams(3); td\n Temperley Lieb diagrams of order 3\n sage: td.list()\n [{{-3, 3}, {-2, -1}, {1, 2}},\n {{-3, 1}, {-2, -1}, {2, 3}},\n {{-3, -2}, {-1, 1}, {2, 3}},\n {{-3, -2}, {-1, 3}, {1, 2}},\n {{-3, 3}, {-2, 2}, {-1, 1}}]\n\n sage: td = da.TemperleyLiebDiagrams(5/2); td\n Temperley Lieb diagrams of order 5/2\n sage: td.list()\n [{{-3, 3}, {-2, -1}, {1, 2}}, {{-3, 3}, {-2, 2}, {-1, 1}}]\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: td = da.TemperleyLiebDiagrams(3)\n sage: td.an_element() in td\n True\n sage: td.cardinality() == len(td.list())\n True\n\n sage: td = da.TemperleyLiebDiagrams(7/2)\n sage: td.an_element() in td\n True\n sage: td.cardinality() == len(td.list())\n True\n '
Element = TemperleyLiebDiagram
_name = 'Temperley Lieb'
_diagram_func = temperley_lieb_diagrams
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n The number of Temperley--Lieb diagrams of integer order `k` is the\n `k`-th Catalan number.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: td = da.TemperleyLiebDiagrams(3)\n sage: td.cardinality()\n 5\n '
if (self.order in ZZ):
return catalan_number(ZZ(self.order))
else:
return catalan_number(ZZ((self.order - (1 / 2))))
def __contains__(self, obj):
'\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: td = da.TemperleyLiebDiagrams(2)\n sage: td.an_element() in td\n True\n sage: td([[1,2],[-1,-2]]) in td\n True\n sage: [[1,2],[-1,-2]] in td\n True\n sage: [[1,-2],[-1,2]] in td\n False\n '
if (not hasattr(obj, '_base_diagram')):
try:
obj = self._element_constructor_(obj)
except (ValueError, TypeError):
return False
return ((obj in BrauerDiagrams(self.order)) and obj.is_planar())
|
class PlanarDiagrams(AbstractPartitionDiagrams):
'\n All planar diagrams of integer or integer `+1/2` order.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pld = da.PlanarDiagrams(1); pld\n Planar diagrams of order 1\n sage: pld.list()\n [{{-1, 1}}, {{-1}, {1}}]\n\n sage: pld = da.PlanarDiagrams(3/2); pld\n Planar diagrams of order 3/2\n sage: pld.list()\n [{{-2, 1, 2}, {-1}},\n {{-2, 2}, {-1}, {1}},\n {{-2, 2}, {-1, 1}},\n {{-2, -1, 2}, {1}},\n {{-2, -1, 1, 2}}]\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pld = da.PlanarDiagrams(3)\n sage: pld.an_element() in pld\n True\n sage: pld.cardinality() == len(pld.list())\n True\n sage: pld = da.PlanarDiagrams(5/2)\n sage: pld.an_element() in pld\n True\n sage: pld.cardinality() == len(pld.list())\n True\n '
Element = PlanarDiagram
_name = 'Planar'
_diagram_func = planar_diagrams
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n The number of all planar diagrams of order `k` is the\n `2k`-th Catalan number.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pld = da.PlanarDiagrams(3)\n sage: pld.cardinality()\n 132\n '
return catalan_number((2 * self.order))
def __contains__(self, obj):
'\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: pld = da.PlanarDiagrams(2)\n sage: pld.an_element() in pld\n True\n sage: pld([[1,2],[-1,-2]]) in pld\n True\n sage: [[1,2],[-1,-2]] in pld\n True\n sage: [[1,-2],[-1,2]] in pld\n False\n '
if (not hasattr(obj, '_base_diagram')):
try:
obj = self._element_constructor_(obj)
except (ValueError, TypeError):
return False
return super().__contains__(obj)
|
class IdealDiagrams(AbstractPartitionDiagrams):
'\n All "ideal" diagrams of integer or integer `+1/2` order.\n\n If `k` is an integer then an ideal diagram of order `k` is a partition\n diagram of order `k` with propagating number less than `k`.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: id = da.IdealDiagrams(3)\n sage: id.an_element() in id\n True\n sage: id.cardinality() == len(id.list())\n True\n sage: da.IdealDiagrams(3/2).list()\n [{{-2, -1, 1, 2}},\n {{-2, 1, 2}, {-1}},\n {{-2, -1, 2}, {1}},\n {{-2, 2}, {-1}, {1}}]\n '
Element = IdealDiagram
_name = 'Ideal'
_diagram_func = ideal_diagrams
def __contains__(self, obj):
'\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: id = da.IdealDiagrams(2)\n sage: id.an_element() in id\n True\n sage: id([[1,2],[-1,-2]]) in id\n True\n sage: [[1,2],[-1,-2]] in id\n True\n sage: [[1,-2],[-1,2]] in id\n False\n '
if (not hasattr(obj, '_base_diagram')):
try:
obj = self._element_constructor_(obj)
except (ValueError, TypeError):
return False
return (super().__contains__(obj) and (obj.propagating_number() < self.order))
|
class DiagramAlgebra(CombinatorialFreeModule):
"\n Abstract class for diagram algebras and is not designed to be used\n directly.\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: R.<x> = QQ[]\n sage: D = da.DiagramAlgebra(2, x, R, 'P', da.PartitionDiagrams(2))\n sage: list(D.basis())\n [P{{-2, -1, 1, 2}},\n P{{-2, 1, 2}, {-1}},\n P{{-2}, {-1, 1, 2}},\n P{{-2, -1}, {1, 2}},\n P{{-2}, {-1}, {1, 2}},\n P{{-2, -1, 1}, {2}},\n P{{-2, 1}, {-1, 2}},\n P{{-2, 1}, {-1}, {2}},\n P{{-2, 2}, {-1, 1}},\n P{{-2, -1, 2}, {1}},\n P{{-2, 2}, {-1}, {1}},\n P{{-2}, {-1, 1}, {2}},\n P{{-2}, {-1, 2}, {1}},\n P{{-2, -1}, {1}, {2}},\n P{{-2}, {-1}, {1}, {2}}]\n "
def __init__(self, k, q, base_ring, prefix, diagrams, category=None):
"\n Initialize ``self``.\n\n INPUT:\n\n - ``k`` -- the rank\n - ``q`` -- the deformation parameter\n - ``base_ring`` -- the base ring\n - ``prefix`` -- the prefix of our monomials\n - ``diagrams`` -- the object representing all the diagrams\n (i.e. indices for the basis elements)\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: R.<x> = QQ[]\n sage: D = da.DiagramBasis(2, x, R, 'P', da.PartitionDiagrams(2))\n sage: TestSuite(D).run()\n "
self._prefix = prefix
self._q = base_ring(q)
self._k = k
self._base_diagrams = diagrams
cat = AssociativeAlgebras(base_ring.category()).FiniteDimensional().WithBasis()
if isinstance(self, UnitDiagramMixin):
cat = cat.Unital()
category = cat.or_subcategory(category)
CombinatorialFreeModule.__init__(self, base_ring, diagrams, category=category, prefix=prefix, bracket=False)
def _element_constructor_(self, set_partition):
"\n Construct an element of ``self``.\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: R.<x> = QQ[]\n sage: D = da.DiagramAlgebra(2, x, R, 'P', da.PartitionDiagrams(2))\n sage: sp = da.to_set_partition( [[1,2], [-1,-2]] )\n sage: b_elt = D(sp); b_elt\n P{{-2, -1}, {1, 2}}\n sage: b_elt in D\n True\n sage: D([[1,2],[-1,-2]]) == b_elt\n True\n sage: D([{1,2},{-1,-2}]) == b_elt\n True\n sage: S = SymmetricGroupAlgebra(R,2)\n sage: D(S([2,1]))\n P{{-2, 1}, {-1, 2}}\n sage: D2 = da.DiagramAlgebra(2, x, R, 'P', da.PlanarDiagrams(2))\n sage: D2(S([1,2]))\n P{{-2, 2}, {-1, 1}}\n sage: D2(S([2,1]))\n Traceback (most recent call last):\n ...\n ValueError: the diagram {{-2, 1}, {-1, 2}} must be planar\n "
if self.basis().keys().is_parent_of(set_partition):
return self.basis()[set_partition]
if isinstance(set_partition, SymmetricGroupAlgebra_n.Element):
return self._apply_module_morphism(set_partition, self._perm_to_Blst, self)
sp = self._base_diagrams(set_partition)
if (sp in self.basis().keys()):
return self.basis()[sp]
raise ValueError('invalid input of {0}'.format(set_partition))
def __getitem__(self, d):
"\n Get the basis item of ``self`` indexed by ``d``.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: R.<x> = QQ[]\n sage: D = da.DiagramAlgebra(2, x, R, 'P', da.PartitionDiagrams(2))\n sage: sp = da.PartitionDiagrams(2)( [[1,2], [-1,-2]] )\n sage: D[sp]\n P{{-2, -1}, {1, 2}}\n sage: D[[1,-1,2,-2]]\n P{{-2, -1, 1, 2}}\n sage: D3 = da.DiagramAlgebra(3, x, R, 'P', da.PartitionDiagrams(3))\n sage: da.PartitionDiagrams(3)( [[1,2], [-1,-2]] )\n Traceback (most recent call last):\n ...\n ValueError: {{-2, -1}, {1, 2}} does not represent two rows of vertices of order 3\n sage: D3[sp]\n P{{-3, 3}, {-2, -1}, {1, 2}}\n sage: D3[[1,-1,2,-2]]\n P{{-3, 3}, {-2, -1, 1, 2}}\n sage: D3[[1,2,-2]]\n P{{-3, 3}, {-2, 1, 2}, {-1}}\n sage: P = PartitionAlgebra(3,x)\n sage: P[[1]]\n P{{-3, 3}, {-2, 2}, {-1}, {1}}\n "
if (isinstance(d, (list, tuple)) and all(((a in ZZ) for a in d))):
d = [d]
d = self._base_diagrams(to_set_partition(d, self._k))
if (d in self.basis().keys()):
return self.basis()[d]
raise ValueError('{0} is not an index of a basis element'.format(d))
def _perm_to_Blst(self, w):
"\n Convert the permutation ``w`` to an element of ``self``.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: S = SymmetricGroupAlgebra(R,2)\n sage: import sage.combinat.diagram_algebras as da\n sage: D2 = da.DiagramAlgebra(2, x, R, 'P', da.PlanarDiagrams(2))\n sage: D2._perm_to_Blst([2,1])\n Traceback (most recent call last):\n ...\n ValueError: the diagram {{-2, 1}, {-1, 2}} must be planar\n "
u = sorted(w)
p = [[u[i], (- x)] for (i, x) in enumerate(w)]
if (len(u) < self.order()):
p1 = [[j, (- j)] for j in range((len(u) + 1), (self.order() + 1))]
p.extend(p1)
return self[p]
def _diag_to_Blst(self, d):
"\n Return an element of ``self`` from the input ``d``.\n\n If ``d`` is a partial diagram of `\\{1,2,\\ldots,k,-1,-2,\\ldots,-k\\}`\n then the set partition is filled in by adding the parts `\\{i,-i\\}`\n if possible, and singletons sets for the remaining parts.\n\n INPUT:\n\n - ``d`` -- an iterable that behaves like\n :class:`AbstractPartitionDiagram` or :class:`Permutation`\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: PartitionAlgebra(3, x, R)._diag_to_Blst([[1,2], [-3,-1]])\n P{{-3, -1}, {-2}, {1, 2}, {3}}\n sage: BrauerAlgebra(4, x, R)._diag_to_Blst([3,1,2])\n B{{-4, 4}, {-3, 1}, {-2, 3}, {-1, 2}}\n sage: import sage.combinat.diagram_algebras as da\n sage: D3 = da.DiagramAlgebra(3, x, R, 'P', da.PlanarDiagrams(3))\n sage: D3._diag_to_Blst([[1, 2], [-2,-1]])\n P{{-3, 3}, {-2, -1}, {1, 2}}\n sage: D3._diag_to_Blst([[-1,2], [-2,1]])\n Traceback (most recent call last):\n ...\n ValueError: the diagram {{-3, 3}, {-2, 1}, {-1, 2}} must be planar\n sage: D3._diag_to_Blst([[-1,2], [-3,1]])\n Traceback (most recent call last):\n ...\n ValueError: the diagram {{-3, 1}, {-2}, {-1, 2}, {3}} must be planar\n "
d = list(d)
if (not d):
return self.one()
if (d[0] in ZZ):
return self._perm_to_Blst(d)
d = to_set_partition(d, self._k)
return self[self._base_diagrams(d)]
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: q = var('q') # needs sage.symbolic\n sage: PA = PartitionAlgebra(2, q) # needs sage.symbolic\n sage: PA.order() # needs sage.symbolic\n 2\n "
return self._k
def set_partitions(self):
"\n Return the collection of underlying set partitions indexing the\n basis elements of a given diagram algebra.\n\n .. TODO:: Is this really necessary? deprecate?\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: R.<x> = QQ[]\n sage: D = da.DiagramAlgebra(2, x, R, 'P', da.PartitionDiagrams(2))\n sage: list(D.set_partitions()) == list(da.PartitionDiagrams(2))\n True\n "
return self.basis().keys()
def _latex_term(self, diagram):
'\n Return `\\LaTeX` representation of ``diagram`` to draw\n diagram algebra element in latex using tikz.\n\n EXAMPLES::\n\n sage: R.<x> = ZZ[]\n sage: P = PartitionAlgebra(2, x, R)\n sage: latex(P([[1,2],[-2,-1]])) # indirect doctest\n \\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\n sage: latex(P.orbit_basis()([[1,2],[-2,-1]])) # indirect doctest\n \\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, fill] {};\n \\node[vertex] (G--1) at (0.0, -1) [shape = circle, draw, fill] {};\n \\node[vertex] (G-1) at (0.0, 1) [shape = circle, draw, fill] {};\n \\node[vertex] (G-2) at (1.5, 1) [shape = circle, draw, fill] {};\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 '
return diagram_latex(diagram, fill=hasattr(self, '_fill'))
class Element(CombinatorialFreeModule.Element):
'\n An element of a diagram algebra.\n\n This subclass provides a few additional methods for\n partition algebra elements. Most element methods are\n already implemented elsewhere.\n '
def diagram(self):
'\n Return the underlying diagram of ``self`` if ``self`` is a basis\n element. Raises an error if ``self`` is not a basis element.\n\n EXAMPLES::\n\n sage: R.<x> = ZZ[]\n sage: P = PartitionAlgebra(2, x, R)\n sage: elt = 3*P([[1,2],[-2,-1]])\n sage: elt.diagram()\n {{-2, -1}, {1, 2}}\n '
if (len(self) != 1):
raise ValueError('this is only defined for basis elements')
PA = self.parent()
ans = self.support_of_term()
if (ans not in PA.basis().keys()):
raise ValueError('element should be keyed by a diagram')
return ans
def diagrams(self):
'\n Return the diagrams in the support of ``self``.\n\n EXAMPLES::\n\n sage: R.<x> = ZZ[]\n sage: P = PartitionAlgebra(2, x, R)\n sage: elt = 3*P([[1,2],[-2,-1]]) + P([[1,2],[-2], [-1]])\n sage: sorted(elt.diagrams(), key=str)\n [{{-2, -1}, {1, 2}}, {{-2}, {-1}, {1, 2}}]\n '
return self.support()
|
class UnitDiagramMixin():
'\n Mixin class for diagram algebras that have the unit indexed by\n the :func:`identity_set_partition`.\n '
@cached_method
def one_basis(self):
'\n The following constructs the identity element of ``self``.\n\n It is not called directly; instead one should use ``DA.one()`` if\n ``DA`` is a defined diagram algebra.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: P = PartitionAlgebra(2, x, R)\n sage: P.one_basis()\n {{-2, 2}, {-1, 1}}\n '
return self._base_diagrams(identity_set_partition(self._k))
|
class DiagramBasis(DiagramAlgebra):
'\n Abstract base class for diagram algebras in the diagram basis.\n '
def product_on_basis(self, d1, d2):
"\n Return the product `D_{d_1} D_{d_2}` by two basis diagrams.\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: R.<x> = QQ[]\n sage: D = da.DiagramBasis(2, x, R, 'P', da.PartitionDiagrams(2))\n sage: sp = da.PartitionDiagrams(2)([[1,2],[-1,-2]])\n sage: D.product_on_basis(sp, sp)\n x*P{{-2, -1}, {1, 2}}\n "
if (not self._indices.is_parent_of(d1)):
d1 = self._indices(d1)
if (not self._indices.is_parent_of(d2)):
d2 = self._indices(d2)
(composite_diagram, loops_removed) = d1.compose(d2, check=False)
return self.term(composite_diagram, (self._q ** loops_removed))
|
class PartitionAlgebra(DiagramBasis, UnitDiagramMixin):
'\n A partition algebra.\n\n A partition algebra of rank `k` over a given ground ring `R` is an\n algebra with (`R`-module) basis indexed by the collection of set\n partitions of `\\{1, \\ldots, k, -1, \\ldots, -k\\}`. Each such set\n partition can be represented by a graph on nodes `\\{1, \\ldots, k, -1,\n \\ldots, -k\\}` arranged in two rows, with nodes `1, \\ldots, k` in the\n top row from left to right and with nodes `-1, \\ldots, -k` in the\n bottom row from left to right, and edges drawn such that the connected\n components of the graph are precisely the parts of the set partition.\n (This choice of edges is often not unique, and so there are often many\n graphs representing one and the same set partition; the representation\n nevertheless is useful and vivid. We often speak of "diagrams" to mean\n graphs up to such equivalence of choices of edges; of course, we could\n just as well speak of set partitions.)\n\n There is not just one partition algebra of given rank over a given\n ground ring, but rather a whole family of them, indexed by the\n elements of `R`. More precisely, for every `q \\in R`, the partition\n algebra of rank `k` over `R` with parameter `q` is defined to be the\n `R`-algebra with basis the collection of all set partitions of\n `\\{1, \\ldots, k, -1, \\ldots, -k\\}`, where the product of two basis\n elements is given by the rule\n\n .. MATH::\n\n a \\cdot b = q^N (a \\circ b),\n\n where `a \\circ b` is the composite set partition obtained by placing\n the diagram (i.e., graph) of `a` above the diagram of `b`, identifying\n the bottom row nodes of `a` with the top row nodes of `b`, and\n omitting any closed "loops" in the middle. The number `N` is the\n number of connected components formed by the omitted loops.\n\n The parameter `q` is a deformation parameter. Taking `q = 1` produces\n the semigroup algebra (over the base ring) of the partition monoid,\n in which the product of two set partitions is simply given by their\n composition.\n\n The partition algebra is regarded as an example of a "diagram algebra"\n due to the fact that its natural basis is given by certain graphs\n often called diagrams.\n\n There are a number of predefined elements for the partition algebra.\n We define the cup/cap pair by :meth:`a()`. The simple transpositions\n are denoted :meth:`s()`. Finally, we define elements :meth:`e()`,\n where if `i = (2r+1)/2`, then ``e(i)`` contains the blocks `\\{r+1\\}`\n and `\\{-r-1\\}` and if `i \\in \\ZZ`, then `e_i` contains the block\n `\\{-i, -i-1, i, i+1\\}`, with all other blocks being `\\{-j, j\\}`.\n So we have::\n\n sage: P = PartitionAlgebra(4, 0)\n sage: P.a(2)\n P{{-4, 4}, {-3, -2}, {-1, 1}, {2, 3}}\n sage: P.e(3/2)\n P{{-4, 4}, {-3, 3}, {-2}, {-1, 1}, {2}}\n sage: P.e(2)\n P{{-4, 4}, {-3, -2, 2, 3}, {-1, 1}}\n sage: P.e(5/2)\n P{{-4, 4}, {-3}, {-2, 2}, {-1, 1}, {3}}\n sage: P.s(2)\n P{{-4, 4}, {-3, 2}, {-2, 3}, {-1, 1}}\n\n An excellent reference for partition algebras and their various\n subalgebras (Brauer algebra, Temperley--Lieb algebra, etc) is the\n paper [HR2005]_.\n\n INPUT:\n\n - ``k`` -- rank of the algebra\n\n - ``q`` -- the deformation parameter `q`\n\n OPTIONAL ARGUMENTS:\n\n - ``base_ring`` -- (default ``None``) a ring containing ``q``; if\n ``None``, then Sage automatically chooses the parent of ``q``\n\n - ``prefix`` -- (default ``"P"``) a label for the basis elements\n\n EXAMPLES:\n\n The following shorthand simultaneously defines the univariate polynomial\n ring over the rationals as well as the variable ``x``::\n\n sage: R.<x> = PolynomialRing(QQ)\n sage: R\n Univariate Polynomial Ring in x over Rational Field\n sage: x\n x\n sage: x.parent() is R\n True\n\n We now define the partition algebra of rank `2` with parameter ``x``\n over `\\ZZ` in the usual (diagram) basis::\n\n sage: R.<x> = ZZ[]\n sage: A2 = PartitionAlgebra(2, x, R)\n sage: A2\n Partition Algebra of rank 2 with parameter x\n over Univariate Polynomial Ring in x over Integer Ring\n sage: A2.basis().keys()\n Partition diagrams of order 2\n sage: A2.basis().keys()([[-2, 1, 2], [-1]])\n {{-2, 1, 2}, {-1}}\n sage: A2.basis().list()\n [P{{-2, -1, 1, 2}}, P{{-2, 1, 2}, {-1}},\n P{{-2}, {-1, 1, 2}}, P{{-2, -1}, {1, 2}},\n P{{-2}, {-1}, {1, 2}}, P{{-2, -1, 1}, {2}},\n P{{-2, 1}, {-1, 2}}, P{{-2, 1}, {-1}, {2}},\n P{{-2, 2}, {-1, 1}}, P{{-2, -1, 2}, {1}},\n P{{-2, 2}, {-1}, {1}}, P{{-2}, {-1, 1}, {2}},\n P{{-2}, {-1, 2}, {1}}, P{{-2, -1}, {1}, {2}},\n P{{-2}, {-1}, {1}, {2}}]\n sage: E = A2([[1,2],[-2,-1]]); E\n P{{-2, -1}, {1, 2}}\n sage: E in A2.basis().list()\n True\n sage: E^2\n x*P{{-2, -1}, {1, 2}}\n sage: E^5\n x^4*P{{-2, -1}, {1, 2}}\n sage: (A2([[2,-2],[-1,1]]) - 2*A2([[1,2],[-1,-2]]))^2\n (4*x-4)*P{{-2, -1}, {1, 2}} + P{{-2, 2}, {-1, 1}}\n\n Next, we construct an element::\n\n sage: a2 = A2.an_element(); a2\n 3*P{{-2}, {-1, 1, 2}} + 2*P{{-2, -1, 1, 2}} + 2*P{{-2, 1, 2}, {-1}}\n\n There is a natural embedding into partition algebras on more\n elements, by adding identity strands::\n\n sage: A4 = PartitionAlgebra(4, x, R)\n sage: A4(a2)\n 3*P{{-4, 4}, {-3, 3}, {-2}, {-1, 1, 2}}\n + 2*P{{-4, 4}, {-3, 3}, {-2, -1, 1, 2}}\n + 2*P{{-4, 4}, {-3, 3}, {-2, 1, 2}, {-1}}\n\n Thus, the empty partition corresponds to the identity::\n\n sage: A4([])\n P{{-4, 4}, {-3, 3}, {-2, 2}, {-1, 1}}\n sage: A4(5)\n 5*P{{-4, 4}, {-3, 3}, {-2, 2}, {-1, 1}}\n\n The group algebra of the symmetric group is a subalgebra::\n\n sage: S3 = SymmetricGroupAlgebra(ZZ, 3)\n sage: s3 = S3.an_element(); s3\n [1, 2, 3] + 2*[1, 3, 2] + 3*[2, 1, 3] + [3, 1, 2]\n sage: A4(s3)\n P{{-4, 4}, {-3, 1}, {-2, 3}, {-1, 2}}\n + 2*P{{-4, 4}, {-3, 2}, {-2, 3}, {-1, 1}}\n + 3*P{{-4, 4}, {-3, 3}, {-2, 1}, {-1, 2}}\n + P{{-4, 4}, {-3, 3}, {-2, 2}, {-1, 1}}\n sage: A4([2,1])\n P{{-4, 4}, {-3, 3}, {-2, 1}, {-1, 2}}\n\n Be careful not to confuse the embedding of the group algebra of\n the symmetric group with the embedding of partial set partitions.\n The latter are embedded by adding the parts `\\{i,-i\\}` if\n possible, and singletons sets for the remaining parts::\n\n sage: A4([[2,1]])\n P{{-4, 4}, {-3, 3}, {-2}, {-1}, {1, 2}}\n sage: A4([[-1,3],[-2,-3,1]])\n P{{-4, 4}, {-3, -2, 1}, {-1, 3}, {2}}\n\n Another subalgebra is the Brauer algebra, which has perfect\n matchings as basis elements. The group algebra of the\n symmetric group is in fact a subalgebra of the Brauer algebra::\n\n sage: B3 = BrauerAlgebra(3, x, R)\n sage: b3 = B3(s3); b3\n B{{-3, 1}, {-2, 3}, {-1, 2}} + 2*B{{-3, 2}, {-2, 3}, {-1, 1}}\n + 3*B{{-3, 3}, {-2, 1}, {-1, 2}} + B{{-3, 3}, {-2, 2}, {-1, 1}}\n\n An important basis of the partition algebra is the\n :meth:`orbit basis <orbit_basis>`::\n\n sage: O2 = A2.orbit_basis()\n sage: o2 = O2([[1,2],[-1,-2]]) + O2([[1,2,-1,-2]]); o2\n O{{-2, -1}, {1, 2}} + O{{-2, -1, 1, 2}}\n\n The diagram basis element corresponds to the sum of all orbit\n basis elements indexed by coarser set partitions::\n\n sage: A2(o2)\n P{{-2, -1}, {1, 2}}\n\n We can convert back from the orbit basis to the diagram basis::\n\n sage: o2 = O2.an_element(); o2\n 3*O{{-2}, {-1, 1, 2}} + 2*O{{-2, -1, 1, 2}} + 2*O{{-2, 1, 2}, {-1}}\n sage: A2(o2)\n 3*P{{-2}, {-1, 1, 2}} - 3*P{{-2, -1, 1, 2}} + 2*P{{-2, 1, 2}, {-1}}\n\n One can work with partition algebras using a symbol for the parameter,\n leaving the base ring unspecified. This implies that the underlying\n base ring is Sage\'s symbolic ring.\n\n ::\n\n sage: # needs sage.symbolic\n sage: q = var(\'q\')\n sage: PA = PartitionAlgebra(2, q); PA\n Partition Algebra of rank 2 with parameter q over Symbolic Ring\n sage: PA([[1,2],[-2,-1]])^2 == q*PA([[1,2],[-2,-1]])\n True\n sage: ((PA([[2, -2], [1, -1]]) - 2*PA([[-2, -1], [1, 2]]))^2\n ....: == (4*q-4)*PA([[1, 2], [-2, -1]]) + PA([[2, -2], [1, -1]]))\n True\n\n The identity element of the partition algebra is the set\n partition `\\{\\{1,-1\\}, \\{2,-2\\}, \\ldots, \\{k,-k\\}\\}`::\n\n sage: # needs sage.symbolic\n sage: P = PA.basis().list()\n sage: PA.one()\n P{{-2, 2}, {-1, 1}}\n sage: PA.one() * P[7] == P[7]\n True\n sage: P[7] * PA.one() == P[7]\n True\n\n We now give some further examples of the use of the other arguments.\n One may wish to "specialize" the parameter to a chosen element of\n the base ring::\n\n sage: R.<q> = RR[]\n sage: PA = PartitionAlgebra(2, q, R, prefix=\'B\')\n sage: PA\n Partition Algebra of rank 2 with parameter q over\n Univariate Polynomial Ring in q over Real Field with 53 bits of precision\n sage: PA([[1,2],[-1,-2]])\n 1.00000000000000*B{{-2, -1}, {1, 2}}\n sage: PA = PartitionAlgebra(2, 5, base_ring=ZZ, prefix=\'B\')\n sage: PA\n Partition Algebra of rank 2 with parameter 5 over Integer Ring\n sage: ((PA([[2, -2], [1, -1]]) - 2*PA([[-2, -1], [1, 2]]))^2\n ....: == 16*PA([[-2, -1], [1, 2]]) + PA([[2, -2], [1, -1]]))\n True\n\n Symmetric group algebra elements and elements from other subalgebras\n of the partition algebra (e.g., ``BrauerAlgebra`` and\n ``TemperleyLiebAlgebra``) can also be coerced into the partition algebra::\n\n sage: # needs sage.symbolic\n sage: S = SymmetricGroupAlgebra(SR, 2)\n sage: B = BrauerAlgebra(2, x, SR)\n sage: A = PartitionAlgebra(2, x, SR)\n sage: S([2,1]) * A([[1,-1],[2,-2]])\n P{{-2, 1}, {-1, 2}}\n sage: B([[-1,-2],[2,1]]) * A([[1],[-1],[2,-2]])\n P{{-2}, {-1}, {1, 2}}\n sage: A([[1],[-1],[2,-2]]) * B([[-1,-2],[2,1]])\n P{{-2, -1}, {1}, {2}}\n\n The same is true if the elements come from a subalgebra of a partition\n algebra of smaller order, or if they are defined over a different\n base ring::\n\n sage: R = FractionField(ZZ[\'q\']); q = R.gen()\n sage: S = SymmetricGroupAlgebra(ZZ, 2)\n sage: B = BrauerAlgebra(2, q, ZZ[q])\n sage: A = PartitionAlgebra(3, q, R)\n sage: S([2,1]) * A([[1,-1],[2,-3],[3,-2]])\n P{{-3, 1}, {-2, 3}, {-1, 2}}\n sage: A(B([[-1,-2],[2,1]]))\n P{{-3, 3}, {-2, -1}, {1, 2}}\n\n TESTS:\n\n A computation that returned an incorrect result until :trac:`15958`::\n\n sage: A = PartitionAlgebra(1,17)\n sage: g = SetPartitionsAk(1).list()\n sage: a = A[g[1]]\n sage: a\n P{{-1}, {1}}\n sage: a*a\n 17*P{{-1}, {1}}\n\n Shorthands for working with basis elements are as follows::\n\n sage: # needs sage.symbolic\n sage: S = SymmetricGroupAlgebra(ZZ, 3)\n sage: A = PartitionAlgebra(3, x, SR)\n sage: A([[1,3],[-1],[-3]]) # pair up the omitted nodes as `{-i, i}`, if possible\n P{{-3}, {-2, 2}, {-1}, {1, 3}}\n sage: A([[1,3],[-1],[-3]]) == A[[1,3],[-1],[-3]]\n True\n sage: A([[1,2]])\n P{{-3, 3}, {-2}, {-1}, {1, 2}}\n sage: A([[1,2]]) == A[[1,2]]\n True\n sage: A([2,3,1]) # permutations in one-line notation are imported as well\n P{{-3, 2}, {-2, 1}, {-1, 3}}\n sage: A([2,3,1]) == A(S([2,3,1]))\n True\n '
@staticmethod
def __classcall_private__(cls, k, q, base_ring=None, prefix='P'):
"\n Standardize the input by getting the base ring from the parent of\n the parameter ``q`` if no ``base_ring`` is given.\n\n TESTS::\n\n sage: R.<q> = QQ[]\n sage: PA1 = PartitionAlgebra(2, q)\n sage: PA2 = PartitionAlgebra(2, q, R, 'P')\n sage: PA1 is PA2\n True\n "
if (base_ring is None):
base_ring = q.parent()
return super().__classcall__(cls, k, q, base_ring, prefix)
def __init__(self, k, q, base_ring, prefix):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: R.<q> = QQ[]\n sage: PA = PartitionAlgebra(2, q, R)\n sage: TestSuite(PA).run()\n '
self._k = k
self._prefix = prefix
self._q = base_ring(q)
DiagramAlgebra.__init__(self, k, q, base_ring, prefix, PartitionDiagrams(k))
def _element_constructor_(self, x):
"\n Construct an element of ``self``.\n\n TESTS::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: R.<x> = QQ[]\n sage: PA = PartitionAlgebra(2, x, R, 'P')\n sage: PA([]) == PA.one()\n True\n sage: D = da.DiagramAlgebra(2, x, R, 'P', da.PartitionDiagrams(2))\n sage: D([]) == D.one()\n Traceback (most recent call last):\n ...\n ValueError: invalid input of []\n sage: sp = da.to_set_partition( [[1,2], [-1,-2]] )\n sage: b_elt = D(sp); b_elt\n P{{-2, -1}, {1, 2}}\n sage: b_elt in D\n True\n sage: D([[1,2],[-1,-2]]) == b_elt\n True\n sage: D([{1,2},{-1,-2}]) == b_elt\n True\n sage: S = SymmetricGroupAlgebra(R,2)\n sage: D(S([2,1]))\n P{{-2, 1}, {-1, 2}}\n sage: D2 = da.DiagramAlgebra(2, x, R, 'P', da.PlanarDiagrams(2))\n sage: D2(S([1,2]))\n P{{-2, 2}, {-1, 1}}\n sage: D2(S([2,1]))\n Traceback (most recent call last):\n ...\n ValueError: the diagram {{-2, 1}, {-1, 2}} must be planar\n "
if self.basis().keys().is_parent_of(x):
return self.basis()[x]
if isinstance(x, (AbstractPartitionDiagram, list, tuple, Permutations.Element)):
return self._diag_to_Blst(x)
if (isinstance(x, OrbitBasis.Element) and self.base_ring().has_coerce_map_from(x.parent().base_ring())):
return self(x.parent().to_diagram_basis(x))
if (isinstance(x, (PartitionAlgebra.Element, SubPartitionAlgebra.Element)) and self.has_coerce_map_from(x.parent().base_ring())):
return sum(((a * self._diag_to_Blst(d)) for (d, a) in x))
return super()._element_constructor_(x)
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: R.<q> = QQ[]\n sage: PartitionAlgebra(2, q, R)\n Partition Algebra of rank 2 with parameter q\n over Univariate Polynomial Ring in q over Rational Field\n '
return 'Partition Algebra of rank {} with parameter {} over {}'.format(self._k, self._q, self.base_ring())
def _coerce_map_from_(self, R):
'\n Return a coerce map from ``R`` if one exists and ``None`` otherwise.\n\n .. TODO::\n\n - Refactor some of these generic morphisms as compositions\n of morphisms.\n - Allow for coercion if base_rings and parameters are the same,\n up to relabeling/isomorphism?\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: S = SymmetricGroupAlgebra(R, 4)\n sage: A = PartitionAlgebra(4, x, R)\n sage: O = A.orbit_basis()\n sage: A._coerce_map_from_(S)\n Generic morphism:\n From: Symmetric group algebra of order 4 over Univariate Polynomial Ring in x over Rational Field\n To: Partition Algebra of rank 4 with parameter x over Univariate Polynomial Ring in x over Rational Field\n sage: A._coerce_map_from_(O)\n Generic morphism:\n From: Orbit basis of Partition Algebra of rank 4 with parameter x over Univariate Polynomial Ring in x over Rational Field\n To: Partition Algebra of rank 4 with parameter x over Univariate Polynomial Ring in x over Rational Field\n sage: Sp3 = SymmetricGroupAlgebra(ZZ, 3)\n sage: A._coerce_map_from_(Sp3)\n Generic morphism:\n From: Symmetric group algebra of order 3 over Integer Ring\n To: Partition Algebra of rank 4 with parameter x over Univariate Polynomial Ring in x over Rational Field\n sage: B3 = BrauerAlgebra(3, x, R)\n sage: A._coerce_map_from_(B3)\n Generic morphism:\n From: Brauer Algebra of rank 3 with parameter x over Univariate Polynomial Ring in x over Rational Field\n To: Partition Algebra of rank 4 with parameter x over Univariate Polynomial Ring in x over Rational Field\n sage: A3 = PartitionAlgebra(3, x, R)\n sage: A._coerce_map_from_(A3)\n Generic morphism:\n From: Partition Algebra of rank 3 with parameter x over Univariate Polynomial Ring in x over Rational Field\n To: Partition Algebra of rank 4 with parameter x over Univariate Polynomial Ring in x over Rational Field\n sage: O3 = A3.orbit_basis()\n sage: A._coerce_map_from_(O3)\n Generic morphism:\n From: Orbit basis of Partition Algebra of rank 3 with parameter x over Univariate Polynomial Ring in x over Rational Field\n To: Partition Algebra of rank 4 with parameter x over Univariate Polynomial Ring in x over Rational Field\n\n TESTS::\n\n sage: elt = O3.an_element(); elt\n 2*O{{-3, -2, -1, 1, 2, 3}} + 2*O{{-3, -2, 1, 2, 3}, {-1}}\n + 3*O{{-3, -1, 1, 2, 3}, {-2}}\n sage: A._coerce_map_from_(O3)(elt)\n -3*P{{-4, 4}, {-3, -2, -1, 1, 2, 3}}\n + 2*P{{-4, 4}, {-3, -2, 1, 2, 3}, {-1}}\n + 3*P{{-4, 4}, {-3, -1, 1, 2, 3}, {-2}}\n '
if isinstance(R, OrbitBasis):
if ((R._k <= self._k) and self.base_ring().has_coerce_map_from(R.base_ring())):
return R.module_morphism(self._orbit_to_diagram_on_basis, codomain=self)
return None
if isinstance(R, (PartitionAlgebra, SubPartitionAlgebra)):
if ((R._k <= self._k) and self.base_ring().has_coerce_map_from(R.base_ring())):
return R.module_morphism(self._diag_to_Blst, codomain=self)
return None
if isinstance(R, SymmetricGroupAlgebra_n):
if ((R.n <= self._k) and self.base_ring().has_coerce_map_from(R.base_ring())):
return R.module_morphism(self._perm_to_Blst, codomain=self)
return None
return super()._coerce_map_from_(R)
def orbit_basis(self):
'\n Return the orbit basis of ``self``.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: P2 = PartitionAlgebra(2, x, R)\n sage: O2 = P2.orbit_basis(); O2\n Orbit basis of Partition Algebra of rank 2 with parameter x over\n Univariate Polynomial Ring in x over Rational Field\n sage: pp = 7 * P2[{-1}, {-2, 1, 2}] - 2 * P2[{-2}, {-1, 1}, {2}]; pp\n -2*P{{-2}, {-1, 1}, {2}} + 7*P{{-2, 1, 2}, {-1}}\n sage: op = pp.to_orbit_basis(); op\n -2*O{{-2}, {-1, 1}, {2}} - 2*O{{-2}, {-1, 1, 2}}\n - 2*O{{-2, -1, 1}, {2}} + 5*O{{-2, -1, 1, 2}}\n + 7*O{{-2, 1, 2}, {-1}} - 2*O{{-2, 2}, {-1, 1}}\n sage: op == O2(op)\n True\n sage: pp * op.leading_term()\n 4*P{{-2}, {-1, 1}, {2}} - 4*P{{-2, -1, 1}, {2}}\n + 14*P{{-2, -1, 1, 2}} - 14*P{{-2, 1, 2}, {-1}}\n '
return OrbitBasis(self)
def _orbit_to_diagram_on_basis(self, d):
'\n Return the orbit basis element, indexed by the partition\n diagram ``d``, in the diagram basis of the partition algebra.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: P2 = PartitionAlgebra(2, x, R)\n sage: from sage.combinat.diagram_algebras import PartitionDiagrams\n sage: PD = PartitionDiagrams(2)\n sage: P2._orbit_to_diagram_on_basis(PD([[1,2,-2],[-1]]))\n -P{{-2, -1, 1, 2}} + P{{-2, 1, 2}, {-1}}\n '
SPd = SetPartitions(len(d))
return self.sum((((((- 1) ** (len(d) - len(sp))) * prod((ZZ((len(p) - 1)).factorial() for p in sp))) * self([sum((list(d[(i - 1)]) for i in p), []) for p in sp])) for sp in SPd))
@cached_method
def a(self, i):
'\n Return the element `a_i` in ``self``.\n\n The element `a_i` is the cap and cup at `(i, i+1)`, so it contains\n the blocks `\\{i, i+1\\}`, `\\{-i, -i-1\\}`. Other blocks are of the\n form `\\{-j, j\\}`.\n\n INPUT:\n\n - ``i`` -- an integer between 1 and `k-1`\n\n EXAMPLES::\n\n sage: R.<n> = QQ[]\n sage: P3 = PartitionAlgebra(3, n)\n sage: P3.a(1)\n P{{-3, 3}, {-2, -1}, {1, 2}}\n sage: P3.a(2)\n P{{-3, -2}, {-1, 1}, {2, 3}}\n\n sage: P3 = PartitionAlgebra(5/2, n)\n sage: P3.a(1)\n P{{-3, 3}, {-2, -1}, {1, 2}}\n sage: P3.a(2)\n Traceback (most recent call last):\n ...\n ValueError: i must be an integer between 1 and 1\n '
if ((i <= 0) or (i >= floor(self._k))):
raise ValueError('i must be an integer between 1 and {}'.format((floor(self._k) - 1)))
B = self.basis()
SP = B.keys()
D = [[(- j), j] for j in range(1, (ceil(self._k) + 1))]
D[(i - 1)] = [i, (i + 1)]
D[i] = [(- i), (- (i + 1))]
return B[SP(D)]
generator_a = a
@cached_method
def e(self, i):
'\n Return the element `e_i` in ``self``.\n\n If `i = (2r+1)/2`, then `e_i` contains the blocks `\\{r+1\\}` and\n `\\{-r-1\\}`. If `i \\in \\ZZ`, then `e_i` contains the block\n `\\{-i, -i-1, i, i+1\\}`. Other blocks are of the form `\\{-j, j\\}`.\n\n INPUT:\n\n - ``i`` -- a half integer between 1/2 and `k-1/2`\n\n EXAMPLES::\n\n sage: R.<n> = QQ[]\n sage: P3 = PartitionAlgebra(3, n)\n sage: P3.e(1)\n P{{-3, 3}, {-2, -1, 1, 2}}\n sage: P3.e(2)\n P{{-3, -2, 2, 3}, {-1, 1}}\n sage: P3.e(1/2)\n P{{-3, 3}, {-2, 2}, {-1}, {1}}\n sage: P3.e(5/2)\n P{{-3}, {-2, 2}, {-1, 1}, {3}}\n sage: P3.e(0)\n Traceback (most recent call last):\n ...\n ValueError: i must be an (half) integer between 1/2 and 5/2\n sage: P3.e(3)\n Traceback (most recent call last):\n ...\n ValueError: i must be an (half) integer between 1/2 and 5/2\n\n sage: P2h = PartitionAlgebra(5/2,n)\n sage: [P2h.e(k/2) for k in range(1,5)]\n [P{{-3, 3}, {-2, 2}, {-1}, {1}},\n P{{-3, 3}, {-2, -1, 1, 2}},\n P{{-3, 3}, {-2}, {-1, 1}, {2}},\n P{{-3, -2, 2, 3}, {-1, 1}}]\n '
if ((i <= 0) or (i >= self._k)):
raise ValueError('i must be an (half) integer between 1/2 and {}'.format((((2 * self._k) - 1) / 2)))
B = self.basis()
SP = B.keys()
if (i in ZZ):
i -= 1
D = [[(- j), j] for j in range(1, (ceil(self._k) + 1))]
D[i] += D.pop((i + 1))
return B[SP(D)]
else:
i = ceil(i)
D = [[(- j), j] for j in range(1, (ceil(self._k) + 1))]
D[(i - 1)] = [(- i)]
D.append([i])
return B[SP(D)]
generator_e = e
@cached_method
def s(self, i):
'\n Return the ``i``-th simple transposition `s_i` in ``self``.\n\n Borrowing the notation from the symmetric group, the `i`-th\n simple transposition `s_i` has blocks of the form `\\{-i, i+1\\}`,\n `\\{-i-1, i\\}`. Other blocks are of the form `\\{-j, j\\}`.\n\n INPUT:\n\n - ``i`` -- an integer between 1 and `k-1`\n\n EXAMPLES::\n\n sage: R.<n> = QQ[]\n sage: P3 = PartitionAlgebra(3, n)\n sage: P3.s(1)\n P{{-3, 3}, {-2, 1}, {-1, 2}}\n sage: P3.s(2)\n P{{-3, 2}, {-2, 3}, {-1, 1}}\n\n sage: R.<n> = ZZ[]\n sage: P2h = PartitionAlgebra(5/2,n)\n sage: P2h.s(1)\n P{{-3, 3}, {-2, 1}, {-1, 2}}\n '
if ((i not in ZZ) or (i <= 0) or (i >= self._k)):
raise ValueError('i must be an integer between 1 and {}'.format((self._k - 1)))
B = self.basis()
SP = B.keys()
D = [[(- j), j] for j in range(1, (ceil(self._k) + 1))]
D[(i - 1)] = [(- (i + 1)), i]
D[i] = [(- i), (i + 1)]
return B[SP(D)]
generator_s = s
@cached_method
def sigma(self, i):
'\n Return the element `\\sigma_i` from [Eny2012]_ of ``self``.\n\n INPUT:\n\n - ``i`` -- a half integer between 1/2 and `k-1/2`\n\n .. NOTE::\n\n In [Cre2020]_ and [Eny2013]_, these are the elements `\\sigma_{2i}`.\n\n EXAMPLES::\n\n sage: R.<n> = QQ[]\n sage: P3 = PartitionAlgebra(3, n)\n sage: P3.sigma(1)\n P{{-3, 3}, {-2, 2}, {-1, 1}}\n sage: P3.sigma(3/2)\n P{{-3, 3}, {-2, 1}, {-1, 2}}\n sage: P3.sigma(2)\n -P{{-3, -1, 1, 3}, {-2, 2}} + P{{-3, -1, 3}, {-2, 1, 2}}\n + P{{-3, 1, 3}, {-2, -1, 2}} - P{{-3, 3}, {-2, -1, 1, 2}}\n + P{{-3, 3}, {-2, 2}, {-1, 1}}\n sage: P3.sigma(5/2)\n -P{{-3, -1, 1, 2}, {-2, 3}} + P{{-3, -1, 2}, {-2, 1, 3}}\n + P{{-3, 1, 2}, {-2, -1, 3}} - P{{-3, 2}, {-2, -1, 1, 3}}\n + P{{-3, 2}, {-2, 3}, {-1, 1}}\n\n We test the relations in Lemma 2.2.3(1) in [Cre2020]_ (v1)::\n\n sage: k = 4\n sage: R.<x> = QQ[]\n sage: P = PartitionAlgebra(k, x)\n sage: all(P.sigma(i/2).dual() == P.sigma(i/2)\n ....: for i in range(1,2*k))\n True\n sage: all(P.sigma(i)*P.sigma(i+1/2) == P.sigma(i+1/2)*P.sigma(i) == P.s(i)\n ....: for i in range(1,floor(k)))\n True\n sage: all(P.sigma(i)*P.e(i) == P.e(i)*P.sigma(i) == P.e(i)\n ....: for i in range(1,floor(k)))\n True\n sage: all(P.sigma(i+1/2)*P.e(i) == P.e(i)*P.sigma(i+1/2) == P.e(i)\n ....: for i in range(1,floor(k)))\n True\n\n sage: k = 9/2\n sage: R.<x> = QQ[]\n sage: P = PartitionAlgebra(k, x)\n sage: all(P.sigma(i/2).dual() == P.sigma(i/2)\n ....: for i in range(1,2*k-1))\n True\n sage: all(P.sigma(i)*P.sigma(i+1/2) == P.sigma(i+1/2)*P.sigma(i) == P.s(i)\n ....: for i in range(1,k-1/2))\n True\n sage: all(P.sigma(i)*P.e(i) == P.e(i)*P.sigma(i) == P.e(i)\n ....: for i in range(1,floor(k)))\n True\n sage: all(P.sigma(i+1/2)*P.e(i) == P.e(i)*P.sigma(i+1/2) == P.e(i)\n ....: for i in range(1,floor(k)))\n True\n '
if ((i <= 0) or (i >= self._k)):
raise ValueError('i must be an (half) integer between 1 and {}'.format((((2 * self._k) - 1) / 2)))
half = (QQ.one() / 2)
if (i in ZZ):
if (i == 1):
return self.one()
si = self.s(i)
sim = self.s((i - 1))
x = (((self.e((i - 1)) * self.jucys_murphy_element((i - 1))) * si) * self.e((i - 1)))
return ((((((((sim * si) * self.sigma((i - 1))) * si) * sim) + (x * si)) + (si * x)) - (((((self.e((i - 1)) * self.jucys_murphy_element((i - 1))) * sim) * self.e(i)) * self.e((i - half))) * self.e((i - 1)))) - (((((((si * self.e((i - 1))) * self.e((i - half))) * self.e(i)) * sim) * self.jucys_murphy_element((i - 1))) * self.e((i - 1))) * si))
else:
j = (ceil(i) - 1)
if (j == 0):
return self.zero()
if (j == 1):
return self.s(1)
si = self.s(j)
sim = self.s((j - 1))
x = (((self.e((j - 1)) * self.jucys_murphy_element((j - 1))) * si) * self.e((j - 1)))
return ((((((((sim * si) * self.sigma((i - 1))) * si) * sim) + ((si * x) * si)) + x) - ((((((si * self.e((j - 1))) * self.jucys_murphy_element((j - 1))) * sim) * self.e(j)) * self.e((i - 1))) * self.e((j - 1)))) - ((((((self.e((j - 1)) * self.e((i - 1))) * self.e(j)) * sim) * self.jucys_murphy_element((j - 1))) * self.e((j - 1))) * si))
@cached_method
def jucys_murphy_element(self, i):
'\n Return the ``i``-th Jucys-Murphy element `L_i` from [Eny2012]_.\n\n INPUT:\n\n - ``i`` -- a half integer between 1/2 and `k`\n\n ALGORITHM:\n\n We use the recursive definition for `L_{2i}` given in [Cre2020]_.\n See also [Eny2012]_ and [Eny2013]_.\n\n .. NOTE::\n\n `L_{1/2}` and `L_1` differs from [HR2005]_.\n\n EXAMPLES::\n\n sage: R.<n> = QQ[]\n sage: P3 = PartitionAlgebra(3, n)\n sage: P3.jucys_murphy_element(1/2)\n 0\n sage: P3.jucys_murphy_element(1)\n P{{-3, 3}, {-2, 2}, {-1}, {1}}\n sage: P3.jucys_murphy_element(2)\n P{{-3, 3}, {-2}, {-1, 1}, {2}} - P{{-3, 3}, {-2}, {-1, 1, 2}}\n + P{{-3, 3}, {-2, -1}, {1, 2}} - P{{-3, 3}, {-2, -1, 1}, {2}}\n + P{{-3, 3}, {-2, 1}, {-1, 2}}\n sage: P3.jucys_murphy_element(3/2)\n n*P{{-3, 3}, {-2, -1, 1, 2}} - P{{-3, 3}, {-2, -1, 2}, {1}}\n - P{{-3, 3}, {-2, 1, 2}, {-1}} + P{{-3, 3}, {-2, 2}, {-1, 1}}\n sage: P3.L(3/2) * P3.L(2) == P3.L(2) * P3.L(3/2)\n True\n\n We test the relations in Lemma 2.2.3(2) in [Cre2020]_ (v1)::\n\n sage: k = 4\n sage: R.<n> = QQ[]\n sage: P = PartitionAlgebra(k, n)\n sage: L = [P.L(i/2) for i in range(1,2*k+1)]\n sage: all(x.dual() == x for x in L)\n True\n sage: all(x * y == y * x for x in L for y in L) # long time\n True\n sage: Lsum = sum(L)\n sage: gens = [P.s(i) for i in range(1,k)]\n sage: gens += [P.e(i/2) for i in range(1,2*k)]\n sage: all(x * Lsum == Lsum * x for x in gens)\n True\n\n Also the relations in Lemma 2.2.3(3) in [Cre2020]_ (v1)::\n\n sage: all(P.e((2*i+1)/2) * P.sigma(2*i/2) * P.e((2*i+1)/2)\n ....: == (n - P.L((2*i-1)/2)) * P.e((2*i+1)/2) for i in range(1,k))\n True\n sage: all(P.e(i/2) * (P.L(i/2) + P.L((i+1)/2))\n ....: == (P.L(i/2) + P.L((i+1)/2)) * P.e(i/2)\n ....: == n * P.e(i/2) for i in range(1,2*k))\n True\n sage: all(P.sigma(2*i/2) * P.e((2*i-1)/2) * P.e(2*i/2)\n ....: == P.L(2*i/2) * P.e(2*i/2) for i in range(1,k))\n True\n sage: all(P.e(2*i/2) * P.e((2*i-1)/2) * P.sigma(2*i/2)\n ....: == P.e(2*i/2) * P.L(2*i/2) for i in range(1,k))\n True\n sage: all(P.sigma((2*i+1)/2) * P.e((2*i+1)/2) * P.e(2*i/2)\n ....: == P.L(2*i/2) * P.e(2*i/2) for i in range(1,k))\n True\n sage: all(P.e(2*i/2) * P.e((2*i+1)/2) * P.sigma((2*i+1)/2)\n ....: == P.e(2*i/2) * P.L(2*i/2) for i in range(1,k))\n True\n\n The same tests for a half integer partition algebra::\n\n sage: k = 9/2\n sage: R.<n> = QQ[]\n sage: P = PartitionAlgebra(k, n)\n sage: L = [P.L(i/2) for i in range(1,2*k+1)]\n sage: all(x.dual() == x for x in L)\n True\n sage: all(x * y == y * x for x in L for y in L) # long time\n True\n sage: Lsum = sum(L)\n sage: gens = [P.s(i) for i in range(1,k-1/2)]\n sage: gens += [P.e(i/2) for i in range(1,2*k)]\n sage: all(x * Lsum == Lsum * x for x in gens)\n True\n sage: all(P.e((2*i+1)/2) * P.sigma(2*i/2) * P.e((2*i+1)/2)\n ....: == (n - P.L((2*i-1)/2)) * P.e((2*i+1)/2) for i in range(1,floor(k)))\n True\n sage: all(P.e(i/2) * (P.L(i/2) + P.L((i+1)/2))\n ....: == (P.L(i/2) + P.L((i+1)/2)) * P.e(i/2)\n ....: == n * P.e(i/2) for i in range(1,2*k))\n True\n sage: all(P.sigma(2*i/2) * P.e((2*i-1)/2) * P.e(2*i/2)\n ....: == P.L(2*i/2) * P.e(2*i/2) for i in range(1,ceil(k)))\n True\n sage: all(P.e(2*i/2) * P.e((2*i-1)/2) * P.sigma(2*i/2)\n ....: == P.e(2*i/2) * P.L(2*i/2) for i in range(1,ceil(k)))\n True\n sage: all(P.sigma((2*i+1)/2) * P.e((2*i+1)/2) * P.e(2*i/2)\n ....: == P.L(2*i/2) * P.e(2*i/2) for i in range(1,floor(k)))\n True\n sage: all(P.e(2*i/2) * P.e((2*i+1)/2) * P.sigma((2*i+1)/2)\n ....: == P.e(2*i/2) * P.L(2*i/2) for i in range(1,floor(k)))\n True\n '
if ((i <= 0) or (i > self._k)):
raise ValueError('i must be an (half) integer between 1/2 and {}'.format(self._k))
half = (QQ.one() / 2)
if (i in ZZ):
if (i == 1):
return self.e(half)
i -= 1
L = self.jucys_murphy_element
return ((((self.s(i) * L(i)) * (self.s(i) - self.e(i))) - ((self.e(i) * L(i)) * (self.s(i) - (self.e((i + half)) * self.e(i))))) + self.sigma((i + half)))
else:
j = (ceil(i) - 1)
if (j == 0):
return self.zero()
L = self.jucys_murphy_element
return (((((self.s(j) * L((i - 1))) * self.s(j)) - (self.e(j) * L(j))) + ((((self._q * self.one()) - L((i - 1))) - L(j)) * self.e(j))) + self.sigma(j))
L = jucys_murphy_element
class Element(DiagramBasis.Element):
def to_orbit_basis(self):
'\n Return ``self`` in the orbit basis of the associated\n partition algebra.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: P = PartitionAlgebra(2, x, R)\n sage: pp = P.an_element();\n sage: pp.to_orbit_basis()\n 3*O{{-2}, {-1, 1, 2}} + 7*O{{-2, -1, 1, 2}} + 2*O{{-2, 1, 2}, {-1}}\n sage: pp = (3*P([[-2], [-1, 1, 2]]) + 2*P([[-2, -1, 1, 2]])\n ....: + 2*P([[-2, 1, 2], [-1]])); pp\n 3*P{{-2}, {-1, 1, 2}} + 2*P{{-2, -1, 1, 2}} + 2*P{{-2, 1, 2}, {-1}}\n sage: pp.to_orbit_basis()\n 3*O{{-2}, {-1, 1, 2}} + 7*O{{-2, -1, 1, 2}} + 2*O{{-2, 1, 2}, {-1}}\n '
OP = self.parent().orbit_basis()
return OP(self)
def dual(self):
'\n Return the dual of ``self``.\n\n The dual of an element in the partition algebra is formed\n by taking the dual of each diagram in the support.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: P = PartitionAlgebra(2, x, R)\n sage: elt = P.an_element(); elt\n 3*P{{-2}, {-1, 1, 2}} + 2*P{{-2, -1, 1, 2}} + 2*P{{-2, 1, 2}, {-1}}\n sage: elt.dual()\n 3*P{{-2, -1, 1}, {2}} + 2*P{{-2, -1, 1, 2}} + 2*P{{-2, -1, 2}, {1}}\n '
P = self.parent()
return P._from_dict({D.dual(): c for (D, c) in self._monomial_coefficients.items()}, remove_zeros=False)
|
class OrbitBasis(DiagramAlgebra):
'\n The orbit basis of the partition algebra.\n\n Let `D_\\pi` represent the diagram basis element indexed by the\n partition `\\pi`, then (see equations (2.14), (2.17) and (2.18) of [BH2017]_)\n\n .. MATH::\n\n D_\\pi = \\sum_{\\tau \\geq \\pi} O_\\tau,\n\n where the sum is over all partitions `\\tau` which are coarser than `\\pi`\n and `O_\\tau` is the orbit basis element indexed by the partition `\\tau`.\n\n If `\\mu_{2k}(\\pi,\\tau)` represents the Moebius function of the partition\n lattice, then\n\n .. MATH::\n\n O_\\pi = \\sum_{\\tau \\geq \\pi} \\mu_{2k}(\\pi, \\tau) D_\\tau.\n\n If `\\tau` is a partition of `\\ell` blocks and the `i^{th}` block of\n `\\tau` is a union of `b_i` blocks of `\\pi`, then\n\n .. MATH::\n\n \\mu_{2k}(\\pi, \\tau) = \\prod_{i=1}^\\ell (-1)^{b_i-1} (b_i-1)! .\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: P2 = PartitionAlgebra(2, x, R)\n sage: O2 = P2.orbit_basis(); O2\n Orbit basis of Partition Algebra of rank 2 with parameter x over\n Univariate Polynomial Ring in x over Rational Field\n sage: oa = O2([[1],[-1],[2,-2]]); ob = O2([[-1,-2,2],[1]]); oa, ob\n (O{{-2, 2}, {-1}, {1}}, O{{-2, -1, 2}, {1}})\n sage: oa * ob\n (x-2)*O{{-2, -1, 2}, {1}}\n\n We can convert between the two bases::\n\n sage: pa = P2(oa); pa\n 2*P{{-2, -1, 1, 2}} - P{{-2, -1, 2}, {1}} - P{{-2, 1, 2}, {-1}}\n + P{{-2, 2}, {-1}, {1}} - P{{-2, 2}, {-1, 1}}\n sage: pa * ob\n (-x+2)*P{{-2, -1, 1, 2}} + (x-2)*P{{-2, -1, 2}, {1}}\n sage: _ == pa * P2(ob)\n True\n sage: O2(pa * ob)\n (x-2)*O{{-2, -1, 2}, {1}}\n\n Note that the unit in the orbit basis is not a single diagram,\n in contrast to the natural diagram basis::\n\n sage: P2.one()\n P{{-2, 2}, {-1, 1}}\n sage: O2.one()\n O{{-2, -1, 1, 2}} + O{{-2, 2}, {-1, 1}}\n sage: O2.one() == P2.one()\n True\n\n TESTS:\n\n Check that going between the two bases is the identity::\n\n sage: R.<x> = QQ[]\n sage: P2 = PartitionAlgebra(2, x, R)\n sage: O2 = P2.orbit_basis(); O2\n Orbit basis of Partition Algebra of rank 2 with parameter x over\n Univariate Polynomial Ring in x over Rational Field\n sage: PD = P2.basis().keys()\n sage: all(O2(P2(O2(m))) == O2(m) for m in PD)\n True\n sage: all(P2(O2(P2(m))) == P2(m) for m in PD)\n True\n '
@staticmethod
def __classcall_private__(cls, *args):
'\n Normalize input to ensure a unique representation.\n\n INPUT:\n\n Either:\n\n - ``A`` -- an abstract diagram algebra\n\n or the arguments to construct a diagram algebra:\n\n - ``k`` -- the rank\n - ``q`` -- the parameter\n - ``R`` -- the base ring\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: P2 = PartitionAlgebra(2, x, R)\n sage: from sage.combinat.diagram_algebras import OrbitBasis\n sage: O2a = P2.orbit_basis()\n sage: O2b = OrbitBasis(P2)\n sage: O2c = OrbitBasis(2, x, R)\n sage: O2a is O2b and O2a is O2c\n True\n sage: O2d = OrbitBasis(2, x, QQ[x])\n sage: O2a is O2d\n True\n '
if (len(args) == 1):
PA = args[0]
if (not isinstance(PA, DiagramAlgebra)):
raise ValueError('{} is not a partition algebra'.format(PA))
alg = PA
elif (len(args) != 3):
raise ValueError(('expected 1 or 3 arguments, received %s: %s' % (len(args), args)))
else:
(k, q, R) = args
q = R(q)
alg = PartitionAlgebra(k, q, R)
return super().__classcall__(cls, alg)
def __init__(self, alg):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: O2 = PartitionAlgebra(2, -1, QQ).orbit_basis()\n sage: TestSuite(O2).run()\n '
base_ring = alg.base_ring()
k = alg._k
q = alg._q
diagrams = alg._base_diagrams
category = alg.category()
DiagramAlgebra.__init__(self, k, q, base_ring, 'O', diagrams, category)
self._fill = True
self._alg = alg
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PartitionAlgebra(2, -1, QQ).orbit_basis()\n Orbit basis of Partition Algebra of rank 2 with parameter -1 over Rational Field\n '
return 'Orbit basis of {}'.format(self._alg)
def _element_constructor_(self, x):
'\n Convert ``x`` into ``self``.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: P2 = PartitionAlgebra(2, x, R)\n sage: O2 = P2.orbit_basis()\n sage: O2(P2([]))\n O{{-2, -1, 1, 2}} + O{{-2, 2}, {-1, 1}}\n sage: O2(3).to_diagram_basis() == 3 * P2.one()\n True\n sage: O2(P2([[1,2,-2],[-1]]))\n O{{-2, -1, 1, 2}} + O{{-2, 1, 2}, {-1}}\n '
if isinstance(x, (PartitionAlgebra.Element, SubPartitionAlgebra.Element)):
return self._alg(x).to_orbit_basis()
d = self._alg._diag_to_Blst(x).diagram()
return CombinatorialFreeModule._element_constructor_(self, d)
def _coerce_map_from_(self, R):
'\n Return a coerce map from ``R`` if one exists and ``None`` otherwise.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: P2 = PartitionAlgebra(2, x, R)\n sage: O2 = P2.orbit_basis()\n sage: O2(P2([]))\n O{{-2, -1, 1, 2}} + O{{-2, 2}, {-1, 1}}\n sage: O2(3)\n 3*O{{-2, -1, 1, 2}} + 3*O{{-2, 2}, {-1, 1}}\n sage: O2([[1,2,-2],[-1]])\n O{{-2, 1, 2}, {-1}}\n '
if (R is self._alg):
return self._alg.module_morphism(self._diagram_to_orbit_on_basis, codomain=self)
if self._alg.coerce_map_from(R):
return self._coerce_map_via([self._alg], R)
return super()._coerce_map_from_(R)
@cached_method
def one(self):
'\n Return the element `1` of the partition algebra in the orbit basis.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: P2 = PartitionAlgebra(2, x, R)\n sage: O2 = P2.orbit_basis()\n sage: O2.one()\n O{{-2, -1, 1, 2}} + O{{-2, 2}, {-1, 1}}\n '
PDs = self._base_diagrams
base = SetPartitions()(identity_set_partition(self._k))
brone = self.base_ring().one()
return self._from_dict({PDs(d): brone for d in base.coarsenings()}, coerce=False, remove_zeros=False)
def diagram_basis(self):
'\n Return the associated partition algebra of ``self``\n in the diagram basis.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: O2 = PartitionAlgebra(2, x, R).orbit_basis()\n sage: P2 = O2.diagram_basis(); P2\n Partition Algebra of rank 2 with parameter x over Univariate\n Polynomial Ring in x over Rational Field\n sage: o2 = O2.an_element(); o2\n 3*O{{-2}, {-1, 1, 2}} + 2*O{{-2, -1, 1, 2}} + 2*O{{-2, 1, 2}, {-1}}\n sage: P2(o2)\n 3*P{{-2}, {-1, 1, 2}} - 3*P{{-2, -1, 1, 2}} + 2*P{{-2, 1, 2}, {-1}}\n\n TESTS::\n\n sage: R.<x> = QQ[]\n sage: P2 = PartitionAlgebra(2, x, R)\n sage: O2 = P2.orbit_basis()\n sage: op = O2([]); op\n O{{-2, 2}, {-1, 1}}\n sage: PA = O2.diagram_basis()\n sage: P2 == PA\n True\n sage: PA([]) == P2.one()\n True\n sage: PA(op)\n -P{{-2, -1, 1, 2}} + P{{-2, 2}, {-1, 1}}\n sage: op == PA(op).to_orbit_basis()\n True\n '
return self._alg
def _diagram_to_orbit_on_basis(self, diag):
'\n Return the element ``diag`` in the orbit basis.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: P2 = PartitionAlgebra(2, x, R)\n sage: O2 = P2.orbit_basis()\n sage: from sage.combinat.diagram_algebras import PartitionDiagrams\n sage: PD = PartitionDiagrams(2)\n sage: O2._diagram_to_orbit_on_basis(PD([[1,2,-2],[-1]]))\n O{{-2, -1, 1, 2}} + O{{-2, 1, 2}, {-1}}\n sage: P2.one().to_orbit_basis()\n O{{-2, -1, 1, 2}} + O{{-2, 2}, {-1, 1}}\n sage: pp = P2[{-2}, {-1, 1}, {2}]\n sage: O2(pp)\n O{{-2}, {-1, 1}, {2}} + O{{-2}, {-1, 1, 2}} + O{{-2, -1, 1}, {2}}\n + O{{-2, -1, 1, 2}} + O{{-2, 2}, {-1, 1}}\n\n TESTS::\n\n sage: P2([]).to_orbit_basis() == O2.one()\n True\n sage: O2([]) == O2.one()\n False\n sage: op = O2.an_element()\n sage: op == op.to_diagram_basis().to_orbit_basis()\n True\n '
PDs = PartitionDiagrams(self._alg._k)
one = self.base_ring().one()
return self._from_dict({PDs(d): one for d in diag.set_partition().coarsenings()}, coerce=False, remove_zeros=False)
def product_on_basis(self, d1, d2):
'\n Return the product `O_{d_1} O_{d_2}` of two elements\n in the orbit basis ``self``.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: OP = PartitionAlgebra(2, x, R).orbit_basis()\n sage: SP = OP.basis().keys(); sp = SP([[-2, -1, 1, 2]])\n sage: OP.product_on_basis(sp, sp)\n O{{-2, -1, 1, 2}}\n sage: o1 = OP.one(); o2 = OP([]); o3 = OP.an_element()\n sage: o2 == o1\n False\n sage: o1 * o1 == o1\n True\n sage: o3 * o1 == o1 * o3 and o3 * o1 == o3\n True\n sage: o4 = (3*OP([[-2, -1, 1], [2]]) + 2*OP([[-2, -1, 1, 2]])\n ....: + 2*OP([[-2, -1, 2], [1]]))\n sage: o4 * o4\n 6*O{{-2, -1, 1}, {2}} + 4*O{{-2, -1, 1, 2}} + 4*O{{-2, -1, 2}, {1}}\n\n We compute Examples 4.5 in [BH2017]_::\n\n sage: R.<x> = QQ[]\n sage: P = PartitionAlgebra(3,x); O = P.orbit_basis()\n sage: O[[1,2,3],[-1,-2,-3]] * O[[1,2,3],[-1,-2,-3]]\n (x-2)*O{{-3, -2, -1}, {1, 2, 3}} + (x-1)*O{{-3, -2, -1, 1, 2, 3}}\n\n sage: P = PartitionAlgebra(4,x); O = P.orbit_basis()\n sage: O[[1],[-1],[2,3],[4,-2],[-3,-4]] * O[[1],[2,-2],[3,4],[-1,-3],[-4]]\n (x^2-11*x+30)*O{{-4}, {-3, -1}, {-2, 4}, {1}, {2, 3}}\n + (x^2-9*x+20)*O{{-4}, {-3, -1, 1}, {-2, 4}, {2, 3}}\n + (x^2-9*x+20)*O{{-4}, {-3, -1, 2, 3}, {-2, 4}, {1}}\n + (x^2-9*x+20)*O{{-4, 1}, {-3, -1}, {-2, 4}, {2, 3}}\n + (x^2-7*x+12)*O{{-4, 1}, {-3, -1, 2, 3}, {-2, 4}}\n + (x^2-9*x+20)*O{{-4, 2, 3}, {-3, -1}, {-2, 4}, {1}}\n + (x^2-7*x+12)*O{{-4, 2, 3}, {-3, -1, 1}, {-2, 4}}\n\n sage: O[[1,-1],[2,-2],[3],[4,-3],[-4]] * O[[1,-2],[2],[3,-1],[4],[-3],[-4]]\n (x-6)*O{{-4}, {-3}, {-2, 1}, {-1, 4}, {2}, {3}}\n + (x-5)*O{{-4}, {-3, 3}, {-2, 1}, {-1, 4}, {2}}\n + (x-5)*O{{-4, 3}, {-3}, {-2, 1}, {-1, 4}, {2}}\n\n sage: P = PartitionAlgebra(6,x); O = P.orbit_basis()\n sage: (O[[1,-2,-3],[2,4],[3,5,-6],[6],[-1],[-4,-5]]\n ....: * O[[1,-2],[2,3],[4],[5],[6,-4,-5,-6],[-1,-3]])\n 0\n\n sage: (O[[1,-2],[2,-3],[3,5],[4,-5],[6,-4],[-1],[-6]]\n ....: * O[[1,-2],[2,-1],[3,-4],[4,-6],[5,-3],[6,-5]])\n O{{-6, 6}, {-5}, {-4, 2}, {-3, 4}, {-2}, {-1, 1}, {3, 5}}\n\n TESTS:\n\n Check that multiplication agrees with the multiplication in the\n partition algebra::\n\n sage: R.<x> = QQ[]\n sage: OP = PartitionAlgebra(2, x).orbit_basis()\n sage: P = OP.diagram_basis()\n sage: o1 = OP.one(); o2 = OP([]); o3 = OP.an_element()\n sage: p1 = P(o1); p2 = P(o2); p3 = P(o3)\n sage: (p2 * p3).to_orbit_basis() == o2 * o3\n True\n sage: (3*p3 * (p1 - 2*p2)).to_orbit_basis() == 3*o3 * (o1 - 2*o2)\n True\n\n sage: R.<x> = QQ[]\n sage: P = PartitionAlgebra(2,x); O = P.orbit_basis()\n sage: all(b * bp == OP(P(b) * P(bp)) for b in OP.basis() # long time\n ....: for bp in OP.basis())\n True\n\n REFERENCES:\n\n - [BH2017]_\n '
pi_1 = [frozenset([(- i) for i in part if (i < 0)]) for part in d1]
pi_2 = [frozenset([i for i in part if (i > 0)]) for part in d2]
if (set([part for part in pi_1 if part]) != set([part for part in pi_2 if part])):
return self.zero()
q = self._q
R = q.parent()
PDs = self._base_diagrams
def matchings(A, B):
for i in range((min(len(A), len(B)) + 1)):
for X in itertools.combinations(A, i):
restA = list(A.difference(X))
for Y in itertools.combinations(B, i):
restB = list(B.difference(Y))
for sigma in Permutations(Y):
(yield (([x.union(y) for (x, y) in zip(X, sigma)] + restA) + restB))
(D, removed) = d1.compose(d2, check=False)
only_top = set([frozenset(part) for part in d1 if all(((i > 0) for i in part))])
only_bottom = set([frozenset(part) for part in d2 if all(((i < 0) for i in part))])
only_both = only_top.union(only_bottom)
restD = [P for P in D if (frozenset(P) not in only_both)]
term_dict = {PDs((restD + X)): R.prod(((q - t) for t in range((len(X) + len(restD)), ((len(X) + len(restD)) + removed)))) for X in matchings(only_top, only_bottom)}
return self._from_dict(term_dict)
class Element(PartitionAlgebra.Element):
def to_diagram_basis(self):
'\n Expand ``self`` in the natural diagram basis of the\n partition algebra.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: P = PartitionAlgebra(2, x, R)\n sage: O = P.orbit_basis()\n sage: elt = O.an_element(); elt\n 3*O{{-2}, {-1, 1, 2}} + 2*O{{-2, -1, 1, 2}} + 2*O{{-2, 1, 2}, {-1}}\n sage: elt.to_diagram_basis()\n 3*P{{-2}, {-1, 1, 2}} - 3*P{{-2, -1, 1, 2}} + 2*P{{-2, 1, 2}, {-1}}\n sage: pp = P.an_element(); pp\n 3*P{{-2}, {-1, 1, 2}} + 2*P{{-2, -1, 1, 2}} + 2*P{{-2, 1, 2}, {-1}}\n sage: op = pp.to_orbit_basis(); op\n 3*O{{-2}, {-1, 1, 2}} + 7*O{{-2, -1, 1, 2}} + 2*O{{-2, 1, 2}, {-1}}\n sage: pp == op.to_diagram_basis()\n True\n '
return self.parent()._alg(self)
|
class SubPartitionAlgebra(DiagramBasis):
'\n A subalgebra of the partition algebra in the diagram basis indexed\n by a subset of the diagrams.\n '
def __init__(self, k, q, base_ring, prefix, diagrams, category=None):
'\n Initialize ``self`` by adding a coercion to the ambient space.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: BA = BrauerAlgebra(2, x, R)\n sage: BA.ambient().has_coerce_map_from(BA)\n True\n '
DiagramBasis.__init__(self, k, q, base_ring, prefix, diagrams, category)
def ambient(self):
"\n Return the partition algebra ``self`` is a sub-algebra of.\n\n EXAMPLES::\n\n sage: x = var('x') # needs sage.symbolic\n sage: BA = BrauerAlgebra(2, x) # needs sage.symbolic\n sage: BA.ambient() # needs sage.symbolic\n Partition Algebra of rank 2 with parameter x over Symbolic Ring\n "
return self.lift.codomain()
@lazy_attribute
def lift(self):
'\n Return the lift map from diagram subalgebra to the ambient space.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: BA = BrauerAlgebra(2, x, R)\n sage: E = BA([[1,2],[-1,-2]])\n sage: lifted = BA.lift(E); lifted\n B{{-2, -1}, {1, 2}}\n sage: lifted.parent() is BA.ambient()\n True\n '
amb = PartitionAlgebra(self._k, self._q, self.base_ring(), prefix=self._prefix)
phi = self.module_morphism(amb.monomial, codomain=amb, category=self.category())
phi.register_as_coercion()
return phi
def retract(self, x):
'\n Retract an appropriate partition algebra element to the\n corresponding element in the partition subalgebra.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: BA = BrauerAlgebra(2, x, R)\n sage: PA = BA.ambient()\n sage: E = PA([[1,2], [-1,-2]])\n sage: BA.retract(E) in BA\n True\n '
if ((x not in self.ambient()) or any(((i not in self._indices) for i in x.support()))):
raise ValueError('{0} cannot retract to {1}'.format(x, self))
return self._from_dict(x._monomial_coefficients, remove_zeros=False)
class Element(DiagramBasis.Element):
def to_orbit_basis(self):
'\n Return ``self`` in the orbit basis of the associated\n ambient partition algebra.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: B = BrauerAlgebra(2, x, R)\n sage: bb = B([[-2, -1], [1, 2]]); bb\n B{{-2, -1}, {1, 2}}\n sage: bb.to_orbit_basis()\n O{{-2, -1}, {1, 2}} + O{{-2, -1, 1, 2}}\n '
P = self.parent().lift.codomain()
OP = P.orbit_basis()
return OP(P(self))
|
class BrauerAlgebra(SubPartitionAlgebra, UnitDiagramMixin):
'\n A Brauer algebra.\n\n The Brauer algebra of rank `k` is an algebra with basis indexed by the\n collection of set partitions of `\\{1, \\ldots, k, -1, \\ldots, -k\\}`\n with block size 2.\n\n This algebra is a subalgebra of the partition algebra.\n For more information, see :class:`PartitionAlgebra`.\n\n INPUT:\n\n - ``k`` -- rank of the algebra\n\n - ``q`` -- the deformation parameter `q`\n\n OPTIONAL ARGUMENTS:\n\n - ``base_ring`` -- (default ``None``) a ring containing ``q``; if ``None``\n then just takes the parent of ``q``\n\n - ``prefix`` -- (default ``"B"``) a label for the basis elements\n\n EXAMPLES:\n\n We now define the Brauer algebra of rank `2` with parameter ``x``\n over `\\ZZ`::\n\n sage: R.<x> = ZZ[]\n sage: B = BrauerAlgebra(2, x, R)\n sage: B\n Brauer Algebra of rank 2 with parameter x\n over Univariate Polynomial Ring in x over Integer Ring\n sage: B.basis()\n Lazy family (Term map from Brauer diagrams of order 2 to Brauer Algebra\n of rank 2 with parameter x over Univariate Polynomial Ring in x\n over Integer Ring(i))_{i in Brauer diagrams of order 2}\n sage: B.basis().keys()\n Brauer diagrams of order 2\n sage: B.basis().keys()([[-2, 1], [2, -1]])\n {{-2, 1}, {-1, 2}}\n sage: b = B.basis().list(); b\n [B{{-2, -1}, {1, 2}}, B{{-2, 1}, {-1, 2}}, B{{-2, 2}, {-1, 1}}]\n sage: b[0]\n B{{-2, -1}, {1, 2}}\n sage: b[0]^2\n x*B{{-2, -1}, {1, 2}}\n sage: b[0]^5\n x^4*B{{-2, -1}, {1, 2}}\n\n Note, also that since the symmetric group algebra is contained in\n the Brauer algebra, there is also a conversion between the two. ::\n\n sage: R.<x> = ZZ[]\n sage: B = BrauerAlgebra(2, x, R)\n sage: S = SymmetricGroupAlgebra(R, 2)\n sage: S([2,1])*B([[1,-1],[2,-2]])\n B{{-2, 1}, {-1, 2}}\n '
@staticmethod
def __classcall_private__(cls, k, q, base_ring=None, prefix='B'):
"\n Standardize the input by getting the base ring from the parent of\n the parameter ``q`` if no ``base_ring`` is given.\n\n TESTS::\n\n sage: R.<q> = QQ[]\n sage: BA1 = BrauerAlgebra(2, q)\n sage: BA2 = BrauerAlgebra(2, q, R, 'B')\n sage: BA1 is BA2\n True\n "
if (base_ring is None):
base_ring = q.parent()
return super().__classcall__(cls, k, q, base_ring, prefix)
def __init__(self, k, q, base_ring, prefix):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: R.<q> = QQ[]\n sage: BA = BrauerAlgebra(2, q, R)\n sage: TestSuite(BA).run()\n '
SubPartitionAlgebra.__init__(self, k, q, base_ring, prefix, BrauerDiagrams(k))
options = BrauerDiagram.options
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: R.<q> = QQ[]\n sage: BrauerAlgebra(2, q, R)\n Brauer Algebra of rank 2 with parameter q\n over Univariate Polynomial Ring in q over Rational Field\n '
return 'Brauer Algebra of rank {} with parameter {} over {}'.format(self._k, self._q, self.base_ring())
def _coerce_map_from_(self, R):
'\n Return a coerce map from ``R`` if one exists and ``None`` otherwise.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: S = SymmetricGroupAlgebra(R, 4)\n sage: A = BrauerAlgebra(4, x, R)\n sage: A._coerce_map_from_(S)\n Generic morphism:\n From: Symmetric group algebra of order 4 over Univariate Polynomial Ring in x over Rational Field\n To: Brauer Algebra of rank 4 with parameter x over Univariate Polynomial Ring in x over Rational Field\n sage: Sp = SymmetricGroupAlgebra(QQ, 4)\n sage: A._coerce_map_from_(Sp)\n Generic morphism:\n From: Symmetric group algebra of order 4 over Rational Field\n To: Brauer Algebra of rank 4 with parameter x over Univariate Polynomial Ring in x over Rational Field\n sage: Sp3 = SymmetricGroupAlgebra(QQ, 3)\n sage: A._coerce_map_from_(Sp3)\n Generic morphism:\n From: Symmetric group algebra of order 3 over Rational Field\n To: Brauer Algebra of rank 4 with parameter x over Univariate Polynomial Ring in x over Rational Field\n '
if isinstance(R, SymmetricGroupAlgebra_n):
if ((R.n <= self._k) and self.base_ring().has_coerce_map_from(R.base_ring())):
return R.module_morphism(self._perm_to_Blst, codomain=self)
return None
return super()._coerce_map_from_(R)
def _element_constructor_(self, set_partition):
'\n Construct an element of ``self``.\n\n EXAMPLES::\n\n sage: R.<q> = QQ[]\n sage: BA = BrauerAlgebra(2, q, R)\n sage: sp = SetPartition([[1,2], [-1,-2]])\n sage: b_elt = BA(sp); b_elt\n B{{-2, -1}, {1, 2}}\n sage: b_elt in BA\n True\n sage: BA([[1,2],[-1,-2]]) == b_elt\n True\n sage: BA([{1,2},{-1,-2}]) == b_elt\n True\n '
set_partition = to_Brauer_partition(set_partition, k=self.order())
return DiagramAlgebra._element_constructor_(self, set_partition)
def jucys_murphy(self, j):
"\n Return the ``j``-th generalized Jucys-Murphy element of ``self``.\n\n The `j`-th Jucys-Murphy element of a Brauer algebra is simply\n the `j`-th Jucys-Murphy element of the symmetric group algebra\n with an extra `(z-1)/2` term, where ``z`` is the parameter\n of the Brauer algebra.\n\n REFERENCES:\n\n .. [Naz96] Maxim Nazarov, Young's Orthogonal Form for Brauer's\n Centralizer Algebra. Journal of Algebra 182 (1996), 664--693.\n\n EXAMPLES::\n\n sage: # needs sage.symbolic\n sage: z = var('z')\n sage: B = BrauerAlgebra(3,z)\n sage: B.jucys_murphy(1)\n (1/2*z-1/2)*B{{-3, 3}, {-2, 2}, {-1, 1}}\n sage: B.jucys_murphy(3)\n -B{{-3, -2}, {-1, 1}, {2, 3}} - B{{-3, -1}, {-2, 2}, {1, 3}}\n + B{{-3, 1}, {-2, 2}, {-1, 3}} + B{{-3, 2}, {-2, 3}, {-1, 1}}\n + (1/2*z-1/2)*B{{-3, 3}, {-2, 2}, {-1, 1}}\n "
if (j < 1):
raise ValueError('Jucys-Murphy index must be positive')
k = self.order()
if (j > k):
raise ValueError('Jucys-Murphy index cannot be greater than the order of the algebra')
def convertI(x):
return self._indices(to_Brauer_partition(x, k=k))
R = self.base_ring()
one = R.one()
d = {self.one_basis(): R(((self._q - 1) / 2))}
for i in range(1, j):
d[convertI([[i, (- j)], [j, (- i)]])] = one
d[convertI([[i, j], [(- i), (- j)]])] = (- one)
return self._from_dict(d, remove_zeros=True)
|
class TemperleyLiebAlgebra(SubPartitionAlgebra, UnitDiagramMixin):
'\n A Temperley--Lieb algebra.\n\n The Temperley--Lieb algebra of rank `k` is an algebra with basis\n indexed by the collection of planar set partitions of\n `\\{1, \\ldots, k, -1, \\ldots, -k\\}` with block size 2.\n\n This algebra is thus a subalgebra of the partition algebra.\n For more information, see :class:`PartitionAlgebra`.\n\n INPUT:\n\n - ``k`` -- rank of the algebra\n\n - ``q`` -- the deformation parameter `q`\n\n OPTIONAL ARGUMENTS:\n\n - ``base_ring`` -- (default ``None``) a ring containing ``q``; if ``None``\n then just takes the parent of ``q``\n\n - ``prefix`` -- (default ``"T"``) a label for the basis elements\n\n EXAMPLES:\n\n We define the Temperley--Lieb algebra of rank `2` with parameter\n `x` over `\\ZZ`::\n\n sage: R.<x> = ZZ[]\n sage: T = TemperleyLiebAlgebra(2, x, R); T\n Temperley-Lieb Algebra of rank 2 with parameter x\n over Univariate Polynomial Ring in x over Integer Ring\n sage: T.basis()\n Lazy family (Term map from Temperley Lieb diagrams of order 2\n to Temperley-Lieb Algebra of rank 2 with parameter x over\n Univariate Polynomial Ring in x over Integer\n Ring(i))_{i in Temperley Lieb diagrams of order 2}\n sage: T.basis().keys()\n Temperley Lieb diagrams of order 2\n sage: T.basis().keys()([[-1, 1], [2, -2]])\n {{-2, 2}, {-1, 1}}\n sage: b = T.basis().list(); b\n [T{{-2, -1}, {1, 2}}, T{{-2, 2}, {-1, 1}}]\n sage: b[0]\n T{{-2, -1}, {1, 2}}\n sage: b[0]^2 == x*b[0]\n True\n sage: b[0]^5 == x^4*b[0]\n True\n '
@staticmethod
def __classcall_private__(cls, k, q, base_ring=None, prefix='T'):
"\n Standardize the input by getting the base ring from the parent of\n the parameter ``q`` if no ``base_ring`` is given.\n\n TESTS::\n\n sage: R.<q> = QQ[]\n sage: T1 = TemperleyLiebAlgebra(2, q)\n sage: T2 = TemperleyLiebAlgebra(2, q, R, 'T')\n sage: T1 is T2\n True\n "
if (base_ring is None):
base_ring = q.parent()
return super().__classcall__(cls, k, q, base_ring, prefix)
def __init__(self, k, q, base_ring, prefix):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: R.<q> = QQ[]\n sage: TL = TemperleyLiebAlgebra(2, q, R)\n sage: TestSuite(TL).run()\n '
SubPartitionAlgebra.__init__(self, k, q, base_ring, prefix, TemperleyLiebDiagrams(k))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: R.<q> = QQ[]\n sage: TemperleyLiebAlgebra(2, q, R)\n Temperley-Lieb Algebra of rank 2 with parameter q\n over Univariate Polynomial Ring in q over Rational Field\n '
return 'Temperley-Lieb Algebra of rank {} with parameter {} over {}'.format(self._k, self._q, self.base_ring())
def _element_constructor_(self, set_partition):
'\n Construct an element of ``self``.\n\n EXAMPLES::\n\n sage: R.<q> = QQ[]\n sage: TL = TemperleyLiebAlgebra(2, q, R)\n sage: sp = SetPartition([[1,2], [-1,-2]])\n sage: b_elt = TL(sp); b_elt\n T{{-2, -1}, {1, 2}}\n sage: b_elt in TL\n True\n sage: TL([[1,2],[-1,-2]]) == b_elt\n True\n sage: TL([{1,2},{-1,-2}]) == b_elt\n True\n sage: S = SymmetricGroupAlgebra(R, 2)\n sage: TL(S([1,2]))\n T{{-2, 2}, {-1, 1}}\n sage: TL(S([2,1]))\n Traceback (most recent call last):\n ...\n ValueError: the diagram {{-2, 1}, {-1, 2}} must be planar\n '
if isinstance(set_partition, SymmetricGroupAlgebra_n.Element):
return SubPartitionAlgebra._element_constructor_(self, set_partition)
set_partition = to_Brauer_partition(set_partition, k=self.order())
return SubPartitionAlgebra._element_constructor_(self, set_partition)
def _ascii_art_term(self, diagram):
'\n Return an ascii art representation of ``diagram``.\n\n EXAMPLES::\n\n sage: R.<q> = QQ[]\n sage: TL = TemperleyLiebAlgebra(4, q, R)\n sage: x = TL.an_element()\n sage: ascii_art(x) # indirect doctest\n o o o o o o o o\n o o o o | `-` | | `-` |\n 2* `-` `-` + 2* `-----` + 3* `---. |\n .-. .-. .-. .-. .-. | |\n o o o o o o o o o o o o\n '
return TL_diagram_ascii_art(diagram, use_unicode=False)
def _unicode_art_term(self, diagram):
'\n Return a unicode art representation of ``diagram``.\n\n EXAMPLES::\n\n sage: R.<q> = QQ[]\n sage: TL = TemperleyLiebAlgebra(4, q, R)\n sage: x = TL.an_element()\n sage: unicode_art(x) # indirect doctest\n ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬\n ⚬ ⚬ ⚬ ⚬ │ ╰─╯ │ │ ╰─╯ │\n 2* ╰─╯ ╰─╯ + 2* ╰─────╯ + 3* ╰───╮ │\n ╭─╮ ╭─╮ ╭─╮ ╭─╮ ╭─╮ │ │\n ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬\n '
return TL_diagram_ascii_art(diagram, use_unicode=True)
|
class PlanarAlgebra(SubPartitionAlgebra, UnitDiagramMixin):
'\n A planar algebra.\n\n The planar algebra of rank `k` is an algebra with basis indexed by the\n collection of all planar set partitions of\n `\\{1, \\ldots, k, -1, \\ldots, -k\\}`.\n\n This algebra is thus a subalgebra of the partition algebra. For more\n information, see :class:`PartitionAlgebra`.\n\n INPUT:\n\n - ``k`` -- rank of the algebra\n\n - ``q`` -- the deformation parameter `q`\n\n OPTIONAL ARGUMENTS:\n\n - ``base_ring`` -- (default ``None``) a ring containing ``q``; if ``None``\n then just takes the parent of ``q``\n\n - ``prefix`` -- (default ``"Pl"``) a label for the basis elements\n\n EXAMPLES:\n\n We define the planar algebra of rank `2` with parameter\n `x` over `\\ZZ`::\n\n sage: R.<x> = ZZ[]\n sage: Pl = PlanarAlgebra(2, x, R); Pl\n Planar Algebra of rank 2 with parameter x over Univariate Polynomial Ring in x over Integer Ring\n sage: Pl.basis().keys()\n Planar diagrams of order 2\n sage: Pl.basis().keys()([[-1, 1], [2, -2]])\n {{-2, 2}, {-1, 1}}\n sage: Pl.basis().list()\n [Pl{{-2}, {-1}, {1, 2}},\n Pl{{-2}, {-1}, {1}, {2}},\n Pl{{-2, 1}, {-1}, {2}},\n Pl{{-2, 2}, {-1}, {1}},\n Pl{{-2, 1, 2}, {-1}},\n Pl{{-2, 2}, {-1, 1}},\n Pl{{-2}, {-1, 1}, {2}},\n Pl{{-2}, {-1, 2}, {1}},\n Pl{{-2}, {-1, 1, 2}},\n Pl{{-2, -1}, {1, 2}},\n Pl{{-2, -1}, {1}, {2}},\n Pl{{-2, -1, 1}, {2}},\n Pl{{-2, -1, 2}, {1}},\n Pl{{-2, -1, 1, 2}}]\n sage: E = Pl([[1,2],[-1,-2]])\n sage: E^2 == x*E\n True\n sage: E^5 == x^4*E\n True\n '
@staticmethod
def __classcall_private__(cls, k, q, base_ring=None, prefix='Pl'):
"\n Standardize the input by getting the base ring from the parent of\n the parameter ``q`` if no ``base_ring`` is given.\n\n TESTS::\n\n sage: R.<q> = QQ[]\n sage: Pl1 = PlanarAlgebra(2, q)\n sage: Pl2 = PlanarAlgebra(2, q, R, 'Pl')\n sage: Pl1 is Pl2\n True\n "
if (base_ring is None):
base_ring = q.parent()
return super().__classcall__(cls, k, q, base_ring, prefix)
def __init__(self, k, q, base_ring, prefix):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: R.<q> = QQ[]\n sage: PlA = PlanarAlgebra(2, q, R)\n sage: TestSuite(PlA).run()\n '
SubPartitionAlgebra.__init__(self, k, q, base_ring, prefix, PlanarDiagrams(k))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: R.<x> = ZZ[]\n sage: Pl = PlanarAlgebra(2, x, R); Pl\n Planar Algebra of rank 2 with parameter x\n over Univariate Polynomial Ring in x over Integer Ring\n '
txt = 'Planar Algebra of rank {} with parameter {} over {}'
return txt.format(self._k, self._q, self.base_ring())
|
class PropagatingIdeal(SubPartitionAlgebra):
'\n A propagating ideal.\n\n The propagating ideal of rank `k` is a non-unital algebra with basis\n indexed by the collection of ideal set partitions of `\\{1, \\ldots, k, -1,\n \\ldots, -k\\}`. We say a set partition is *ideal* if its propagating\n number is less than `k`.\n\n This algebra is a non-unital subalgebra and an ideal of the partition\n algebra.\n For more information, see :class:`PartitionAlgebra`.\n\n EXAMPLES:\n\n We now define the propagating ideal of rank `2` with parameter\n `x` over `\\ZZ`::\n\n sage: R.<x> = QQ[]\n sage: I = PropagatingIdeal(2, x, R); I\n Propagating Ideal of rank 2 with parameter x\n over Univariate Polynomial Ring in x over Rational Field\n sage: I.basis().keys()\n Ideal diagrams of order 2\n sage: I.basis().list()\n [I{{-2, -1, 1, 2}},\n I{{-2, 1, 2}, {-1}},\n I{{-2}, {-1, 1, 2}},\n I{{-2, -1}, {1, 2}},\n I{{-2}, {-1}, {1, 2}},\n I{{-2, -1, 1}, {2}},\n I{{-2, 1}, {-1}, {2}},\n I{{-2, -1, 2}, {1}},\n I{{-2, 2}, {-1}, {1}},\n I{{-2}, {-1, 1}, {2}},\n I{{-2}, {-1, 2}, {1}},\n I{{-2, -1}, {1}, {2}},\n I{{-2}, {-1}, {1}, {2}}]\n sage: E = I([[1,2],[-1,-2]])\n sage: E^2 == x*E\n True\n sage: E^5 == x^4*E\n True\n '
@staticmethod
def __classcall_private__(cls, k, q, base_ring=None, prefix='I'):
"\n Standardize the input by getting the base ring from the parent of\n the parameter ``q`` if no ``base_ring`` is given.\n\n TESTS::\n\n sage: R.<q> = QQ[]\n sage: IA1 = PropagatingIdeal(2, q)\n sage: IA2 = PropagatingIdeal(2, q, R, 'I')\n sage: IA1 is IA2\n True\n "
if (base_ring is None):
base_ring = q.parent()
return super().__classcall__(cls, k, q, base_ring, prefix)
def __init__(self, k, q, base_ring, prefix):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: R.<q> = QQ[]\n sage: I = PropagatingIdeal(2, q, R)\n sage: TestSuite(I).run()\n '
category = AssociativeAlgebras(base_ring.category()).FiniteDimensional().WithBasis()
SubPartitionAlgebra.__init__(self, k, q, base_ring, prefix, IdealDiagrams(k), category)
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: PropagatingIdeal(2, x, R)\n Propagating Ideal of rank 2 with parameter x over Univariate\n Polynomial Ring in x over Rational Field\n '
return 'Propagating Ideal of rank {} with parameter {} over {}'.format(self._k, self._q, self.base_ring())
class Element(SubPartitionAlgebra.Element):
'\n An element of a propagating ideal.\n\n We need to take care of exponents since we are not unital.\n '
def __pow__(self, n):
'\n Return ``self`` to the `n`-th power.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: I = PropagatingIdeal(2, x, R)\n sage: E = I([[1,2],[-1,-2]])\n sage: E^2\n x*I{{-2, -1}, {1, 2}}\n sage: E^0\n Traceback (most recent call last):\n ...\n ValueError: can only take positive integer powers\n '
if (n <= 0):
raise ValueError('can only take positive integer powers')
return generic_power(self, n)
|
def TL_diagram_ascii_art(diagram, use_unicode=False, blobs=[]):
'\n Return ascii art for a Temperley-Lieb diagram ``diagram``.\n\n INPUT:\n\n - ``diagram`` -- a list of pairs of matchings of the set\n `\\{-1, \\ldots, -n, 1, \\ldots, n\\}`\n - ``use_unicode`` -- (default: ``False``): whether or not\n to use unicode art instead of ascii art\n - ``blobs`` -- (optional) a list of matchings with blobs on them\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import TL_diagram_ascii_art\n sage: TL = [(-15,-12), (-14,-13), (-11,15), (-10,14), (-9,-6),\n ....: (-8,-7), (-5,-4), (-3,1), (-2,-1), (2,3), (4,5),\n ....: (6,11), (7, 8), (9,10), (12,13)]\n sage: TL_diagram_ascii_art(TL, use_unicode=False)\n o o o o o o o o o o o o o o o\n | `-` `-` | `-` `-` | `-` | |\n | `---------` | |\n | .-------` |\n `---. | .-------`\n | .-----. | | .-----.\n .-. | .-. | .-. | | | | .-. |\n o o o o o o o o o o o o o o o\n sage: TL_diagram_ascii_art(TL, use_unicode=True)\n ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬\n │ ╰─╯ ╰─╯ │ ╰─╯ ╰─╯ │ ╰─╯ │ │\n │ ╰─────────╯ │ │\n │ ╭───────╯ │\n ╰───╮ │ ╭───────╯\n │ ╭─────╮ │ │ ╭─────╮\n ╭─╮ │ ╭─╮ │ ╭─╮ │ │ │ │ ╭─╮ │\n ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬\n\n sage: TL = [(-20,-9), (-19,-10), (-18,-11), (-17,-16), (-15,-12), (2,3),\n ....: (-14,-13), (-8,16), (-7,7), (-6,6), (-5,1), (-4,-3), (-2,-1),\n ....: (4,5), (8,15), (9,10), (11,14), (12,13), (17,20), (18,19)]\n sage: TL_diagram_ascii_art(TL, use_unicode=False, blobs=[(-2,-1), (-5,1)])\n o o o o o o o o o o o o o o o o o o o o\n | `-` `-` | | | `-` | `-` | | | | `-` |\n | | | | `-----` | | `-----`\n | | | `-------------` |\n `---0---. | | .---------------`\n | | | | .---------------------.\n | | | | | .-----------------. |\n | | | | | | .-------------. | |\n | | | | | | | .-----. | | |\n .0. .-. | | | | | | | | .-. | .-. | | |\n o o o o o o o o o o o o o o o o o o o o\n sage: TL_diagram_ascii_art(TL, use_unicode=True, blobs=[(-2,-1), (-5,1)])\n ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬\n │ ╰─╯ ╰─╯ │ │ │ ╰─╯ │ ╰─╯ │ │ │ │ ╰─╯ │\n │ │ │ │ ╰─────╯ │ │ ╰─────╯\n │ │ │ ╰─────────────╯ │\n ╰───●───╮ │ │ ╭───────────────╯\n │ │ │ │ ╭─────────────────────╮\n │ │ │ │ │ ╭─────────────────╮ │\n │ │ │ │ │ │ ╭─────────────╮ │ │\n │ │ │ │ │ │ │ ╭─────╮ │ │ │\n ╭●╮ ╭─╮ │ │ │ │ │ │ │ │ ╭─╮ │ ╭─╮ │ │ │\n ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬ ⚬\n '
def insert_pairing(cur, intervals):
'\n Helper function to insert a possibly nested interval\n and push the others up, assuming inserting points from\n right-to-left.\n '
for level in intervals:
for (j, I) in enumerate(level):
if ((len(I) > 1) and (I[0] < cur[0])):
(cur, level[j]) = (level[j], cur)
level.append([cur[0]])
level.append([cur[1]])
break
else:
level.append(cur)
return
else:
intervals.append([cur])
intervals = [[]]
propogating = []
vertical = []
top_intervals = [[]]
num_left = 0
num_right = 0
def key_func(P):
if (P[1] < 0):
return (0, P[0], P[1])
elif (P[0] > 0):
return (3, (- P[1]), (- P[0]))
else:
(bot, top) = ((- P[0]), P[1])
if (top < bot):
return (1, top, bot)
elif (top > bot):
return (2, (- bot), (- top))
else:
return (1, top, bot)
diagram = sorted(diagram, key=key_func)
for P in diagram:
if (P[1] < 0):
insert_pairing([(- P[1]), (- P[0]), False, False], intervals)
elif (P[0] > 0):
insert_pairing([P[0], P[1], True, True], top_intervals)
elif ((- P[0]) == P[1]):
vertical.append(P[1])
else:
if ((- P[0]) < P[1]):
num_right += 1
else:
num_left += 1
propogating.append(P)
total_prop = max(num_left, num_right)
prop_intervals = [[] for _ in range(total_prop)]
count_left = 0
for (i, P) in enumerate(propogating):
(bot, top) = P
bot = (- bot)
for level in intervals:
level.append([bot])
for level in top_intervals:
level.append([top])
left_moving = (count_left < num_left)
if (not left_moving):
i -= num_left
else:
count_left += 1
for j in range(i):
prop_intervals[j].append([bot])
for j in range((i + 1), total_prop):
prop_intervals[j].append([top])
if (not left_moving):
(top, bot) = (bot, top)
prop_intervals[i].append([top, bot, left_moving, (not left_moving)])
intervals += prop_intervals
intervals += reversed(top_intervals)
for level in intervals:
level.extend(([i] for i in vertical))
n = max((max(P) for P in diagram))
if use_unicode:
from sage.typeset.unicode_art import UnicodeArt
d = ['╭', '╮', '╰', '╯', '─', '│']
blob = '●'
ret = [(' ⚬' * n)]
char_art = UnicodeArt
else:
from sage.typeset.ascii_art import AsciiArt
d = ['.', '.', '`', '`', '-', '|']
blob = '0'
ret = [(' o' * n)]
char_art = AsciiArt
def signed(val, pos):
return (val if pos else (- val))
for level in reversed(intervals):
cur = ''
for I in sorted(level):
cur += (' ' * (((2 * I[0]) - 1) - len(cur)))
if (len(I) == 1):
cur += (d[5] + ' ')
else:
cur += (d[2] if I[2] else d[0])
if (tuple(sorted([signed(I[0], I[2]), signed(I[1], I[3])])) in blobs):
cur += (d[4] * ((I[1] - I[0]) - 1))
cur += blob
cur += (d[4] * ((I[1] - I[0]) - 1))
else:
cur += (d[4] * ((2 * (I[1] - I[0])) - 1))
cur += (d[3] if I[3] else d[1])
ret.append(cur)
ret.append(ret[0])
return char_art(ret, baseline=(len(ret) // 2))
|
def diagram_latex(diagram, fill=False, edge_options=None, edge_additions=None):
'\n Return latex code for the diagram ``diagram`` using tikz.\n\n EXAMPLES::\n\n sage: from sage.combinat.diagram_algebras import PartitionDiagrams, diagram_latex\n sage: P = PartitionDiagrams(2)\n sage: D = P([[1,2],[-2,-1]])\n sage: print(diagram_latex(D)) # indirect doctest\n \\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 '
from sage.misc.latex import latex
latex.add_package_to_preamble_if_available('tikz')
if fill:
filled_str = ', fill'
else:
filled_str = ''
if (edge_options is None):
edge_options = (lambda P: '')
if (edge_additions is None):
edge_additions = (lambda P: '')
def sgn(x):
if (x > 0):
return 1
if (x < 0):
return (- 1)
return 0
l1 = []
l2 = []
for i in list(diagram):
l1.append(list(i))
for j in list(i):
l2.append(j)
output = '\\begin{tikzpicture}[scale = 0.5,thick, baseline={(0,-1ex/2)}] \n\\tikzstyle{vertex} = [shape = circle, minimum size = 7pt, inner sep = 1pt] \n'
for i in l2:
output = (output + '\\node[vertex] (G-{}) at ({}, {}) [shape = circle, draw{}] {{}}; \n'.format(i, ((abs(i) - 1) * 1.5), sgn(i), filled_str))
for i in l1:
if (len(i) > 1):
l4 = list(i)
posList = []
negList = []
for j in l4:
if (j > 0):
posList.append(j)
elif (j < 0):
negList.append(j)
posList.sort()
negList.sort()
l4 = (posList + negList)
l5 = l4[:]
for j in range(len(l5)):
l5[(j - 1)] = l4[j]
if (len(l4) == 2):
l4.pop()
l5.pop()
for j in zip(l4, l5):
xdiff = (abs(j[1]) - abs(j[0]))
y1 = sgn(j[0])
y2 = sgn(j[1])
if (((y2 - y1) == 0) and (abs(xdiff) < 5)):
diffCo = (0.5 + (0.1 * (abs(xdiff) - 1)))
outVec = ((sgn(xdiff) * diffCo), (((- 1) * diffCo) * y1))
inVec = ((((- 1) * diffCo) * sgn(xdiff)), (((- 1) * diffCo) * y2))
elif (((y2 - y1) != 0) and (abs(xdiff) == 1)):
outVec = ((sgn(xdiff) * 0.75), ((- 1) * y1))
inVec = ((((- 1) * sgn(xdiff)) * 0.75), ((- 1) * y2))
else:
outVec = ((sgn(xdiff) * 1), ((- 1) * y1))
inVec = (((- 1) * sgn(xdiff)), ((- 1) * y2))
output = (output + '\\draw[{}] (G-{}) .. controls +{} and +{} .. {}(G-{}); \n'.format(edge_options(j), j[0], outVec, inVec, edge_additions(j), j[1]))
output = (output + '\\end{tikzpicture}')
return output
|
def is_planar(sp):
'\n Return ``True`` if the diagram corresponding to the set partition ``sp``\n is planar; otherwise, return ``False``.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: da.is_planar( da.to_set_partition([[1,-2],[2,-1]]))\n False\n sage: da.is_planar( da.to_set_partition([[1,-1],[2,-2]]))\n True\n '
to_consider = [x for x in map(list, sp) if (len(x) > 1)]
n = len(to_consider)
for i in range(n):
ap = [x for x in to_consider[i] if (x > 0)]
an = [abs(x) for x in to_consider[i] if (x < 0)]
if (ap and an):
for j in range(n):
if (i == j):
continue
bp = [x for x in to_consider[j] if (x > 0)]
bn = [abs(x) for x in to_consider[j] if (x < 0)]
if ((not bn) or (not bp)):
continue
if (max(bp) > max(ap)):
if (min(bn) < min(an)):
return False
for row in [ap, an]:
if (len(row) > 1):
row.sort()
for s in range((len(row) - 1)):
if ((row[s] + 1) == row[(s + 1)]):
continue
rng = list(range((row[s] + 1), row[(s + 1)]))
for j in range(n):
if (i == j):
continue
if (row is ap):
sr = set(rng)
else:
sr = set(((- x) for x in rng))
sj = set(to_consider[j])
intersection = sr.intersection(sj)
if intersection:
if (sj != intersection):
return False
return True
|
def to_graph(sp):
'\n Return a graph representing the set partition ``sp``.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: g = da.to_graph( da.to_set_partition([[1,-2],[2,-1]])); g\n Graph on 4 vertices\n\n sage: g.vertices(sort=True)\n [-2, -1, 1, 2]\n sage: g.edges(sort=True)\n [(-2, 1, None), (-1, 2, None)]\n '
g = Graph()
for part in sp:
part_list = list(part)
if (len(part_list) > 0):
g.add_vertex(part_list[0])
for i in range(1, len(part_list)):
g.add_vertex(part_list[i])
g.add_edge(part_list[(i - 1)], part_list[i])
return g
|
def pair_to_graph(sp1, sp2):
'\n Return a graph consisting of the disjoint union of the graphs of set\n partitions ``sp1`` and ``sp2`` along with edges joining the bottom\n row (negative numbers) of ``sp1`` to the top row (positive numbers)\n of ``sp2``.\n\n The vertices of the graph ``sp1`` appear in the result as pairs\n ``(k, 1)``, whereas the vertices of the graph ``sp2`` appear as\n pairs ``(k, 2)``.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: sp1 = da.to_set_partition([[1,-2],[2,-1]])\n sage: sp2 = da.to_set_partition([[1,-2],[2,-1]])\n sage: g = da.pair_to_graph( sp1, sp2 ); g\n Graph on 8 vertices\n\n sage: g.vertices(sort=True)\n [(-2, 1), (-2, 2), (-1, 1), (-1, 2), (1, 1), (1, 2), (2, 1), (2, 2)]\n sage: g.edges(sort=True)\n [((-2, 1), (1, 1), None), ((-2, 1), (2, 2), None),\n ((-2, 2), (1, 2), None), ((-1, 1), (1, 2), None),\n ((-1, 1), (2, 1), None), ((-1, 2), (2, 2), None)]\n\n Another example which used to be wrong until :trac:`15958`::\n\n sage: sp3 = da.to_set_partition([[1, -1], [2], [-2]])\n sage: sp4 = da.to_set_partition([[1], [-1], [2], [-2]])\n sage: g = da.pair_to_graph( sp3, sp4 ); g\n Graph on 8 vertices\n\n sage: g.vertices(sort=True)\n [(-2, 1), (-2, 2), (-1, 1), (-1, 2), (1, 1), (1, 2), (2, 1), (2, 2)]\n sage: g.edges(sort=True)\n [((-2, 1), (2, 2), None), ((-1, 1), (1, 1), None),\n ((-1, 1), (1, 2), None)]\n '
g = Graph()
for part in sp1:
part_list = list(part)
if part_list:
g.add_vertex((part_list[0], 1))
if (part_list[0] < 0):
g.add_edge((part_list[0], 1), (abs(part_list[0]), 2))
for i in range(1, len(part_list)):
g.add_vertex((part_list[i], 1))
if (part_list[i] < 0):
g.add_edge((part_list[i], 1), (abs(part_list[i]), 2))
g.add_edge((part_list[(i - 1)], 1), (part_list[i], 1))
for part in sp2:
part_list = list(part)
if part_list:
g.add_vertex((part_list[0], 2))
for i in range(1, len(part_list)):
g.add_vertex((part_list[i], 2))
g.add_edge((part_list[(i - 1)], 2), (part_list[i], 2))
return g
|
def propagating_number(sp):
'\n Return the propagating number of the set partition ``sp``.\n\n The propagating number is the number of blocks with both a positive and\n negative number.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: sp1 = da.to_set_partition([[1,-2],[2,-1]])\n sage: sp2 = da.to_set_partition([[1,2],[-2,-1]])\n sage: da.propagating_number(sp1)\n 2\n sage: da.propagating_number(sp2)\n 0\n '
return sum((1 for part in sp if (min(part) < 0 < max(part))))
|
def to_set_partition(l, k=None):
'\n Convert input to a set partition of `\\{1, \\ldots, k, -1, \\ldots, -k\\}`\n\n Convert a list of a list of numbers to a set partitions. Each list\n of numbers in the outer list specifies the numbers contained in one\n of the blocks in the set partition.\n\n If `k` is specified, then the set partition will be a set partition\n of `\\{1, \\ldots, k, -1, \\ldots, -k\\}`. Otherwise, `k` will default to\n the minimum number needed to contain all of the specified numbers.\n\n INPUT:\n\n - ``l`` - a list of lists of integers\n - ``k`` - integer (optional, default ``None``)\n\n OUTPUT:\n\n - a list of sets\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: f = lambda sp: SetPartition(da.to_set_partition(sp))\n sage: f([[1,-1],[2,-2]]) == SetPartition(da.identity_set_partition(2))\n True\n sage: da.to_set_partition([[1]])\n [{1}, {-1}]\n sage: da.to_set_partition([[1,-1],[-2,3]],9/2)\n [{-1, 1}, {-2, 3}, {2}, {-4, 4}, {-5, 5}, {-3}]\n '
if (k is None):
if (not l):
return []
k = max((max(map(abs, x)) for x in l))
to_be_added = set((list(range(1, ceil((k + 1)))) + [(- x) for x in range(1, ceil((k + 1)))]))
sp = []
for part in l:
spart = set(part)
to_be_added -= spart
sp.append(spart)
while to_be_added:
i = to_be_added.pop()
if ((- i) in to_be_added):
to_be_added.remove((- i))
sp.append(set([i, (- i)]))
else:
sp.append(set([i]))
return sp
|
def to_Brauer_partition(l, k=None):
'\n Same as :func:`to_set_partition` but assumes omitted elements are\n connected straight through.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: f = lambda sp: SetPartition(da.to_Brauer_partition(sp))\n sage: f([[1,2],[-1,-2]]) == SetPartition([[1,2],[-1,-2]])\n True\n sage: f([[1,3],[-1,-3]]) == SetPartition([[1,3],[-3,-1],[2,-2]])\n True\n sage: f([[1,-4],[-3,-1],[3,4]]) == SetPartition([[-3,-1],[2,-2],[1,-4],[3,4]])\n True\n sage: p = SetPartition([[1,2],[-1,-2],[3,-3],[4,-4]])\n sage: SetPartition(da.to_Brauer_partition([[1,2],[-1,-2]], k=4)) == p\n True\n '
L = to_set_partition(l, k=k)
L2 = []
paired = []
not_paired = []
for i in L:
L2.append(list(i))
for i in L2:
if (len(i) > 2):
raise ValueError('blocks must have size at most 2, but {} has {}'.format(i, len(i)))
if (len(i) == 2):
paired.append(i)
if (len(i) == 1):
not_paired.append(i)
if any((((i[0] in j) or (((- 1) * i[0]) in j)) for i in not_paired for j in paired)):
raise ValueError('unable to convert {} to a Brauer partition due to the invalid block {}'.format(l, i))
for i in not_paired:
if ([(- i[0])] in not_paired):
not_paired.remove([(- i[0])])
paired.append([i[0], (- i[0])])
return to_set_partition(paired)
|
def identity_set_partition(k):
'\n Return the identity set partition `\\{\\{1, -1\\}, \\ldots, \\{k, -k\\}\\}`.\n\n EXAMPLES::\n\n sage: import sage.combinat.diagram_algebras as da\n sage: SetPartition(da.identity_set_partition(2))\n {{-2, 2}, {-1, 1}}\n '
if (k in ZZ):
return [[i, (- i)] for i in range(1, (k + 1))]
return [[i, (- i)] for i in range(1, (k + (ZZ(3) / ZZ(2))))]
|
class DLXMatrix():
def __init__(self, ones, initialsolution=None):
"\n Solve the Exact Cover problem by using the Dancing Links algorithm\n described by Knuth.\n\n Consider a matrix M with entries of 0 and 1, and compute a subset\n of the rows of this matrix which sum to the vector of all 1's.\n\n The dancing links algorithm works particularly well for sparse\n matrices, so the input is a list of lists of the form: (note the\n 1-index!)::\n\n [\n [1, [i_11,i_12,...,i_1r]]\n ...\n [m,[i_m1,i_m2,...,i_ms]]\n ]\n\n where M[j][i_jk] = 1.\n\n The first example below corresponds to the matrix::\n\n 1110\n 1010\n 0100\n 0001\n\n which is exactly covered by::\n\n 1110\n 0001\n\n and\n\n ::\n\n 1010\n 0100\n 0001\n\n EXAMPLES::\n\n sage: from sage.combinat.dlx import *\n sage: ones = [[1,[1,2,3]]]\n sage: ones+= [[2,[1,3]]]\n sage: ones+= [[3,[2]]]\n sage: ones+= [[4,[4]]]\n sage: DLXM = DLXMatrix(ones,[4])\n sage: for C in DLXM:\n ....: print(C)\n [4, 1]\n [4, 2, 3]\n\n .. NOTE::\n\n The 0 entry is reserved internally for headers in the\n sparse representation, so rows and columns begin their\n indexing with 1. Apologies for any heartache this\n causes. Blame the original author, or fix it yourself.\n "
if (initialsolution is None):
initialsolution = []
self._cursolution = []
self._nodes = [[0, 0, None, None, None, None]]
self._constructmatrix(ones, initialsolution)
self._level = 0
self._stack = [(None, None)]
def __eq__(self, other):
'\n Return ``True`` if every attribute of\n ``other`` matches the attribute of\n ``self``.\n\n INPUT:\n\n\n - ``other`` - a DLX matrix\n\n\n EXAMPLES::\n\n sage: from sage.combinat.dlx import *\n sage: M = DLXMatrix([[1,[1]]])\n sage: M == loads(dumps(M))\n True\n '
if (not isinstance(other, DLXMatrix)):
return False
return (self.__dict__ == other.__dict__)
def __iter__(self):
'\n Return ``self``.\n\n TESTS::\n\n sage: from sage.combinat.dlx import *\n sage: M = DLXMatrix([[1,[1]]])\n sage: M.__iter__() is M\n True\n '
return self
def _walknodes(self, firstnode, direction):
'\n Generator for iterating over all nodes in given ``direction`` (not\n including ``firstnode``).\n\n TESTS::\n\n sage: from sage.combinat.dlx import *\n sage: ones = [[1,[1,2,3]]]\n sage: ones+= [[2,[1,3]]]\n sage: ones+= [[3,[2]]]\n sage: ones+= [[4,[4]]]\n sage: DLX = DLXMatrix(ones,[4])\n sage: count = 0\n sage: for c in DLX._walknodes(ROOTNODE,RIGHT):\n ....: count += DLX._nodes[c][COUNT]\n ....: for d in DLX._walknodes(c,DOWN):\n ....: count -= 1\n sage: count\n 0\n '
nodetable = self._nodes
n = nodetable[firstnode][direction]
while (n != firstnode):
(yield n)
n = nodetable[n][direction]
def _constructmatrix(self, ones, initialsolution=None):
'\n Construct the (sparse) DLX matrix based on list ``\'ones\'``.\n\n The first component in the list elements is row index (which\n will be returned by solve) and the second component is list of\n column indexes of ones in given row.\n\n \'initialsolution\' is list of row indexes that are required to be\n part of the solution. They will be removed from the matrix.\n\n .. NOTE:\n\n Rows and cols are 1-indexed ; the zero index is reserved for\n the root node and column heads.\n\n TESTS::\n\n sage: from sage.combinat.dlx import *\n sage: ones = [[1,[1,2,3]]]\n sage: ones+= [[2,[1,3]]]\n sage: ones+= [[3,[2]]]\n sage: ones+= [[4,[4]]]\n sage: DLX = DLXMatrix([[1,[1]]])\n sage: DLX._constructmatrix(ones,[4])\n sage: c = DLX._nodes[ROOTNODE][RIGHT]\n sage: fullcount = 0\n sage: while c != ROOTNODE:\n ....: fullcount += DLX._nodes[c][COUNT]\n ....: d = DLX._nodes[c][DOWN]\n ....: while d != c:\n ....: bad = DLX._nodes[DLX._nodes[d][DOWN]][UP] != d\n ....: bad|= DLX._nodes[DLX._nodes[d][UP]][DOWN] != d\n ....: bad|= DLX._nodes[DLX._nodes[d][LEFT]][RIGHT] != d\n ....: bad|= DLX._nodes[DLX._nodes[d][RIGHT]][LEFT] != d\n ....: if bad:\n ....: raise RuntimeError("linked list inconsistent")\n ....: d = DLX._nodes[d][DOWN]\n ....: c = DLX._nodes[c][RIGHT]\n sage: fullcount\n 6\n '
if (initialsolution is None):
initialsolution = []
self._cursolution = []
self._nodes = [[ROOTNODE, ROOTNODE, None, None, None, None]]
nodetable = self._nodes
ones.sort()
pruneNodes = []
headers = [ROOTNODE]
for r in ones:
curRow = r[0]
columns = r[1]
if (not columns):
continue
columns.sort()
while (len(headers) <= columns[(- 1)]):
lastheader = headers[(- 1)]
newind = len(nodetable)
nodetable.append([lastheader, ROOTNODE, newind, newind, None, 0])
nodetable[ROOTNODE][LEFT] = newind
nodetable[lastheader][RIGHT] = newind
headers.append(newind)
newind = len(nodetable)
for (i, c) in enumerate(columns):
h = headers[c]
l = (newind + ((i - 1) % len(columns)))
r = (newind + ((i + 1) % len(columns)))
nodetable.append([l, r, nodetable[h][UP], h, h, curRow])
nodetable[nodetable[h][UP]][DOWN] = (newind + i)
nodetable[h][UP] = (newind + i)
nodetable[h][COUNT] += 1
if (curRow in initialsolution):
pruneNodes.append(newind)
for n in pruneNodes:
self._cursolution += [nodetable[n][INDEX]]
self._covercolumn(nodetable[n][COLUMN])
for j in self._walknodes(n, RIGHT):
self._covercolumn(nodetable[j][COLUMN])
def _covercolumn(self, c):
"\n Perform the column covering operation, as described by Knuth's\n pseudocode::\n\n cover(c):\n i <- D[c]\n while i != c:\n j <- R[i]\n while j != i\n D[U[j]] <- D[j]\n U[D[j]] <- U[j]\n N[C[j]] <- N[C[j]] - 1\n j <- R[j]\n i <- D[i]\n\n This is undone by the uncover operation.\n\n TESTS::\n\n sage: from sage.combinat.dlx import *\n sage: M = DLXMatrix([[1,[1,3]],[2,[1,2]],[3,[2]]])\n sage: one = M._nodes[ROOTNODE][RIGHT]\n sage: M._covercolumn(one)\n sage: two = M._nodes[ROOTNODE][RIGHT]\n sage: three = M._nodes[two][RIGHT]\n sage: M._nodes[three][RIGHT] == ROOTNODE\n True\n sage: M._nodes[two][COUNT]\n 1\n sage: M._nodes[three][COUNT]\n 0\n "
nodetable = self._nodes
nodetable[nodetable[c][RIGHT]][LEFT] = nodetable[c][LEFT]
nodetable[nodetable[c][LEFT]][RIGHT] = nodetable[c][RIGHT]
for i in self._walknodes(c, DOWN):
for j in self._walknodes(i, RIGHT):
nodetable[nodetable[j][DOWN]][UP] = nodetable[j][UP]
nodetable[nodetable[j][UP]][DOWN] = nodetable[j][DOWN]
nodetable[nodetable[j][COLUMN]][COUNT] -= 1
def _uncovercolumn(self, c):
"\n Perform the column uncovering operation, as described by Knuth's\n pseudocode::\n\n uncover(c):\n i <- U[c]\n while i != c:\n j <- L[i]\n while j != i\n U[j] <- U[D[j]]\n D[j] <- D[U[j]]\n N[C[j]] <- N[C[j]] + 1\n j <- L[j]\n i <- U[i]\n\n This undoes by the cover operation since everything is done in the\n reverse order.\n\n TESTS::\n\n sage: from sage.combinat.dlx import *\n sage: M = DLXMatrix([[1,[1,3]],[2,[1,2]],[3,[2]]])\n sage: one = M._nodes[ROOTNODE][RIGHT]\n sage: M._covercolumn(one)\n sage: two = M._nodes[ROOTNODE][RIGHT]\n sage: M._uncovercolumn(one)\n sage: M._nodes[two][LEFT] == one\n True\n sage: M._nodes[two][COUNT]\n 2\n "
nodetable = self._nodes
for i in self._walknodes(c, UP):
for j in self._walknodes(i, LEFT):
nodetable[nodetable[j][DOWN]][UP] = j
nodetable[nodetable[j][UP]][DOWN] = j
nodetable[nodetable[j][COLUMN]][COUNT] += 1
nodetable[nodetable[c][RIGHT]][LEFT] = c
nodetable[nodetable[c][LEFT]][RIGHT] = c
def __next__(self):
'\n Search for the first solution we can find, and return it.\n\n Knuth describes the Dancing Links algorithm recursively, though\n actually implementing it as a recursive algorithm is permissible\n only for highly restricted problems. (for example, the original\n author implemented this for Sudoku, and it works beautifully\n there)\n\n What follows is an iterative description of DLX::\n\n stack <- [(NULL)]\n level <- 0\n while level >= 0:\n cur <- stack[level]\n if cur = NULL:\n if R[h] = h:\n level <- level - 1\n yield solution\n else:\n cover(best_column)\n stack[level] = best_column\n else if D[cur] != C[cur]:\n if cur != C[cur]:\n delete solution[level]\n for j in L[cur], L[L[cur]], ... , while j != cur:\n uncover(C[j])\n cur <- D[cur]\n solution[level] <- cur\n stack[level] <- cur\n for j in R[cur], R[R[cur]], ... , while j != cur:\n cover(C[j])\n level <- level + 1\n stack[level] <- (NULL)\n else:\n if C[cur] != cur:\n delete solution[level]\n for j in L[cur], L[L[cur]], ... , while j != cur:\n uncover(C[j])\n uncover(cur)\n level <- level - 1\n\n TESTS::\n\n sage: from sage.combinat.dlx import *\n sage: M = DLXMatrix([[1,[1,2]],[2,[2,3]],[3,[1,3]]])\n sage: while 1:\n ....: try:\n ....: C = next(M)\n ....: except StopIteration:\n ....: print("StopIteration")\n ....: break\n ....: print(C)\n StopIteration\n sage: M = DLXMatrix([[1,[1,2]],[2,[2,3]],[3,[3]]])\n sage: for C in M:\n ....: print(C)\n [1, 3]\n sage: M = DLXMatrix([[1,[1]],[2,[2,3]],[3,[2]],[4,[3]]])\n sage: for C in M:\n ....: print(C)\n [1, 2]\n [1, 3, 4]\n '
nodetable = self._nodes
while (self._level >= 0):
(c, r) = self._stack[self._level]
if (c is None):
if (nodetable[ROOTNODE][RIGHT] == ROOTNODE):
self._level -= 1
return self._cursolution
else:
c = nodetable[ROOTNODE][RIGHT]
maxcount = nodetable[nodetable[ROOTNODE][RIGHT]][COUNT]
for j in self._walknodes(ROOTNODE, RIGHT):
if (nodetable[j][COUNT] < maxcount):
c = j
maxcount = nodetable[j][COUNT]
self._covercolumn(c)
self._stack[self._level] = (c, c)
elif (nodetable[r][DOWN] != c):
if (c != r):
self._cursolution = self._cursolution[:(- 1)]
for j in self._walknodes(r, LEFT):
self._uncovercolumn(nodetable[j][COLUMN])
r = nodetable[r][DOWN]
self._cursolution += [nodetable[r][INDEX]]
for j in self._walknodes(r, RIGHT):
self._covercolumn(nodetable[j][COLUMN])
self._stack[self._level] = (c, r)
self._level += 1
if (len(self._stack) == self._level):
self._stack.append((None, None))
else:
self._stack[self._level] = (None, None)
else:
if (c != r):
self._cursolution = self._cursolution[:(- 1)]
for j in self._walknodes(r, LEFT):
self._uncovercolumn(nodetable[j][COLUMN])
self._uncovercolumn(c)
self._level -= 1
raise StopIteration
next = __next__
|
def AllExactCovers(M):
"\n Use A. Ajanki's DLXMatrix class to solve the exact cover\n problem on the matrix M (treated as a dense binary matrix).\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: M = Matrix([[1,1,0],[1,0,1],[0,1,1]]) # no exact covers\n sage: for cover in AllExactCovers(M):\n ....: print(cover)\n sage: M = Matrix([[1,1,0],[1,0,1],[0,0,1],[0,1,0]]) # two exact covers\n sage: for cover in AllExactCovers(M):\n ....: print(cover)\n [(1, 1, 0), (0, 0, 1)]\n [(1, 0, 1), (0, 1, 0)]\n "
ones = []
r = 1
for R in M.rows():
row = []
for i in range(len(R)):
if R[i]:
row.append((i + 1))
ones.append([r, row])
r += 1
for s in DLXMatrix(ones):
(yield [M.row((i - 1)) for i in s])
|
def OneExactCover(M):
"\n Use A. Ajanki's DLXMatrix class to solve the exact cover\n problem on the matrix M (treated as a dense binary matrix).\n\n EXAMPLES::\n\n sage: M = Matrix([[1,1,0],[1,0,1],[0,1,1]]) # no exact covers # needs sage.modules\n sage: OneExactCover(M) # needs sage.modules\n\n sage: M = Matrix([[1,1,0],[1,0,1],[0,0,1],[0,1,0]]) # two exact covers # needs sage.modules\n sage: OneExactCover(M) # needs sage.modules\n [(1, 1, 0), (0, 0, 1)]\n "
for s in AllExactCovers(M):
return s
|
def replace_parens(x):
"\n A map sending ``'('`` to ``open_symbol`` and ``')'`` to\n ``close_symbol``, and raising an error on any input other than\n ``'('`` and ``')'``. The values of the constants ``open_symbol``\n and ``close_symbol`` are subject to change.\n\n This is the inverse map of :func:`replace_symbols`.\n\n INPUT:\n\n - ``x`` -- either an opening or closing parenthesis\n\n OUTPUT:\n\n - If ``x`` is an opening parenthesis, replace ``x`` with the\n constant ``open_symbol``.\n\n - If ``x`` is a closing parenthesis, replace ``x`` with the\n constant ``close_symbol``.\n\n - Raise a :class:`ValueError` if ``x`` is neither an opening nor a\n closing parenthesis.\n\n .. SEEALSO:: :func:`replace_symbols`\n\n EXAMPLES::\n\n sage: from sage.combinat.dyck_word import replace_parens\n sage: replace_parens('(')\n 1\n sage: replace_parens(')')\n 0\n sage: replace_parens(1)\n Traceback (most recent call last):\n ...\n ValueError\n "
if (x == '('):
return open_symbol
if (x == ')'):
return close_symbol
raise ValueError
|
def replace_symbols(x):
"\n A map sending ``open_symbol`` to ``'('`` and ``close_symbol`` to ``')'``,\n and raising an error on any input other than ``open_symbol`` and\n ``close_symbol``. The values of the constants ``open_symbol``\n and ``close_symbol`` are subject to change.\n\n This is the inverse map of :func:`replace_parens`.\n\n INPUT:\n\n - ``x`` -- either ``open_symbol`` or ``close_symbol``.\n\n OUTPUT:\n\n - If ``x`` is ``open_symbol``, replace ``x`` with ``'('``.\n\n - If ``x`` is ``close_symbol``, replace ``x`` with ``')'``.\n\n - If ``x`` is neither ``open_symbol`` nor ``close_symbol``, a\n :class:`ValueError` is raised.\n\n .. SEEALSO:: :func:`replace_parens`\n\n EXAMPLES::\n\n sage: from sage.combinat.dyck_word import replace_symbols\n sage: replace_symbols(1)\n '('\n sage: replace_symbols(0)\n ')'\n sage: replace_symbols(3)\n Traceback (most recent call last):\n ...\n ValueError\n "
if (x == open_symbol):
return '('
if (x == close_symbol):
return ')'
raise ValueError
|
class DyckWord(CombinatorialElement):
'\n A Dyck word.\n\n A Dyck word is a sequence of open and close symbols such that every close\n symbol has a corresponding open symbol preceding it. That is to say, a\n Dyck word of length `n` is a list with `k` entries 1 and `n - k`\n entries 0 such that the first `i` entries always have at least as many 1s\n among them as 0s. (Here, the 1 serves as the open symbol and the 0 as the\n close symbol.) Alternatively, the alphabet 1 and 0 can be replaced by\n other characters such as \'(\' and \')\'.\n\n A Dyck word is *complete* if every open symbol moreover has a corresponding\n close symbol.\n\n A Dyck word may also be specified by either a noncrossing partition or\n by an area sequence or the sequence of heights.\n\n A Dyck word may also be thought of as a lattice path in the `\\ZZ^2`\n grid, starting at the origin `(0,0)`, and with steps in the North\n `N = (0,1)` and east `E = (1,0)` directions such that it does not pass\n below the `x = y` diagonal. The diagonal is referred to as the "main\n diagonal" in the documentation. A North step is represented by a 1 in\n the list and an East step is represented by a 0.\n\n Equivalently, the path may be represented with steps in\n the `NE = (1,1)` and the `SE = (1,-1)` direction such that it does not\n pass below the horizontal axis.\n\n .. PLOT::\n :width: 400 px\n\n d = DyckWord([1,0,1,1,1,1,0,1,0,0,1,0,1,1,0,1,0,1,1,0,0,0,0,0])\n sphinx_plot(d.plot(aspect_ratio=1))\n\n A path representing a Dyck word (either using `N` and `E` steps, or\n using `NE` and `SE` steps) is called a Dyck path.\n\n EXAMPLES::\n\n sage: dw = DyckWord([1, 0, 1, 0]); dw\n [1, 0, 1, 0]\n sage: print(dw)\n ()()\n sage: dw.height()\n 1\n sage: dw.to_noncrossing_partition()\n {{1}, {2}}\n\n ::\n\n sage: DyckWord(\'()()\')\n [1, 0, 1, 0]\n sage: DyckWord(\'(())\')\n [1, 1, 0, 0]\n sage: DyckWord(\'((\')\n [1, 1]\n sage: DyckWord(\'\')\n []\n\n ::\n\n sage: DyckWord(noncrossing_partition=[[1],[2]])\n [1, 0, 1, 0]\n sage: DyckWord(noncrossing_partition=[[1,2]])\n [1, 1, 0, 0]\n sage: DyckWord(noncrossing_partition=[])\n []\n\n ::\n\n sage: DyckWord(area_sequence=[0,0])\n [1, 0, 1, 0]\n sage: DyckWord(area_sequence=[0,1])\n [1, 1, 0, 0]\n sage: DyckWord(area_sequence=[0,1,2,2,0,1,1,2])\n [1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0]\n sage: DyckWord(area_sequence=[])\n []\n\n ::\n\n sage: DyckWord(heights_sequence=(0,1,0,1,0))\n [1, 0, 1, 0]\n sage: DyckWord(heights_sequence=(0,1,2,1,0))\n [1, 1, 0, 0]\n sage: DyckWord(heights_sequence=(0,))\n []\n\n ::\n\n sage: print(DyckWord([1,0,1,1,0,0]).to_path_string())\n /\\\n /\\/ \\\n sage: DyckWord([1,0,1,1,0,0]).pretty_print()\n ___\n | x\n _| .\n | . .\n '
@staticmethod
def __classcall_private__(cls, dw=None, noncrossing_partition=None, area_sequence=None, heights_sequence=None, catalan_code=None):
'\n Return an element with the appropriate parent.\n\n EXAMPLES::\n\n sage: DyckWord([1,0,1,1,0,0])\n [1, 0, 1, 1, 0, 0]\n sage: DyckWord(heights_sequence=(0,1,2,1,0))\n [1, 1, 0, 0]\n sage: DyckWord(noncrossing_partition=[[1],[2]])\n [1, 0, 1, 0]\n '
if (dw is None):
if (catalan_code is not None):
return CompleteDyckWords_all().from_Catalan_code(catalan_code)
if (area_sequence is not None):
return CompleteDyckWords_all().from_area_sequence(area_sequence)
if (noncrossing_partition is not None):
return CompleteDyckWords_all().from_noncrossing_partition(noncrossing_partition)
if (heights_sequence is not None):
if (heights_sequence[(- 1)] == 0):
P = CompleteDyckWords_all()
else:
P = DyckWords_all()
return P.from_heights(heights_sequence)
raise ValueError('you have not specified a Dyck word')
if isinstance(dw, str):
l = [replace_parens(x) for x in dw]
else:
l = dw
if isinstance(l, DyckWord):
return l
if (l in CompleteDyckWords_all()):
return CompleteDyckWords_all()(l)
if is_a(l):
return DyckWords_all()(l)
raise ValueError('invalid Dyck word')
def __init__(self, parent, l, latex_options={}):
'\n TESTS::\n\n sage: DW = DyckWords(complete=False).from_heights((0,))\n sage: TestSuite(DW).run()\n sage: DW = DyckWords(complete=False).min_from_heights((0,))\n sage: TestSuite(DW).run()\n sage: DW = DyckWords().from_Catalan_code([])\n sage: TestSuite(DW).run()\n sage: DW = DyckWords().from_area_sequence([])\n sage: TestSuite(DW).run()\n '
CombinatorialElement.__init__(self, parent, l)
self._latex_options = dict(latex_options)
def set_latex_options(self, D):
'\n Set the latex options for use in the ``_latex_`` function.\n\n The default values are set in the ``__init__`` function.\n\n - ``tikz_scale`` -- (default: 1) scale for use with the tikz package.\n\n - ``diagonal`` -- (default: ``False``) boolean value to draw the\n diagonal or not.\n\n - ``line width`` -- (default: 2*``tikz_scale``) value representing the\n line width.\n\n - ``color`` -- (default: black) the line color.\n\n - ``bounce path`` -- (default: ``False``) boolean value to indicate\n if the bounce path should be drawn.\n\n - ``peaks`` -- (default: ``False``) boolean value to indicate if the\n peaks should be displayed.\n\n - ``valleys`` -- (default: ``False``) boolean value to indicate if the\n valleys should be displayed.\n\n INPUT:\n\n - ``D`` -- a dictionary with a list of latex parameters to change\n\n EXAMPLES::\n\n sage: D = DyckWord([1,0,1,0,1,0])\n sage: D.set_latex_options({"tikz_scale":2})\n sage: D.set_latex_options({"valleys":True, "color":"blue"})\n\n .. TODO::\n\n This should probably be merged into DyckWord.options.\n '
for opt in D:
self._latex_options[opt] = D[opt]
def latex_options(self):
"\n Return the latex options for use in the ``_latex_`` function as a\n dictionary.\n\n The default values are set using the options.\n\n - ``tikz_scale`` -- (default: 1) scale for use with the tikz package.\n\n - ``diagonal`` -- (default: ``False``) boolean value to draw the\n diagonal or not.\n\n - ``line width`` -- (default: 2*``tikz_scale``) value representing the\n line width.\n\n - ``color`` -- (default: black) the line color.\n\n - ``bounce path`` -- (default: ``False``) boolean value to indicate\n if the bounce path should be drawn.\n\n - ``peaks`` -- (default: ``False``) boolean value to indicate if the\n peaks should be displayed.\n\n - ``valleys`` -- (default: ``False``) boolean value to indicate if the\n valleys should be displayed.\n\n EXAMPLES::\n\n sage: D = DyckWord([1,0,1,0,1,0])\n sage: D.latex_options()\n {'bounce path': False,\n 'color': black,\n 'diagonal': False,\n 'line width': 2,\n 'peaks': False,\n 'tikz_scale': 1,\n 'valleys': False}\n\n .. TODO::\n\n This should probably be merged into DyckWord.options.\n "
d = self._latex_options.copy()
if ('tikz_scale' not in d):
d['tikz_scale'] = self.parent().options.latex_tikz_scale
if ('diagonal' not in d):
d['diagonal'] = self.parent().options.latex_diagonal
if ('line width' not in d):
d['line width'] = (self.parent().options.latex_line_width_scalar * d['tikz_scale'])
if ('color' not in d):
d['color'] = self.parent().options.latex_color
if ('bounce path' not in d):
d['bounce path'] = self.parent().options.latex_bounce_path
if ('peaks' not in d):
d['peaks'] = self.parent().options.latex_peaks
if ('valleys' not in d):
d['valleys'] = self.parent().options.latex_valleys
return d
def _repr_(self) -> str:
'\n Return a string representation of ``self`` depending on\n :meth:`DyckWords.options`.\n\n TESTS::\n\n sage: DyckWord([1, 0, 1, 0])\n [1, 0, 1, 0]\n sage: DyckWord([1, 1, 0, 0])\n [1, 1, 0, 0]\n sage: DyckWords.options.display="lattice"\n sage: DyckWords.options.diagram_style="line"\n sage: DyckWord([1, 0, 1, 0])\n /\\/\\\n sage: DyckWord([1, 1, 0, 0])\n /\\\n / \\\n sage: DyckWords.options._reset()\n '
return self.parent().options._dispatch(self, '_repr_', 'display')
def _repr_list(self) -> str:
"\n Return a string representation of ``self`` as a list.\n\n TESTS::\n\n sage: DyckWord([])\n []\n sage: DyckWord([1, 0])\n [1, 0]\n sage: DyckWord('(())')\n [1, 1, 0, 0]\n "
return super()._repr_()
def _repr_lattice(self, type=None, labelling=None, underpath=True) -> str:
'\n See :meth:`pretty_print()`.\n\n TESTS::\n\n sage: print(DyckWord(area_sequence=[0,1,0])._repr_lattice(type="NE-SE"))\n /\\\n / \\/\\\n sage: print(DyckWord(area_sequence=[0,1,0])._repr_lattice(labelling=[1,3,2],underpath=False))\n _\n ___| 2\n | x . 3\n | . . 1\n '
if (type is None):
type = self.parent().options.diagram_style
if (type == 'grid'):
type = 'N-E'
elif (type == 'line'):
type = 'NE-SE'
if (type == 'NE-SE'):
if ((labelling is not None) or (underpath is not True)):
raise ValueError('the labelling cannot be shown with Northeast-Southeast paths')
return self.to_path_string()
elif (type == 'N-E'):
alst = self.to_area_sequence()
n = len(alst)
if (n == 0):
return '.\n'
if (labelling is None):
labels = ([' '] * n)
else:
if (len(labelling) != n):
raise ValueError('the given labelling has the wrong length')
labels = [str(label) for label in labelling]
if (not underpath):
max_length = max((len(label) for label in labels))
labels = [lbl.rjust((max_length + 1)) for lbl in labels]
length_of_final_fall = list(reversed(self)).index(open_symbol)
if (length_of_final_fall == 0):
final_fall = ' '
else:
final_fall = (' _' + ('__' * (length_of_final_fall - 1)))
row = (((' ' * ((n - alst[(- 1)]) - 1)) + final_fall) + '\n')
for i in range((n - 1)):
c = 0
row = (row + (' ' * (((n - i) - 2) - alst[((- i) - 2)])))
c += (((n - i) - 2) - alst[((- i) - 2)])
if ((alst[((- i) - 2)] + 1) != alst[((- i) - 1)]):
row += ' _'
c += (alst[((- i) - 2)] - alst[((- i) - 1)])
if underpath:
row += (((((('__' * (alst[((- i) - 2)] - alst[((- i) - 1)])) + '|') + labels[(- 1)]) + ('x ' * (((n - c) - 2) - i))) + (' .' * i)) + '\n')
else:
row += (((((('__' * (alst[((- i) - 2)] - alst[((- i) - 1)])) + '| ') + ('x ' * (((n - c) - 2) - i))) + (' .' * i)) + labels[(- 1)]) + '\n')
labels.pop()
if underpath:
row += ((('|' + labels[(- 1)]) + (' .' * (n - 1))) + '\n')
else:
row += ((('| ' + (' .' * (n - 1))) + labels[(- 1)]) + '\n')
return row
else:
raise ValueError(('the given type (=%s) is not valid' % type))
def _ascii_art_(self):
'\n Return an ASCII art representation of ``self``.\n\n TESTS::\n\n sage: ascii_art(list(DyckWords(3)))\n [ /\\ ]\n [ /\\ /\\ /\\/\\ / \\ ]\n [ /\\/\\/\\, /\\/ \\, / \\/\\, / \\, / \\ ]\n '
from sage.typeset.ascii_art import AsciiArt
rep = self.parent().options.ascii_art
if (rep == 'path'):
ret = self.to_path_string()
elif (rep == 'pretty_output'):
ret = self._repr_lattice()
return AsciiArt(ret.splitlines(), baseline=0)
def _unicode_art_(self):
'\n Return an unicode art representation of this Dyck word.\n\n EXAMPLES::\n\n sage: unicode_art(list(DyckWords(3)))\n ⎡ ╱╲ ⎤\n ⎢ ╱╲ ╱╲ ╱╲╱╲ ╱ ╲ ⎥\n ⎣ ╱╲╱╲╱╲, ╱╲╱ ╲, ╱ ╲╱╲, ╱ ╲, ╱ ╲ ⎦\n '
from sage.typeset.unicode_art import UnicodeArt
return UnicodeArt(self.to_path_string(unicode=True).splitlines())
def __str__(self) -> str:
'\n Return a string consisting of matched parentheses corresponding to\n the Dyck word.\n\n EXAMPLES::\n\n sage: print(DyckWord([1, 0, 1, 0]))\n ()()\n sage: print(DyckWord([1, 1, 0, 0]))\n (())\n '
return ''.join((replace_symbols(x) for x in self))
def to_path_string(self, unicode=False) -> str:
'\n Return a path representation of the Dyck word consisting of steps\n ``/`` and ``\\`` .\n\n INPUT:\n\n - ``unicode`` -- boolean (default ``False``) whether to use unicode\n\n EXAMPLES::\n\n sage: print(DyckWord([1, 0, 1, 0]).to_path_string())\n /\\/\\\n sage: print(DyckWord([1, 1, 0, 0]).to_path_string())\n /\\\n / \\\n sage: print(DyckWord([1,1,0,1,1,0,0,1,0,1,0,0]).to_path_string())\n /\\\n /\\/ \\/\\/\\\n / \\\n '
if unicode:
import unicodedata
space = ' '
up = unicodedata.lookup('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')
down = unicodedata.lookup('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT')
else:
space = ' '
up = '/'
down = '\\'
res = [([space] * len(self)) for _ in range(self.height())]
h = 1
for (i, p) in enumerate(self):
if (p == open_symbol):
res[(- h)][i] = up
h += 1
else:
h -= 1
res[(- h)][i] = down
return '\n'.join((''.join(l) for l in res))
def pretty_print(self, type=None, labelling=None, underpath=True):
'\n Display a DyckWord as a lattice path in the `\\ZZ^2` grid.\n\n If the ``type`` is "N-E", then a cell below the diagonal is\n indicated by a period, whereas a cell below the path but above\n the diagonal is indicated by an x. If a list of labels is\n included, they are displayed along the vertical edges of the\n Dyck path.\n\n If the ``type`` is "NE-SE", then the path is simply printed\n as up steps and down steps.\n\n INPUT:\n\n - ``type`` -- (default: ``None``) can either be:\n\n - ``None`` to use the option default\n - "N-E" to show ``self`` as a path of north and east steps, or\n - "NE-SE" to show ``self`` as a path of north-east and\n south-east steps.\n\n - ``labelling`` -- (if type is "N-E") a list of labels assigned to\n the up steps in ``self``.\n\n - ``underpath`` -- (if type is "N-E", default:``True``) If ``True``,\n the labelling is shown under the path; otherwise, it is shown to\n the right of the path.\n\n EXAMPLES::\n\n sage: for D in DyckWords(3): D.pretty_print()\n _\n _|\n _| .\n | . .\n ___\n | x\n _| .\n | . .\n _\n ___|\n | x .\n | . .\n ___\n _| x\n | x .\n | . .\n _____\n | x x\n | x .\n | . .\n\n ::\n\n sage: for D in DyckWords(3): D.pretty_print(type="NE-SE")\n /\\/\\/\\\n /\\\n /\\/ \\\n /\\\n / \\/\\\n /\\/\\\n / \\\n /\\\n / \\\n / \\\n\n ::\n\n sage: D = DyckWord([1,1,1,0,1,0,0,1,1])\n sage: D.pretty_print()\n | x x\n ___| x .\n _| x x . .\n | x x . . .\n | x . . . .\n | . . . . .\n\n sage: D = DyckWord([1,1,1,0,1,0,0,1,1,0])\n sage: D.pretty_print()\n _\n | x x\n ___| x .\n _| x x . .\n | x x . . .\n | x . . . .\n | . . . . .\n\n sage: D = DyckWord([1,1,1,0,1,0,0,1,1,0,0])\n sage: D.pretty_print()\n ___\n | x x\n ___| x .\n _| x x . .\n | x x . . .\n | x . . . .\n | . . . . .\n\n ::\n\n sage: DyckWord(area_sequence=[0,1,0]).pretty_print(labelling=[1,3,2])\n _\n ___|2\n |3x .\n |1 . .\n\n sage: DyckWord(area_sequence=[0,1,0]).pretty_print(labelling=[1,3,2],underpath=False)\n _\n ___| 2\n | x . 3\n | . . 1\n\n ::\n\n sage: DyckWord(area_sequence=[0,1,1,2,3,2,3,3,2,0,1,1,2,3,4,2,3]).pretty_print()\n _______\n | x x x\n _____| x x .\n | x x x x . .\n | x x x . . .\n | x x . . . .\n _| x . . . . .\n | x . . . . . .\n _____| . . . . . . .\n ___| x x . . . . . . . .\n _| x x x . . . . . . . . .\n | x x x . . . . . . . . . .\n ___| x x . . . . . . . . . . .\n | x x x . . . . . . . . . . . .\n | x x . . . . . . . . . . . . .\n _| x . . . . . . . . . . . . . .\n | x . . . . . . . . . . . . . . .\n | . . . . . . . . . . . . . . . .\n\n sage: DyckWord(area_sequence=[0,1,1,2,3,2,3,3,2,0,1,1,2,3,4,2,3]).pretty_print(labelling=list(range(17)),underpath=False)\n _______\n | x x x 16\n _____| x x . 15\n | x x x x . . 14\n | x x x . . . 13\n | x x . . . . 12\n _| x . . . . . 11\n | x . . . . . . 10\n _____| . . . . . . . 9\n ___| x x . . . . . . . . 8\n _| x x x . . . . . . . . . 7\n | x x x . . . . . . . . . . 6\n ___| x x . . . . . . . . . . . 5\n | x x x . . . . . . . . . . . . 4\n | x x . . . . . . . . . . . . . 3\n _| x . . . . . . . . . . . . . . 2\n | x . . . . . . . . . . . . . . . 1\n | . . . . . . . . . . . . . . . . 0\n\n ::\n\n sage: DyckWord([]).pretty_print()\n .\n '
print(self._repr_lattice(type, labelling, underpath))
pp = pretty_print
def _latex_(self) -> str:
'\n A latex representation of ``self`` using the tikzpicture package.\n\n EXAMPLES::\n\n sage: D = DyckWord([1,0,1,1,1,0,1,1,0,0,0,1,0,0])\n sage: D.set_latex_options({"valleys":True, "peaks":True, "bounce path":True})\n sage: latex(D)\n \\vcenter{\\hbox{$\\begin{tikzpicture}[scale=1]\n \\draw[line width=2,color=red,fill=red] (2, 0) circle (0.21);\n \\draw[line width=2,color=red,fill=red] (6, 2) circle (0.21);\n \\draw[line width=2,color=red,fill=red] (11, 1) circle (0.21);\n \\draw[line width=2,color=red,fill=red] (1, 1) circle (0.21);\n \\draw[line width=2,color=red,fill=red] (5, 3) circle (0.21);\n \\draw[line width=2,color=red,fill=red] (8, 4) circle (0.21);\n \\draw[line width=2,color=red,fill=red] (12, 2) circle (0.21);\n \\draw[rounded corners=1, color=green, line width=4] (0, 0) -- (1, 1) -- (2, 0) -- (3, 1) -- (4, 0) -- (5, 1) -- (6, 2) -- (7, 3) -- (8, 2) -- (9, 1) -- (10, 0) -- (11, 1) -- (12, 2) -- (13, 1) -- (14, 0);\n \\draw[dotted] (0, 0) grid (14, 4);\n \\draw[rounded corners=1, color=black, line width=2] (0, 0) -- (1, 1) -- (2, 0) -- (3, 1) -- (4, 2) -- (5, 3) -- (6, 2) -- (7, 3) -- (8, 4) -- (9, 3) -- (10, 2) -- (11, 1) -- (12, 2) -- (13, 1) -- (14, 0);\n \\end{tikzpicture}$}}\n sage: DyckWord([1,0])._latex_()\n \'\\\\vcenter{\\\\hbox{$\\\\begin{tikzpicture}[scale=1]\\n \\\\draw[dotted] (0, 0) grid (2, 1);\\n \\\\draw[rounded corners=1, color=black, line width=2] (0, 0) -- (1, 1) -- (2, 0);\\n\\\\end{tikzpicture}$}}\'\n sage: DyckWord([1,0,1,1,0,0])._latex_()\n \'\\\\vcenter{\\\\hbox{$\\\\begin{tikzpicture}[scale=1]\\n \\\\draw[dotted] (0, 0) grid (6, 2);\\n \\\\draw[rounded corners=1, color=black, line width=2] (0, 0) -- (1, 1) -- (2, 0) -- (3, 1) -- (4, 2) -- (5, 1) -- (6, 0);\\n\\\\end{tikzpicture}$}}\'\n '
latex.add_package_to_preamble_if_available('tikz')
heights = self.heights()
latex_options = self.latex_options()
diagonal = latex_options['diagonal']
ht = [(0, 0)]
valleys = []
peaks = []
for i in range(1, len(heights)):
(a, b) = ht[(- 1)]
if (heights[i] > heights[(i - 1)]):
if diagonal:
ht.append((a, (b + 1)))
else:
ht.append(((a + 1), (b + 1)))
if ((i < (len(heights) - 1)) and (heights[(i + 1)] < heights[i])):
peaks.append(ht[(- 1)])
else:
if diagonal:
ht.append(((a + 1), b))
else:
ht.append(((a + 1), (b - 1)))
if ((i < (len(heights) - 1)) and (heights[(i + 1)] > heights[i])):
valleys.append(ht[(- 1)])
hti = iter(ht)
if diagonal:
grid = [((0, i), (i, (i + 1))) for i in range(self.number_of_open_symbols())]
else:
grid = [((0, 0), (len(self), self.height()))]
res = (('\\vcenter{\\hbox{$\\begin{tikzpicture}[scale=' + str(latex_options['tikz_scale'])) + ']\n')
mark_points = []
if latex_options['valleys']:
mark_points.extend(valleys)
if latex_options['peaks']:
mark_points.extend(peaks)
for v in mark_points:
res += (' \\draw[line width=2,color=red,fill=red] %s circle (%s);\n' % (str(v), (0.15 + (0.03 * latex_options['line width']))))
if latex_options['bounce path']:
D = self.bounce_path()
D.set_latex_options(latex_options)
D.set_latex_options({'color': 'green', 'line width': (2 * latex_options['line width']), 'bounce path': False, 'peaks': False, 'valleys': False})
res += (D._latex_().split('\n')[(- 2)] + '\n')
for (v1, v2) in grid:
res += (' \\draw[dotted] %s grid %s;\n' % (str(v1), str(v2)))
if diagonal:
res += (' \\draw (0,0) -- %s;\n' % str((self.number_of_open_symbols(), self.number_of_open_symbols())))
res += (' \\draw[rounded corners=1, color=%s, line width=%s] (0, 0)' % (latex_options['color'], str(latex_options['line width'])))
next(hti)
for (i, j) in hti:
res += (' -- (%s, %s)' % (i, j))
res += ';\n'
res += '\\end{tikzpicture}$}}'
return res
def _repr_svg_(self) -> str:
"\n Return the svg picture of ``self``.\n\n This can be displayed by Jupyter.\n\n EXAMPLES::\n\n sage: PP = DyckWords(6).random_element()\n sage: PP._repr_svg_()\n '<?xml...</g></svg>'\n "
N = self.length()
width = (0.1 if (N < 20) else (N / 200))
resu = '<?xml version="1.0" standalone="no"?>'
resu += '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
resu += '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'
resu += '<svg xmlns="http://www.w3.org/2000/svg" '
resu += 'xmlns:xlink="http://www.w3.org/1999/xlink" width="500" viewBox='
resu1 = '<g style="stroke-width:{};stroke-linejoin:bevel; '.format(width)
resu1 += 'stroke-linecap:butt; stroke:black; fill:snow">'
resu3 = '<g style="stroke-width:{};stroke-linejoin:bevel;stroke-dasharray:0.25; '.format((width / 2))
resu3 += 'stroke-linecap:butt; stroke:gray; fill:none">'
horizontal = '<line x1="{}" y1="{}" x2="{}" y2="{}"/>'
hori_lines = []
path = ['<polyline points="0,0']
(x, y) = (0, 0)
max_y = 0
last_seen_level = [0]
for e in self:
x += 1
if (e == open_symbol):
y += 1
last_seen_level.append((x - 1))
max_y = max(max_y, y)
else:
y -= 1
old_x = last_seen_level.pop()
hori_lines.append(horizontal.format(old_x, (- y), x, (- y)))
path.append(f'{x},{(- y)}')
path.append('"/>')
path.append('</g>')
resu1 += ' '.join(path)
hori_lines.append('</g></svg>')
resu3 += ''.join(hori_lines)
margin = (2 * width)
resu += '"{} {} {} {} ">'.format((- margin), ((- max_y) - margin), (N + (2 * margin)), (max_y + (2 * margin)))
return ((resu + resu1) + resu3)
def plot(self, **kwds):
'\n Plot a Dyck word as a continuous path.\n\n EXAMPLES::\n\n sage: w = DyckWords(100).random_element()\n sage: w.plot() # needs sage.plot\n Graphics object consisting of 1 graphics primitive\n '
from sage.plot.plot import list_plot
step = [(- 1), 1]
sigma = 0
list_sigma = [0]
for l in self:
sigma += step[l]
list_sigma.append(sigma)
return list_plot(list_sigma, plotjoined=True, **kwds)
def length(self) -> int:
'\n Return the length of ``self``.\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).length()\n 4\n sage: DyckWord([1, 0, 1, 1, 0]).length()\n 5\n\n TESTS::\n\n sage: DyckWord([]).length()\n 0\n '
return len(self)
def number_of_open_symbols(self) -> int:
'\n Return the number of open symbols in ``self``.\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).number_of_open_symbols()\n 2\n sage: DyckWord([1, 0, 1, 1, 0]).number_of_open_symbols()\n 3\n\n TESTS::\n\n sage: DyckWord([]).number_of_open_symbols()\n 0\n '
return len([x for x in self if (x == open_symbol)])
def number_of_close_symbols(self) -> int:
'\n Return the number of close symbols in ``self``.\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).number_of_close_symbols()\n 2\n sage: DyckWord([1, 0, 1, 1, 0]).number_of_close_symbols()\n 2\n\n TESTS::\n\n sage: DyckWord([]).number_of_close_symbols()\n 0\n '
return len([x for x in self if (x == close_symbol)])
def is_complete(self) -> bool:
'\n Return ``True`` if ``self`` is complete.\n\n A Dyck word `d` is complete if `d` contains as many closers as openers.\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).is_complete()\n True\n sage: DyckWord([1, 0, 1, 1, 0]).is_complete()\n False\n\n TESTS::\n\n sage: DyckWord([]).is_complete()\n True\n '
return (self.number_of_open_symbols() == self.number_of_close_symbols())
def height(self) -> int:
"\n Return the height of ``self``.\n\n We view the Dyck word as a Dyck path from `(0, 0)` to\n `(2n, 0)` in the first quadrant by letting ``1``'s represent\n steps in the direction `(1, 1)` and ``0``'s represent steps in\n the direction `(1, -1)`.\n\n The height is the maximum `y`-coordinate reached.\n\n .. SEEALSO:: :meth:`heights`\n\n EXAMPLES::\n\n sage: DyckWord([]).height()\n 0\n sage: DyckWord([1,0]).height()\n 1\n sage: DyckWord([1, 1, 0, 0]).height()\n 2\n sage: DyckWord([1, 1, 0, 1, 0]).height()\n 2\n sage: DyckWord([1, 1, 0, 0, 1, 0]).height()\n 2\n sage: DyckWord([1, 0, 1, 0]).height()\n 1\n sage: DyckWord([1, 1, 0, 0, 1, 1, 1, 0, 0, 0]).height()\n 3\n "
height = 0
height_max = 0
for letter in self:
if (letter == open_symbol):
height += 1
height_max = max(height, height_max)
elif (letter == close_symbol):
height -= 1
return height_max
def heights(self) -> tuple:
"\n Return the heights of ``self``.\n\n We view the Dyck word as a Dyck path from `(0,0)` to\n `(2n,0)` in the first quadrant by letting ``1``'s represent\n steps in the direction `(1,1)` and ``0``'s represent steps in\n the direction `(1,-1)`.\n\n The heights is the sequence of the `y`-coordinates of all\n `2n+1` lattice points along the path.\n\n .. SEEALSO:: :meth:`~DyckWords.from_heights`, :meth:`~DyckWords.min_from_heights`\n\n EXAMPLES::\n\n sage: DyckWord([]).heights()\n (0,)\n sage: DyckWord([1,0]).heights()\n (0, 1, 0)\n sage: DyckWord([1, 1, 0, 0]).heights()\n (0, 1, 2, 1, 0)\n sage: DyckWord([1, 1, 0, 1, 0]).heights()\n (0, 1, 2, 1, 2, 1)\n sage: DyckWord([1, 1, 0, 0, 1, 0]).heights()\n (0, 1, 2, 1, 0, 1, 0)\n sage: DyckWord([1, 0, 1, 0]).heights()\n (0, 1, 0, 1, 0)\n sage: DyckWord([1, 1, 0, 0, 1, 1, 1, 0, 0, 0]).heights()\n (0, 1, 2, 1, 0, 1, 2, 3, 2, 1, 0)\n "
height = 0
heights = ([0] * (len(self) + 1))
for (i, letter) in enumerate(self):
if (letter == open_symbol):
height += 1
elif (letter == close_symbol):
height -= 1
heights[(i + 1)] = height
return tuple(heights)
def associated_parenthesis(self, pos) -> (int | None):
'\n Report the position for the parenthesis in ``self`` that matches the\n one at position ``pos``.\n\n The positions in ``self`` are counted from `0`.\n\n INPUT:\n\n - ``pos`` -- the index of the parenthesis in the list\n\n OUTPUT:\n\n - Integer representing the index of the matching parenthesis.\n If no parenthesis matches, return ``None``.\n\n EXAMPLES::\n\n sage: DyckWord([1, 0]).associated_parenthesis(0)\n 1\n sage: DyckWord([1, 0, 1, 0]).associated_parenthesis(0)\n 1\n sage: DyckWord([1, 0, 1, 0]).associated_parenthesis(1)\n 0\n sage: DyckWord([1, 0, 1, 0]).associated_parenthesis(2)\n 3\n sage: DyckWord([1, 0, 1, 0]).associated_parenthesis(3)\n 2\n sage: DyckWord([1, 1, 0, 0]).associated_parenthesis(0)\n 3\n sage: DyckWord([1, 1, 0, 0]).associated_parenthesis(2)\n 1\n sage: DyckWord([1, 1, 0]).associated_parenthesis(1)\n 2\n sage: DyckWord([1, 1]).associated_parenthesis(0)\n '
d = 0
height = 0
if (pos >= len(self)):
raise ValueError('invalid index')
if (self[pos] == open_symbol):
d += 1
height += 1
elif (self[pos] == close_symbol):
d -= 1
height -= 1
else:
raise ValueError(('unknown symbol %s' % self[pos]))
while (height != 0):
pos += d
if ((pos < 0) or (pos >= len(self))):
return None
if (self[pos] == open_symbol):
height += 1
elif (self[pos] == close_symbol):
height -= 1
return pos
def ascent_prime_decomposition(self) -> list[DyckWord]:
'\n Decompose this Dyck word into a sequence of ascents and prime\n Dyck paths.\n\n A Dyck word is *prime* if it is complete and has precisely\n one return - the final step. In particular, the empty Dyck\n path is not prime. Thus, the factorization is unique.\n\n This decomposition yields a sequence of odd length: the words\n with even indices consist of up steps only, the words with\n odd indices are prime Dyck paths. The concatenation of the\n result is the original word.\n\n EXAMPLES::\n\n sage: D = DyckWord([1,1,1,0,1,0,1,1,1,1,0,1])\n sage: D.ascent_prime_decomposition()\n [[1, 1], [1, 0], [], [1, 0], [1, 1, 1], [1, 0], [1]]\n\n sage: DyckWord([]).ascent_prime_decomposition()\n [[]]\n\n sage: DyckWord([1,1]).ascent_prime_decomposition()\n [[1, 1]]\n\n sage: DyckWord([1,0,1,0]).ascent_prime_decomposition()\n [[], [1, 0], [], [1, 0], []]\n\n '
n = self.length()
H = self.heights()
result = []
i = 0
height = 0
up = 0
while (i < n):
j = (i + 1)
while (H[j] != height):
if (j == n):
i += 1
height += 1
up += 1
break
j += 1
else:
result.extend([DyckWord(([open_symbol] * up)), DyckWord(self[i:j])])
i = j
up = 0
result.append(DyckWord(([open_symbol] * up)))
return result
def catalan_factorization(self) -> list[DyckWord]:
'\n Decompose this Dyck word into a sequence of complete Dyck\n words.\n\n Each element of the list returned is a (possibly empty)\n complete Dyck word. The original word is obtained by placing\n an up step between each of these complete Dyck words. Thus,\n the number of words returned is one more than the final height.\n\n See Section 1.2 of [CC1982]_ or Lemma 9.1.1 of [Lot2005]_.\n\n EXAMPLES::\n\n sage: D = DyckWord([1,1,1,0,1,0,1,1,1,1,0,1])\n sage: D.catalan_factorization()\n [[], [], [1, 0, 1, 0], [], [], [1, 0], []]\n\n sage: DyckWord([]).catalan_factorization()\n [[]]\n\n sage: DyckWord([1,1]).catalan_factorization()\n [[], [], []]\n\n sage: DyckWord([1,0,1,0]).catalan_factorization()\n [[1, 0, 1, 0]]\n '
H = self.heights()
h = 0
i = 0
j = n = self.length()
result = []
while (i <= n):
if ((H[j] == h) or (j == i)):
result.append(DyckWord(self[i:j]))
h += 1
i = (j + 1)
j = n
else:
j -= 1
return result
def number_of_initial_rises(self) -> int:
'\n Return the length of the initial run of ``self``.\n\n OUTPUT:\n\n - a non--negative integer indicating the length of the initial rise\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).number_of_initial_rises()\n 1\n sage: DyckWord([1, 1, 0, 0]).number_of_initial_rises()\n 2\n sage: DyckWord([1, 1, 0, 0, 1, 0]).number_of_initial_rises()\n 2\n sage: DyckWord([1, 0, 1, 1, 0, 0]).number_of_initial_rises()\n 1\n\n TESTS::\n\n sage: DyckWord([]).number_of_initial_rises()\n 0\n sage: DyckWord([1, 0]).number_of_initial_rises()\n 1\n '
if (not self):
return 0
i = 1
while (self[i] == open_symbol):
i += 1
return i
def peaks(self) -> list:
"\n Return a list of the positions of the peaks of a Dyck word.\n\n A peak is `1` followed by a `0`. Note that this does not agree with\n the definition given in [Hag2008]_.\n\n .. SEEALSO:: :meth:`valleys`, :meth:`number_of_peaks`\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).peaks()\n [0, 2]\n sage: DyckWord([1, 1, 0, 0]).peaks()\n [1]\n sage: DyckWord([1,1,0,1,0,1,0,0]).peaks() # Haglund's def gives 2\n [1, 3, 5]\n "
return [i for i in range((len(self) - 1)) if ((self[i] == open_symbol) and (self[(i + 1)] == close_symbol))]
def number_of_peaks(self) -> int:
'\n Return the number of peaks of the Dyck path associated to ``self`` .\n\n .. SEEALSO:: :meth:`peaks`, :meth:`number_of_valleys`\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).number_of_peaks()\n 2\n sage: DyckWord([1, 1, 0, 0]).number_of_peaks()\n 1\n sage: DyckWord([1,1,0,1,0,1,0,0]).number_of_peaks()\n 3\n sage: DyckWord([]).number_of_peaks()\n 0\n '
return len(self.peaks())
def valleys(self) -> list:
'\n Return a list of the positions of the valleys of a Dyck word.\n\n A valley is `0` followed by a `1`.\n\n .. SEEALSO:: :meth:`peaks`, :meth:`number_of_valleys`\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).valleys()\n [1]\n sage: DyckWord([1, 1, 0, 0]).valleys()\n []\n sage: DyckWord([1,1,0,1,0,1,0,0]).valleys()\n [2, 4]\n '
return [i for i in range((len(self) - 1)) if ((self[i] == close_symbol) and (self[(i + 1)] == open_symbol))]
def number_of_valleys(self) -> int:
'\n Return the number of valleys of ``self``.\n\n .. SEEALSO:: :meth:`number_of_peaks`, :meth:`valleys`\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).number_of_valleys()\n 1\n sage: DyckWord([1, 1, 0, 0]).number_of_valleys()\n 0\n sage: DyckWord([1, 1, 0, 0, 1, 0]).number_of_valleys()\n 1\n sage: DyckWord([1, 0, 1, 1, 0, 0]).number_of_valleys()\n 1\n\n TESTS::\n\n sage: DyckWord([]).number_of_valleys()\n 0\n sage: DyckWord([1, 0]).number_of_valleys()\n 0\n '
return len(self.valleys())
def position_of_first_return(self) -> int:
'\n Return the number of vertical steps before the Dyck path returns to\n the main diagonal.\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0]).position_of_first_return()\n 1\n sage: DyckWord([1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0]).position_of_first_return()\n 7\n sage: DyckWord([1, 1, 0, 0]).position_of_first_return()\n 2\n sage: DyckWord([1, 0, 1, 0]).position_of_first_return()\n 1\n sage: DyckWord([]).position_of_first_return()\n 0\n '
touches = self.touch_points()
if (not touches):
return 0
else:
return touches[0]
def positions_of_double_rises(self) -> list:
"\n Return a list of positions in ``self`` where there are two\n consecutive `1`'s.\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0]).positions_of_double_rises()\n [2, 5]\n sage: DyckWord([1, 1, 0, 0]).positions_of_double_rises()\n [0]\n sage: DyckWord([1, 0, 1, 0]).positions_of_double_rises()\n []\n "
return [i for i in range((len(self) - 1)) if (self[i] == self[(i + 1)] == open_symbol)]
def number_of_double_rises(self) -> int:
"\n Return a the number of positions in ``self`` where there are two\n consecutive `1`'s.\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0]).number_of_double_rises()\n 2\n sage: DyckWord([1, 1, 0, 0]).number_of_double_rises()\n 1\n sage: DyckWord([1, 0, 1, 0]).number_of_double_rises()\n 0\n "
return len(self.positions_of_double_rises())
def returns_to_zero(self) -> list[int]:
'\n Return a list of positions where ``self`` has height `0`,\n excluding the position `0`.\n\n EXAMPLES::\n\n sage: DyckWord([]).returns_to_zero()\n []\n sage: DyckWord([1, 0]).returns_to_zero()\n [2]\n sage: DyckWord([1, 0, 1, 0]).returns_to_zero()\n [2, 4]\n sage: DyckWord([1, 1, 0, 0]).returns_to_zero()\n [4]\n '
height = 0
points = []
for (i, letter) in enumerate(self):
if (letter == open_symbol):
height += 1
elif (letter == close_symbol):
height -= 1
if (not height):
points.append((i + 1))
return points
def touch_points(self) -> list[int]:
'\n Return the abscissae (or, equivalently, ordinates) of the\n points where the Dyck path corresponding to ``self`` (comprising\n `NE` and `SE` steps) touches the main diagonal. This includes\n the last point (if it is on the main diagonal) but excludes the\n beginning point.\n\n Note that these abscissae are precisely the entries of\n :meth:`returns_to_zero` divided by `2`.\n\n OUTPUT:\n\n - a list of integers indicating where the path touches the diagonal\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).touch_points()\n [1, 2]\n sage: DyckWord([1, 1, 0, 0]).touch_points()\n [2]\n sage: DyckWord([1, 1, 0, 0, 1, 0]).touch_points()\n [2, 3]\n sage: DyckWord([1, 0, 1, 1, 0, 0]).touch_points()\n [1, 3]\n '
return [(i // 2) for i in self.returns_to_zero()]
def touch_composition(self):
'\n Return a composition which indicates the positions where ``self``\n returns to the diagonal.\n\n This assumes ``self`` to be a complete Dyck word.\n\n OUTPUT:\n\n - a composition of length equal to the length of the Dyck word.\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).touch_composition()\n [1, 1]\n sage: DyckWord([1, 1, 0, 0]).touch_composition()\n [2]\n sage: DyckWord([1, 1, 0, 0, 1, 0]).touch_composition()\n [2, 1]\n sage: DyckWord([1, 0, 1, 1, 0, 0]).touch_composition()\n [1, 2]\n sage: DyckWord([]).touch_composition()\n []\n '
from sage.combinat.composition import Composition
if (not self):
return Composition([])
return Composition(descents=[(i - 1) for i in self.touch_points()])
def number_of_touch_points(self) -> int:
'\n Return the number of touches of ``self`` at the main diagonal.\n\n OUTPUT:\n\n - a non--negative integer\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).number_of_touch_points()\n 2\n sage: DyckWord([1, 1, 0, 0]).number_of_touch_points()\n 1\n sage: DyckWord([1, 1, 0, 0, 1, 0]).number_of_touch_points()\n 2\n sage: DyckWord([1, 0, 1, 1, 0, 0]).number_of_touch_points()\n 2\n\n TESTS::\n\n sage: DyckWord([]).number_of_touch_points()\n 0\n '
return len(self.returns_to_zero())
def rise_composition(self):
"\n The sequences of lengths of runs of `1`'s in ``self``. Also equal to\n the sequence of lengths of vertical segments in the Dyck path.\n\n EXAMPLES::\n\n sage: DyckWord([1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0]).pretty_print()\n ___\n | x\n _______| .\n | x x x . .\n | x x . . .\n _| x . . . .\n | x . . . . .\n | . . . . . .\n\n sage: DyckWord([1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0]).rise_composition()\n [2, 3, 2]\n sage: DyckWord([1,1,0,0]).rise_composition()\n [2]\n sage: DyckWord([1,0,1,0]).rise_composition()\n [1, 1]\n "
from sage.combinat.composition import Composition
L = list(self)
rise_comp = []
while L:
i = L.index(0)
L = L[(i + 1):]
if i:
rise_comp.append(i)
return Composition(rise_comp)
@combinatorial_map(name='to two-row standard tableau')
def to_standard_tableau(self):
'\n Return a standard tableau of shape `(a,b)` where\n `a` is the number of open symbols and `b` is the number of\n close symbols in ``self``.\n\n EXAMPLES::\n\n sage: DyckWord([]).to_standard_tableau()\n []\n sage: DyckWord([1, 0]).to_standard_tableau()\n [[1], [2]]\n sage: DyckWord([1, 1, 0, 0]).to_standard_tableau()\n [[1, 2], [3, 4]]\n sage: DyckWord([1, 0, 1, 0]).to_standard_tableau()\n [[1, 3], [2, 4]]\n sage: DyckWord([1]).to_standard_tableau()\n [[1]]\n sage: DyckWord([1, 0, 1]).to_standard_tableau()\n [[1, 3], [2]]\n '
open_positions = []
close_positions = []
for i in range(len(self)):
if (self[i] == open_symbol):
open_positions.append((i + 1))
else:
close_positions.append((i + 1))
from sage.combinat.tableau import StandardTableau
return StandardTableau([x for x in [open_positions, close_positions] if x])
def to_tamari_sorting_tuple(self) -> list[int]:
'\n Convert a Dyck word to a Tamari sorting tuple.\n\n The result is a list of integers, one for every up-step from\n left to right. To each up-step is associated\n the distance to the corresponding down step in the Dyck word.\n\n This is useful for a faster conversion to binary trees.\n\n EXAMPLES::\n\n sage: DyckWord([]).to_tamari_sorting_tuple()\n []\n sage: DyckWord([1, 0]).to_tamari_sorting_tuple()\n [0]\n sage: DyckWord([1, 1, 0, 0]).to_tamari_sorting_tuple()\n [1, 0]\n sage: DyckWord([1, 0, 1, 0]).to_tamari_sorting_tuple()\n [0, 0]\n sage: DyckWord([1, 1, 0, 1, 0, 0]).to_tamari_sorting_tuple()\n [2, 0, 0]\n\n .. SEEALSO:: :meth:`~DyckWord_complete.to_Catalan_code`\n '
position = 0
resu = [((- i) - 1) for i in range((len(self) // 2))]
indices_of_active_ups = []
for letter in self:
if (letter == open_symbol):
indices_of_active_ups.append(position)
position += 1
else:
previous = indices_of_active_ups.pop()
resu[previous] += position
return resu
@combinatorial_map(name='to binary trees: up step, left tree, down step, right tree')
def to_binary_tree(self, usemap='1L0R'):
'\n Return a binary tree recursively constructed from the Dyck path\n ``self`` by the map ``usemap``. The default ``usemap`` is ``\'1L0R\'``\n which means:\n\n - an empty Dyck word is a leaf,\n\n - a non empty Dyck word reads `1 L 0 R` where `L` and `R` correspond\n to respectively its left and right subtrees.\n\n INPUT:\n\n - ``usemap`` -- a string, either ``\'1L0R\'``, ``\'1R0L\'``, ``\'L1R0\'``,\n ``\'R1L0\'``\n\n Other valid ``usemap`` are ``\'1R0L\'``, ``\'L1R0\'``, and ``\'R1L0\'``.\n These correspond to different maps from Dyck paths to binary\n trees, whose recursive definitions are hopefully clear from the\n names.\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: dw = DyckWord([1,0])\n sage: dw.to_binary_tree()\n [., .]\n sage: dw = DyckWord([])\n sage: dw.to_binary_tree()\n .\n sage: dw = DyckWord([1,0,1,1,0,0])\n sage: dw.to_binary_tree()\n [., [[., .], .]]\n sage: dw.to_binary_tree("L1R0")\n [[., .], [., .]]\n sage: dw = DyckWord([1,0,1,1,0,0,1,1,1,0,1,0,0,0])\n sage: dw.to_binary_tree() == dw.to_binary_tree("1R0L").left_right_symmetry()\n True\n sage: dw.to_binary_tree() == dw.to_binary_tree("L1R0").left_border_symmetry()\n False\n sage: dw.to_binary_tree("1R0L") == dw.to_binary_tree("L1R0").left_border_symmetry()\n True\n sage: dw.to_binary_tree("R1L0") == dw.to_binary_tree("L1R0").left_right_symmetry()\n True\n sage: dw.to_binary_tree("R10L")\n Traceback (most recent call last):\n ...\n ValueError: R10L is not a correct map\n '
if (usemap not in ['1L0R', '1R0L', 'L1R0', 'R1L0']):
raise ValueError(('%s is not a correct map' % usemap))
from sage.combinat.binary_tree import BinaryTree
if (not self):
return BinaryTree()
tp = [0]
tp.extend(self.returns_to_zero())
l = len(self)
if (usemap[0] == '1'):
s0 = 1
e0 = (tp[1] - 1)
s1 = (e0 + 1)
e1 = l
else:
s0 = 0
e0 = tp[(len(tp) - 2)]
s1 = (e0 + 1)
e1 = (l - 1)
trees = [DyckWord(self[s0:e0]).to_binary_tree(usemap), DyckWord(self[s1:e1]).to_binary_tree(usemap)]
if ((usemap[0] == 'R') or (usemap[1] == 'R')):
trees.reverse()
return BinaryTree(trees)
@combinatorial_map(name='to the Tamari corresponding Binary tree')
def to_binary_tree_tamari(self):
"\n Return the binary tree corresponding to ``self`` in a way which\n is consistent with the Tamari orders on the set of Dyck paths and\n on the set of binary trees.\n\n This is the ``'L1R0'`` map documented in :meth:`to_binary_tree`.\n\n EXAMPLES::\n\n sage: DyckWord([1,0]).to_binary_tree_tamari() # needs sage.graphs\n [., .]\n sage: DyckWord([1,0,1,1,0,0]).to_binary_tree_tamari() # needs sage.graphs\n [[., .], [., .]]\n sage: DyckWord([1,0,1,0,1,0]).to_binary_tree_tamari() # needs sage.graphs\n [[[., .], .], .]\n "
from sage.combinat.binary_tree import from_tamari_sorting_tuple
tup = self.to_tamari_sorting_tuple()
return from_tamari_sorting_tuple(tup)
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" means an interval in the Tamari order. The\n Tamari order on the set of Dyck words of size `n` is the\n partial order obtained from the Tamari order on the set of\n binary trees of size `n` (see\n :meth:`~sage.combinat.binary_tree.BinaryTree.tamari_lequal`)\n by means of the Tamari bijection between Dyck words and binary\n trees\n (:meth:`~sage.combinat.binary_tree.BinaryTree.to_dyck_word_tamari`).\n\n INPUT:\n\n - ``other`` -- a Dyck word greater or equal to ``self`` in the\n Tamari order\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: dw = DyckWord([1, 1, 0, 1, 0, 0, 1, 0])\n sage: ip = dw.tamari_interval(DyckWord([1, 1, 1, 0, 0, 1, 0, 0])); ip\n The Tamari interval of size 4 induced by relations [(2, 4), (3, 4), (3, 1), (2, 1)]\n sage: ip.lower_dyck_word()\n [1, 1, 0, 1, 0, 0, 1, 0]\n sage: ip.upper_dyck_word()\n [1, 1, 1, 0, 0, 1, 0, 0]\n sage: ip.interval_cardinality()\n 4\n sage: ip.number_of_tamari_inversions()\n 2\n sage: list(ip.dyck_words())\n [[1, 1, 1, 0, 0, 1, 0, 0],\n [1, 1, 1, 0, 0, 0, 1, 0],\n [1, 1, 0, 1, 0, 1, 0, 0],\n [1, 1, 0, 1, 0, 0, 1, 0]]\n sage: dw.tamari_interval(DyckWord([1,1,0,0,1,1,0,0]))\n Traceback (most recent call last):\n ...\n ValueError: the two Dyck words are not comparable on the Tamari lattice\n '
from sage.combinat.interval_posets import TamariIntervalPosets
return TamariIntervalPosets.from_dyck_words(self, other)
def _area_sequence_iter(self) -> Iterator[int]:
'\n Return an iterator producing the area sequence.\n\n .. SEEALSO:: :meth:`to_area_sequence`\n\n EXAMPLES::\n\n sage: d = DyckWord([1, 0, 1, 0])\n sage: [a for a in d._area_sequence_iter()]\n [0, 0]\n '
a = 0
for move in self:
if (move == open_symbol):
(yield a)
a += 1
else:
a -= 1
def to_area_sequence(self) -> list[int]:
'\n Return the area sequence of the Dyck word ``self``.\n\n The area sequence of a Dyck word `w` is defined as follows:\n Representing the Dyck word `w` as a Dyck path from `(0, 0)` to\n `(n, n)` using `N` and `E` steps (this involves padding `w` by\n `E` steps until `w` reaches the main diagonal if `w` is not\n already a complete Dyck path), the area sequence of `w` is the\n sequence `(a_1, a_2, \\ldots, a_n)`, where `a_i` is the number\n of full cells in the `i`-th row of the rectangle\n `[0, n] \\times [0, n]` which lie completely above the diagonal.\n (The cells are the regions into which the rectangle is\n subdivided by the lines `x = i` with `i` integer and the lines\n `y = j` with `j` integer. The `i`-th row consists of all the\n cells between the lines `y = i-1` and `y = i`.)\n\n An alternative definition:\n Representing the Dyck word `w` as a Dyck path consisting of\n `NE` and `SE` steps, the area sequence is the sequence of\n ordinates of all lattice points on the path which are\n starting points of `NE` steps.\n\n A list of integers `l` is the area sequence of some Dyck path\n if and only if it satisfies `l_0 = 0` and\n `0 \\leq l_{i+1} \\leq l_i + 1` for `i > 0`.\n\n EXAMPLES::\n\n sage: DyckWord([]).to_area_sequence()\n []\n sage: DyckWord([1, 0]).to_area_sequence()\n [0]\n sage: DyckWord([1, 1, 0, 0]).to_area_sequence()\n [0, 1]\n sage: DyckWord([1, 0, 1, 0]).to_area_sequence()\n [0, 0]\n sage: all(dw ==\n ....: DyckWords().from_area_sequence(dw.to_area_sequence())\n ....: for i in range(6) for dw in DyckWords(i))\n True\n sage: DyckWord([1,0,1,0,1,0,1,0,1,0]).to_area_sequence()\n [0, 0, 0, 0, 0]\n sage: DyckWord([1,1,1,1,1,0,0,0,0,0]).to_area_sequence()\n [0, 1, 2, 3, 4]\n sage: DyckWord([1,1,1,1,0,1,0,0,0,0]).to_area_sequence()\n [0, 1, 2, 3, 3]\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).to_area_sequence()\n [0, 1, 1, 0, 1, 1, 1]\n '
return list(self._area_sequence_iter())
|
class DyckWord_complete(DyckWord):
'\n The class of complete\n :class:`Dyck words<sage.combinat.dyck_word.DyckWord>`.\n A Dyck word is complete, if it contains as many closers as openers.\n\n For further information on Dyck words, see\n :class:`DyckWords_class<sage.combinat.dyck_word.DyckWord>`.\n '
def semilength(self) -> int:
'\n Return the semilength of ``self``.\n\n The semilength of a complete Dyck word `d` is the number of openers\n and the number of closers.\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).semilength()\n 2\n\n TESTS::\n\n sage: DyckWord([]).semilength()\n 0\n '
return (len(self) // 2)
@combinatorial_map(name='to partition')
def to_partition(self):
'\n Return the partition associated to ``self`` .\n\n This partition is determined by thinking of ``self`` as a lattice path\n and considering the cells which are above the path but within the\n `n \\times n` grid and the partition is formed by reading the sequence\n of the number of cells in this collection in each row.\n\n OUTPUT:\n\n - a partition representing the rows of cells in the square lattice\n and above the path\n\n EXAMPLES::\n\n sage: DyckWord([]).to_partition()\n []\n sage: DyckWord([1,0]).to_partition()\n []\n sage: DyckWord([1,1,0,0]).to_partition()\n []\n sage: DyckWord([1,0,1,0]).to_partition()\n [1]\n sage: DyckWord([1,0,1,0,1,0]).to_partition()\n [2, 1]\n sage: DyckWord([1,1,0,0,1,0]).to_partition()\n [2]\n sage: DyckWord([1,0,1,1,0,0]).to_partition()\n [1, 1]\n '
from sage.combinat.partition import Partition
n = (len(self) // 2)
res = []
for c in reversed(self):
if (c == close_symbol):
n -= 1
else:
res.append(n)
return Partition(res)
def number_of_parking_functions(self) -> int:
'\n Return the number of parking functions with ``self`` as the supporting\n Dyck path.\n\n One representation of a parking function is as a pair consisting of a\n Dyck path and a permutation `\\pi` such that if\n `[a_0, a_1, \\ldots, a_{n-1}]` is the area_sequence of the Dyck path\n (see :meth:`to_area_sequence<DyckWord.to_area_sequence>`) then the\n permutation `\\pi` satisfies `\\pi_i < \\pi_{i+1}` whenever\n `a_{i} < a_{i+1}`. This function counts the number of permutations `\\pi`\n which satisfy this condition.\n\n EXAMPLES::\n\n sage: DyckWord(area_sequence=[0,1,2]).number_of_parking_functions()\n 1\n sage: DyckWord(area_sequence=[0,1,1]).number_of_parking_functions()\n 3\n sage: DyckWord(area_sequence=[0,1,0]).number_of_parking_functions()\n 3\n sage: DyckWord(area_sequence=[0,0,0]).number_of_parking_functions()\n 6\n '
from sage.arith.misc import multinomial
return multinomial(self.rise_composition())
def list_parking_functions(self) -> list:
'\n Return all parking functions whose supporting Dyck path is ``self``.\n\n EXAMPLES::\n\n sage: DyckWord([1,1,0,0,1,0]).list_parking_functions()\n [[1, 1, 3], [1, 3, 1], [3, 1, 1]]\n '
return list(self.parking_functions())
def parking_functions(self):
'\n Iterate over parking functions whose supporting Dyck path is ``self``.\n\n EXAMPLES::\n\n sage: list(DyckWord([1,1,0,1,0,0]).parking_functions())\n [[1, 1, 2], [1, 2, 1], [2, 1, 1]]\n '
from sage.combinat.parking_functions import ParkingFunction
alist = self._area_sequence_iter()
for pi in Permutations([((i - ai) + 1) for (i, ai) in enumerate(alist)]):
(yield ParkingFunction(pi))
def reading_permutation(self) -> Permutation:
'\n Return the reading permutation of ``self``.\n\n This is the permutation formed by taking the reading word of\n the Dyck path representing ``self`` (with `N` and `E` steps)\n if the vertical edges of the Dyck path are labeled from bottom\n to top with `1` through `n` and the diagonals are read from\n top to bottom starting with the diagonal furthest from the\n main diagonal.\n\n EXAMPLES::\n\n sage: DyckWord([1,0,1,0]).reading_permutation()\n [2, 1]\n sage: DyckWord([1,1,0,0]).reading_permutation()\n [2, 1]\n sage: DyckWord([1,1,0,1,0,0]).reading_permutation()\n [3, 2, 1]\n sage: DyckWord([1,1,0,0,1,0]).reading_permutation()\n [2, 3, 1]\n sage: DyckWord([1,0,1,1,0,0,1,0]).reading_permutation()\n [3, 4, 2, 1]\n '
if (not self):
return Permutation([])
alist = self.to_area_sequence()
m = max(alist)
p1 = Word([(m - alist[((- i) - 1)]) for i in range(len(alist))]).standard_permutation()
return p1.inverse().complement()
def characteristic_symmetric_function(self, q=None, R=QQ[('q', 't')].fraction_field()):
"\n The characteristic function of ``self`` is the sum of\n `q^{dinv(D,F)} Q_{ides(read(D,F))}` over all permutation\n fillings of the Dyck path representing ``self``, where\n `ides(read(D,F))` is the descent composition of the inverse of the\n reading word of the filling.\n\n INPUT:\n\n - ``q`` -- (default: ``q = R('q')``) a parameter for the generating\n function power\n\n - ``R`` -- (default : ``R = QQ['q','t'].fraction_field()``) the base\n ring to do the calculations over\n\n OUTPUT:\n\n - an element of the symmetric functions over the ring ``R``\n (in the Schur basis).\n\n EXAMPLES::\n\n sage: R = QQ['q','t'].fraction_field()\n sage: (q,t) = R.gens()\n sage: f = sum(t**D.area() * D.characteristic_symmetric_function() # needs sage.modules\n ....: for D in DyckWords(3)); f\n (q^3+q^2*t+q*t^2+t^3+q*t)*s[1, 1, 1] + (q^2+q*t+t^2+q+t)*s[2, 1] + s[3]\n sage: f.nabla(power=-1) # needs sage.modules\n s[1, 1, 1]\n "
from sage.combinat.ncsf_qsym.qsym import QuasiSymmetricFunctions
from sage.combinat.sf.sf import SymmetricFunctions
if (q is None):
q = R('q')
elif (q not in R):
raise ValueError(('q=%s must be an element of the base ring %s' % (q, R)))
F = QuasiSymmetricFunctions(R).Fundamental()
p = self.reading_permutation().inverse()
perms = [Word(perm).standard_permutation() for perm in self.list_parking_functions()]
QSexpr = sum((((q ** self.dinv(pv.inverse())) * F(Permutation([p(i) for i in pv]).descents_composition())) for pv in perms))
s = SymmetricFunctions(R).s()
return s(QSexpr.to_symmetric_function())
def to_pair_of_standard_tableaux(self) -> tuple:
'\n Convert ``self`` to a pair of standard tableaux of the same shape and\n of length less than or equal to two.\n\n EXAMPLES::\n\n sage: DyckWord([1,0,1,0]).to_pair_of_standard_tableaux()\n ([[1], [2]], [[1], [2]])\n sage: DyckWord([1,1,0,0]).to_pair_of_standard_tableaux()\n ([[1, 2]], [[1, 2]])\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).to_pair_of_standard_tableaux()\n ([[1, 2, 4, 7], [3, 5, 6]], [[1, 2, 4, 6], [3, 5, 7]])\n '
from sage.combinat.tableau import Tableau
n = self.semilength()
if (n == 0):
return (Tableau([]), Tableau([]))
elif (self.height() == n):
T = Tableau([list(range(1, (n + 1)))])
return (T, T)
else:
left: list[list[int]] = [[], []]
right: list[list[int]] = [[], []]
for pos in range(n):
if (self[pos] == open_symbol):
left[0].append((pos + 1))
else:
left[1].append((pos + 1))
if (self[((- pos) - 1)] == close_symbol):
right[0].append((pos + 1))
else:
right[1].append((pos + 1))
return (Tableau(left), Tableau(right))
@combinatorial_map(name='to 312 avoiding permutation')
def to_312_avoiding_permutation(self) -> Permutation:
'\n Convert ``self`` to a `312`-avoiding permutation using the bijection\n by Bandlow and Killpatrick in [BK2001]_.\n\n This sends the area to the inversion number.\n\n EXAMPLES::\n\n sage: DyckWord([1,1,0,0]).to_312_avoiding_permutation()\n [2, 1]\n sage: DyckWord([1,0,1,0]).to_312_avoiding_permutation()\n [1, 2]\n sage: p = DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).to_312_avoiding_permutation(); p\n [2, 3, 1, 5, 6, 7, 4]\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).area()\n 5\n sage: p.length()\n 5\n\n TESTS::\n\n sage: PD = [D.to_312_avoiding_permutation() for D in DyckWords(5)]\n sage: all(pi.avoids([3,1,2]) for pi in PD)\n True\n sage: all(D.area()==D.to_312_avoiding_permutation().length() for D in DyckWords(5))\n True\n '
n = self.semilength()
area = self._area_sequence_iter()
pi = Permutations(n).one()
for (j, aj) in enumerate(area):
for i in range(aj):
pi = pi.apply_simple_reflection((j - i))
return pi
@combinatorial_map(name='to non-crossing permutation')
def to_noncrossing_permutation(self) -> Permutation:
'\n Use the bijection by C. Stump in [Stu2008]_ to send ``self`` to a\n non-crossing permutation.\n\n A non-crossing permutation when written in cyclic notation has cycles\n which are strictly increasing. Sends the area to the inversion number\n and ``self.major_index()`` to `n(n-1) - maj(\\sigma) - maj(\\sigma^{-1})`.\n Uses the function :func:`~sage.combinat.dyck_word.pealing`\n\n EXAMPLES::\n\n sage: DyckWord([1,1,0,0]).to_noncrossing_permutation()\n [2, 1]\n sage: DyckWord([1,0,1,0]).to_noncrossing_permutation()\n [1, 2]\n sage: p = DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).to_noncrossing_permutation(); p\n [2, 3, 1, 5, 6, 7, 4]\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).area()\n 5\n sage: p.length()\n 5\n\n TESTS::\n\n sage: all(D.area()==D.to_noncrossing_permutation().length() for D in DyckWords(5))\n True\n sage: all(20-D.major_index()==D.to_noncrossing_permutation().major_index()\n ....: +D.to_noncrossing_permutation().imajor_index() for D in DyckWords(5))\n True\n '
n = self.semilength()
if (n == 0):
return Permutation([])
(D, touch_sequence) = pealing(self, return_touches=True)
pi = list(range(1, (n + 1)))
while touch_sequence:
for touches in touch_sequence:
a = pi[(touches[0] - 1)]
for i in range((len(touches) - 1)):
pi[(touches[i] - 1)] = pi[(touches[(i + 1)] - 1)]
pi[(touches[(- 1)] - 1)] = a
(D, touch_sequence) = pealing(D, return_touches=True)
return Permutations()(pi, check=False)
@combinatorial_map(name='to 321 avoiding permutation')
def to_321_avoiding_permutation(self) -> Permutation:
"\n Use the bijection (pp. 60-61 of [Knu1973]_ or section 3.1 of [CK2008]_)\n to send ``self`` to a `321`-avoiding permutation.\n\n It is shown in [EP2004]_ that it sends the number of centered tunnels\n to the number of fixed points, the number of right tunnels to the\n number of excedences, and the semilength plus the height of the middle\n point to 2 times the length of the longest increasing subsequence.\n\n EXAMPLES::\n\n sage: DyckWord([1,0,1,0]).to_321_avoiding_permutation()\n [2, 1]\n sage: DyckWord([1,1,0,0]).to_321_avoiding_permutation()\n [1, 2]\n sage: D = DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0])\n sage: p = D.to_321_avoiding_permutation()\n sage: p\n [3, 5, 1, 6, 2, 7, 4]\n sage: D.number_of_tunnels()\n 0\n sage: p.number_of_fixed_points()\n 0\n sage: D.number_of_tunnels('right')\n 4\n sage: len(p.weak_excedences())-p.number_of_fixed_points()\n 4\n sage: n = D.semilength()\n sage: D.heights()[n] + n\n 8\n sage: 2*p.longest_increasing_subsequence_length()\n 8\n\n TESTS::\n\n sage: PD = [D.to_321_avoiding_permutation() for D in DyckWords(5)]\n sage: all(pi.avoids([3,2,1]) for pi in PD)\n True\n sage: to_perm = lambda x: x.to_321_avoiding_permutation()\n sage: all(D.number_of_tunnels() == to_perm(D).number_of_fixed_points()\n ....: for D in DyckWords(5))\n True\n sage: all(D.number_of_tunnels('right') == len(to_perm(D).weak_excedences())\n ....: -to_perm(D).number_of_fixed_points() for D in DyckWords(5))\n True\n sage: all(D.heights()[5]+5 == 2*to_perm(D).longest_increasing_subsequence_length()\n ....: for D in DyckWords(5))\n True\n "
from sage.combinat.rsk import RSK_inverse
(A, B) = self.to_pair_of_standard_tableaux()
return RSK_inverse(A, B, output='permutation')
@combinatorial_map(name='to 132 avoiding permutation')
def to_132_avoiding_permutation(self) -> Permutation:
'\n Use the bijection by C. Krattenthaler in [Kra2001]_ to send ``self``\n to a `132`-avoiding permutation.\n\n EXAMPLES::\n\n sage: DyckWord([1,1,0,0]).to_132_avoiding_permutation()\n [1, 2]\n sage: DyckWord([1,0,1,0]).to_132_avoiding_permutation()\n [2, 1]\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).to_132_avoiding_permutation()\n [6, 5, 4, 7, 2, 1, 3]\n\n TESTS::\n\n sage: PD = [D.to_132_avoiding_permutation() for D in DyckWords(5)]\n sage: all(pi.avoids([1,3,2]) for pi in PD)\n True\n '
n = self.semilength()
area = self.to_area_sequence()
area.append(0)
pi = []
values = list(range(1, (n + 1)))
for i in range(n):
if ((area[((n - i) - 1)] + 1) > area[(n - i)]):
pi.append(((n - i) - area[((n - i) - 1)]))
values.remove(((n - i) - area[((n - i) - 1)]))
else:
v = min((v for v in values if (v > ((n - i) - area[((n - i) - 1)]))))
pi.append(v)
values.remove(v)
return Permutation(pi)
def to_permutation(self, map) -> Permutation:
'\n This is simply a method collecting all implemented maps from Dyck\n words to permutations.\n\n INPUT:\n\n - ``map`` -- defines the map from Dyck words to permutations.\n These are currently:\n\n - ``Bandlow-Killpatrick``: :func:`to_312_avoiding_permutation`\n - ``Knuth``: :func:`to_321_avoiding_permutation`\n - ``Krattenthaler``: :func:`to_132_avoiding_permutation`\n - ``Stump``: :func:`to_noncrossing_permutation`\n\n EXAMPLES::\n\n sage: D = DyckWord([1,1,1,0,1,0,0,0])\n sage: D.pretty_print()\n _____\n _| x x\n | x x .\n | x . .\n | . . .\n\n sage: D.to_permutation(map="Bandlow-Killpatrick")\n [3, 4, 2, 1]\n sage: D.to_permutation(map="Stump")\n [4, 2, 3, 1]\n sage: D.to_permutation(map="Knuth")\n [1, 2, 4, 3]\n sage: D.to_permutation(map="Krattenthaler")\n [2, 1, 3, 4]\n\n TESTS::\n\n sage: D = DyckWord([1,0,1,0])\n sage: D.to_permutation(\'Banana\')\n Traceback (most recent call last):\n ...\n ValueError: the given map is not valid\n '
if (map == 'Bandlow-Killpatrick'):
return self.to_312_avoiding_permutation()
elif (map == 'Knuth'):
return self.to_321_avoiding_permutation()
elif (map == 'Krattenthaler'):
return self.to_132_avoiding_permutation()
elif (map == 'Stump'):
return self.to_noncrossing_permutation()
else:
raise ValueError('the given map is not valid')
def to_noncrossing_partition(self, bijection=None):
'\n Bijection of Biane from ``self`` to a noncrossing partition.\n\n There is an optional parameter ``bijection`` that indicates if a\n different bijection from Dyck words to non-crossing partitions\n should be used (since there are potentially many).\n\n If the parameter ``bijection`` is "Stump" then the bijection used is\n from [Stu2008]_, see also the method :meth:`to_noncrossing_permutation`.\n\n Thanks to Mathieu Dutour for describing the bijection. See also\n :func:`~CompleteDyckWords.from_noncrossing_partition`.\n\n EXAMPLES::\n\n sage: DyckWord([]).to_noncrossing_partition()\n {}\n sage: DyckWord([1, 0]).to_noncrossing_partition()\n {{1}}\n sage: DyckWord([1, 1, 0, 0]).to_noncrossing_partition()\n {{1, 2}}\n sage: DyckWord([1, 1, 1, 0, 0, 0]).to_noncrossing_partition()\n {{1, 2, 3}}\n sage: DyckWord([1, 0, 1, 0, 1, 0]).to_noncrossing_partition()\n {{1}, {2}, {3}}\n sage: DyckWord([1, 1, 0, 1, 0, 0]).to_noncrossing_partition()\n {{1, 3}, {2}}\n sage: DyckWord([]).to_noncrossing_partition("Stump")\n {}\n sage: DyckWord([1, 0]).to_noncrossing_partition("Stump")\n {{1}}\n sage: DyckWord([1, 1, 0, 0]).to_noncrossing_partition("Stump")\n {{1, 2}}\n sage: DyckWord([1, 1, 1, 0, 0, 0]).to_noncrossing_partition("Stump")\n {{1, 3}, {2}}\n sage: DyckWord([1, 0, 1, 0, 1, 0]).to_noncrossing_partition("Stump")\n {{1}, {2}, {3}}\n sage: DyckWord([1, 1, 0, 1, 0, 0]).to_noncrossing_partition("Stump")\n {{1, 2, 3}}\n '
P = SetPartitions((len(self) // 2))
if (bijection == 'Stump'):
return P(self.to_noncrossing_permutation().cycle_tuples(), check=False)
partition = []
stack = []
i = 0
p = 1
while (i < len(self)):
stack.append(p)
j = (i + 1)
while ((j < len(self)) and (self[j] == close_symbol)):
j += 1
nz = (j - (i + 1))
if (nz > 0):
if (nz > len(stack)):
raise ValueError('incorrect Dyck word')
partition.append(stack[(- nz):])
stack = stack[:(- nz)]
i = j
p += 1
if stack:
raise ValueError('incorrect Dyck word')
return P(partition, check=False)
def to_Catalan_code(self) -> list:
"\n Return the Catalan code associated to ``self``.\n\n A Catalan code of length `n` is a sequence\n `(a_1, a_2, \\ldots, a_n)` of `n` integers `a_i` such that:\n\n - `0 \\leq a_i \\leq n-i` for every `i`;\n\n - if `i < j` and `a_i > 0` and `a_j > 0` and\n `a_{i+1} = a_{i+2} = \\cdots = a_{j-1} = 0`,\n then `a_i - a_j < j-i`.\n\n It turns out that the Catalan codes of length `n` are in\n bijection with Dyck words.\n\n The Catalan code of a Dyck word is example (x) in Richard Stanley's\n exercises on combinatorial interpretations for Catalan objects.\n The code in this example is the reverse of the description provided\n there. See [Sta-EC2]_ and [StaCat98]_.\n\n EXAMPLES::\n\n sage: DyckWord([]).to_Catalan_code()\n []\n sage: DyckWord([1, 0]).to_Catalan_code()\n [0]\n sage: DyckWord([1, 1, 0, 0]).to_Catalan_code()\n [0, 1]\n sage: DyckWord([1, 0, 1, 0]).to_Catalan_code()\n [0, 0]\n sage: all(dw ==\n ....: DyckWords().from_Catalan_code(dw.to_Catalan_code())\n ....: for i in range(6) for dw in DyckWords(i))\n True\n\n .. SEEALSO:: :meth:`to_tamari_sorting_tuple`\n "
if (not self):
return []
cut = self.associated_parenthesis(0)
if (cut is None):
raise ValueError('not valid for incomplete Dyck words')
recdw = DyckWord((self[1:cut] + self[(cut + 1):]))
returns = ([0] + recdw.returns_to_zero())
res = recdw.to_Catalan_code()
res.append(returns.index((cut - 1)))
return res
@combinatorial_map(name='To Ordered tree')
def to_ordered_tree(self):
'\n Return the ordered tree corresponding to ``self`` where the depth\n of the tree is the maximal height of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: D = DyckWord([1,1,0,0])\n sage: D.to_ordered_tree()\n [[[]]]\n sage: D = DyckWord([1,0,1,0])\n sage: D.to_ordered_tree()\n [[], []]\n sage: D = DyckWord([1, 0, 1, 1, 0, 0])\n sage: D.to_ordered_tree()\n [[], [[]]]\n sage: D = DyckWord([1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0])\n sage: D.to_ordered_tree()\n [[], [[], []], [[], [[]]]]\n\n TESTS::\n\n sage: D = DyckWord([1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0])\n sage: D == D.to_ordered_tree().to_dyck_word() # needs sage.graphs\n True\n '
from sage.combinat.ordered_tree import OrderedTree
levels = [OrderedTree().clone()]
for u in self:
if (u == 1):
levels.append(OrderedTree().clone())
else:
tree = levels.pop()
tree.set_immutable()
root = levels.pop()
root.append(tree)
levels.append(root)
root = levels[0]
root.set_immutable()
return root
def to_triangulation(self) -> list:
'\n Map ``self`` to a triangulation.\n\n The map from complete Dyck words of length `2n` to\n triangulations of `n+2`-gon given by this function is a\n bijection that can be described as follows.\n\n Consider the Dyck word as a path from `(0, 0)` to `(n, n)`\n staying above the diagonal, where `1` is an up step and `0` is\n a right step. Then each horizontal step has a co-height (`0`\n at the top and `n-1` at most at the bottom). One reads the\n Dyck word from left to right. At the beginning, all vertices\n from `0` to `n+1` are available. For each horizontal step,\n one creates an edge from the vertex indexed by the co-height\n to the next available vertex. This chops out a triangle from\n the polygon and one removes the middle vertex of this triangle\n from the list of available vertices.\n\n This bijection has the property that the set of smallest\n vertices of the edges in a triangulation is an encoding of the\n co-heights, from which the Dyck word can be easily recovered.\n\n OUTPUT:\n\n a list of pairs `(i, j)` that are the edges of the\n triangulations.\n\n EXAMPLES::\n\n sage: DyckWord([1, 1, 0, 0]).to_triangulation()\n [(0, 2)]\n\n sage: [t.to_triangulation() for t in DyckWords(3)]\n [[(2, 4), (1, 4)],\n [(2, 4), (0, 2)],\n [(1, 3), (1, 4)],\n [(1, 3), (0, 3)],\n [(0, 2), (0, 3)]]\n\n REFERENCES:\n\n - [Cha2005]_\n '
n = self.number_of_open_symbols()
l = list(range((n + 2)))
edges = []
coheight = (n - 1)
for letter in self[1:(- 1)]:
if (letter == 1):
coheight -= 1
else:
edges.append((coheight, l[(coheight + 2)]))
l.pop((coheight + 1))
return edges
def to_triangulation_as_graph(self):
'\n Map ``self`` to a triangulation and return the result as a graph.\n\n See :meth:`to_triangulation` for the bijection used to map\n complete Dyck words to triangulations.\n\n OUTPUT:\n\n - a graph containing both the perimeter edges and the inner\n edges of a triangulation of a regular polygon.\n\n EXAMPLES::\n\n sage: g = DyckWord([1, 1, 0, 0, 1, 0]).to_triangulation_as_graph(); g # needs sage.graphs\n Graph on 5 vertices\n sage: g.edges(sort=True, labels=False) # needs sage.graphs\n [(0, 1), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (3, 4)]\n sage: g.show() # not tested # needs sage.graphs\n '
n = self.number_of_open_symbols()
edges = self.to_triangulation()
from sage.graphs.graph import Graph
peri = ([(i, (i + 1)) for i in range((n + 1))] + [((n + 1), 0)])
g = Graph((n + 2))
g.add_edges(peri)
g.add_edges(edges)
g.set_pos(g.layout_circular())
return g
def to_non_decreasing_parking_function(self):
'\n Bijection to :class:`non-decreasing parking\n functions<sage.combinat.non_decreasing_parking_function.NonDecreasingParkingFunctions>`.\n\n See there the method\n :meth:`~sage.combinat.non_decreasing_parking_function.NonDecreasingParkingFunction.to_dyck_word`\n for more information.\n\n EXAMPLES::\n\n sage: DyckWord([]).to_non_decreasing_parking_function()\n []\n sage: DyckWord([1,0]).to_non_decreasing_parking_function()\n [1]\n sage: DyckWord([1,1,0,0]).to_non_decreasing_parking_function()\n [1, 1]\n sage: DyckWord([1,0,1,0]).to_non_decreasing_parking_function()\n [1, 2]\n sage: DyckWord([1,0,1,1,0,1,0,0,1,0]).to_non_decreasing_parking_function()\n [1, 2, 2, 3, 5]\n\n TESTS::\n\n sage: ld = DyckWords(5)\n sage: list(ld) == [dw.to_non_decreasing_parking_function().to_dyck_word() for dw in ld]\n True\n '
from sage.combinat.non_decreasing_parking_function import NonDecreasingParkingFunction
return NonDecreasingParkingFunction.from_dyck_word(self)
def major_index(self) -> int:
'\n Return the major index of ``self`` .\n\n The major index of a Dyck word `D` is the sum of the positions of\n the valleys of `D` (when started counting at position ``1``).\n\n EXAMPLES::\n\n sage: DyckWord([1, 0, 1, 0]).major_index()\n 2\n sage: DyckWord([1, 1, 0, 0]).major_index()\n 0\n sage: DyckWord([1, 1, 0, 0, 1, 0]).major_index()\n 4\n sage: DyckWord([1, 0, 1, 1, 0, 0]).major_index()\n 2\n\n TESTS::\n\n sage: DyckWord([]).major_index()\n 0\n sage: DyckWord([1, 0]).major_index()\n 0\n '
valleys = self.valleys()
return (sum(valleys) + len(valleys))
def pyramid_weight(self) -> int:
'\n Return the pyramid weight of ``self``.\n\n A pyramid of ``self`` is a subsequence of the form\n `1^h 0^h`. A pyramid is maximal if it is neither preceded by a `1`\n nor followed by a `0`.\n\n The pyramid weight of a Dyck path is the sum of the lengths of the\n maximal pyramids and was defined in [DS1992]_.\n\n EXAMPLES::\n\n sage: DyckWord([1,1,0,1,1,1,0,0,1,0,0,0,1,1,0,0]).pyramid_weight()\n 6\n sage: DyckWord([1,1,1,0,0,0]).pyramid_weight()\n 3\n sage: DyckWord([1,0,1,0,1,0]).pyramid_weight()\n 3\n sage: DyckWord([1,1,0,1,0,0]).pyramid_weight()\n 2\n '
aseq = (self.to_area_sequence() + [0])
bseq = (self.reverse().to_area_sequence() + [0])
apeak = []
bpeak = []
for i in range((len(aseq) - 1)):
if (aseq[(i + 1)] <= aseq[i]):
apeak.append(i)
if (bseq[(i + 1)] <= bseq[i]):
bpeak.append(i)
out = 0
for (i, apeaki) in enumerate(apeak):
out += min(((aseq[apeaki] - aseq[(apeaki + 1)]) + 1), ((bseq[bpeak[((- i) - 1)]] - bseq[(bpeak[((- i) - 1)] + 1)]) + 1))
return out
def tunnels(self):
'\n Return an iterator of ranges of the matching parentheses in the Dyck\n word ``self``.\n\n That is, if ``(a,b)`` is in ``self.tunnels()``, then the matching\n parenthesis to ``self[a]`` is ``self[b-1]``.\n\n EXAMPLES::\n\n sage: list(DyckWord([1, 1, 0, 1, 1, 0, 0, 1, 0, 0]).tunnels())\n [(0, 10), (1, 3), (3, 7), (4, 6), (7, 9)]\n '
heights = self.heights()
for i in range((len(heights) - 1)):
height = heights[i]
if (height < heights[(i + 1)]):
(yield (i, ((i + 1) + heights[(i + 1):].index(height))))
def number_of_tunnels(self, tunnel_type='centered') -> int:
"\n Return the number of tunnels of ``self`` of type ``tunnel_type``.\n\n A tunnel is a pair `(a,b)` where ``a`` is the position of an open\n parenthesis and ``b`` is the position of the matching close\n parenthesis. If `a + b = n` then the tunnel is called *centered* . If\n `a + b < n` then the tunnel is called *left* and if `a + b > n`, then\n the tunnel is called *right*.\n\n INPUT:\n\n - ``tunnel_type`` -- (default: ``'centered'``) can be one of the\n following: ``'left'``, ``'right'``, ``'centered'``, or ``'all'``.\n\n EXAMPLES::\n\n sage: DyckWord([1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0]).number_of_tunnels()\n 0\n sage: DyckWord([1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0]).number_of_tunnels('left')\n 5\n sage: DyckWord([1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0]).number_of_tunnels('right')\n 2\n sage: DyckWord([1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0]).number_of_tunnels('all')\n 7\n sage: DyckWord([1, 1, 0, 0]).number_of_tunnels('centered')\n 2\n "
n = len(self)
tunnels = self.tunnels()
if (tunnel_type == 'left'):
return len([1 for (i, j) in tunnels if ((i + j) < n)])
elif (tunnel_type == 'centered'):
return len([1 for (i, j) in tunnels if ((i + j) == n)])
elif (tunnel_type == 'right'):
return len([1 for (i, j) in tunnels if ((i + j) > n)])
elif (tunnel_type == 'all'):
return len(list(tunnels))
else:
raise ValueError('the given tunnel_type is not valid')
@combinatorial_map(order=2, name='Reverse path')
def reverse(self) -> DyckWord:
'\n Return the reverse and complement of ``self``.\n\n This operation corresponds to flipping the Dyck path across the\n `y=-x` line.\n\n EXAMPLES::\n\n sage: DyckWord([1,1,0,0,1,0]).reverse()\n [1, 0, 1, 1, 0, 0]\n sage: DyckWord([1,1,1,0,0,0]).reverse()\n [1, 1, 1, 0, 0, 0]\n sage: len([D for D in DyckWords(5) if D.reverse() == D])\n 10\n\n TESTS::\n\n sage: DyckWord([]).reverse()\n []\n '
alist = []
for i in range(len(self)):
if (self[i] == open_symbol):
alist.append(close_symbol)
else:
alist.append(open_symbol)
alist.reverse()
return DyckWord(alist)
def first_return_decomposition(self) -> tuple:
'\n Decompose a Dyck word into a pair of Dyck words (potentially empty)\n where the first word consists of the word after the first up step and\n the corresponding matching closing parenthesis.\n\n EXAMPLES::\n\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).first_return_decomposition()\n ([1, 0, 1, 0], [1, 1, 0, 1, 0, 1, 0, 0])\n sage: DyckWord([1,1,0,0]).first_return_decomposition()\n ([1, 0], [])\n sage: DyckWord([1,0,1,0]).first_return_decomposition()\n ([], [1, 0])\n '
k = (self.position_of_first_return() * 2)
return (DyckWord(self[1:(k - 1)]), DyckWord(self[k:]))
def decomposition_reverse(self) -> DyckWord:
'\n Return the involution of ``self`` with a recursive definition.\n\n If a Dyck word `D` decomposes as `1 D_1 0 D_2` where `D_1` and\n `D_2` are complete Dyck words then the decomposition reverse is\n `1 \\phi(D_2) 0 \\phi(D_1)`.\n\n EXAMPLES::\n\n sage: DyckWord([1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0]).decomposition_reverse()\n [1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0]\n sage: DyckWord([1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0]).decomposition_reverse()\n [1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0]\n sage: DyckWord([1,1,0,0]).decomposition_reverse()\n [1, 0, 1, 0]\n sage: DyckWord([1,0,1,0]).decomposition_reverse()\n [1, 1, 0, 0]\n '
if (not self):
return self
(D1, D2) = self.first_return_decomposition()
D = ([1] + list(D2.decomposition_reverse()))
D += ([0] + list(D1.decomposition_reverse()))
return DyckWord(D)
@combinatorial_map(name='Area-dinv to bounce-area')
def area_dinv_to_bounce_area_map(self) -> DyckWord:
"\n Return the image of ``self`` under the map which sends a\n Dyck word with ``area`` equal to `r` and ``dinv`` equal to `s` to a\n Dyck word with ``bounce`` equal to `r` and ``area`` equal to `s` .\n\n The inverse of this map is :meth:`bounce_area_to_area_dinv_map`.\n\n For a definition of this map, see [Hag2008]_ p. 50 where it is called\n `\\zeta`. However, this map differs from Haglund's map by an application\n of :meth:`reverse` (as does the definition of the :meth:`bounce`\n statistic).\n\n EXAMPLES::\n\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).area_dinv_to_bounce_area_map()\n [1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0]\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).area()\n 5\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).dinv()\n 13\n sage: DyckWord([1,1,1,1,1,0,0,0,1,0,0,1,0,0]).area()\n 13\n sage: DyckWord([1,1,1,1,1,0,0,0,1,0,0,1,0,0]).bounce()\n 5\n sage: DyckWord([1,1,1,1,1,0,0,0,1,0,0,1,0,0]).area_dinv_to_bounce_area_map()\n [1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0]\n sage: DyckWord([1,1,0,0]).area_dinv_to_bounce_area_map()\n [1, 0, 1, 0]\n sage: DyckWord([1,0,1,0]).area_dinv_to_bounce_area_map()\n [1, 1, 0, 0]\n "
if (not self):
return self
a = self.to_area_sequence()
a.reverse()
image = []
for i in range(max(a), (- 2), (- 1)):
for j in a:
if (j == i):
image.append(1)
elif (j == (i + 1)):
image.append(0)
return DyckWord(image)
@combinatorial_map(name='Bounce-area to area-dinv')
def bounce_area_to_area_dinv_map(self) -> DyckWord:
"\n Return the image of the Dyck word under the map which sends a\n Dyck word with ``bounce`` equal to `r` and ``area`` equal to `s` to a\n Dyck word with ``area`` equal to `r` and ``dinv`` equal to `s` .\n\n This implementation uses a recursive method by saying that the\n last entry in the area sequence of the Dyck word ``self`` is\n equal to the number of touch points of the Dyck path minus 1\n of the image of this map.\n\n The inverse of this map is :meth:`area_dinv_to_bounce_area_map`.\n\n For a definition of this map, see [Hag2008]_ p. 50 where it is called\n `\\zeta^{-1}`. However, this map differs from Haglund's map by an\n application of :meth:`reverse` (as does the definition of the\n :meth:`bounce` statistic).\n\n EXAMPLES::\n\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).bounce_area_to_area_dinv_map()\n [1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0]\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).area()\n 5\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).bounce()\n 9\n sage: DyckWord([1,1,0,0,1,1,1,1,0,0,1,0,0,0]).area()\n 9\n sage: DyckWord([1,1,0,0,1,1,1,1,0,0,1,0,0,0]).dinv()\n 5\n sage: all(D==D.bounce_area_to_area_dinv_map().area_dinv_to_bounce_area_map() for D in DyckWords(6))\n True\n sage: DyckWord([1,1,0,0]).bounce_area_to_area_dinv_map()\n [1, 0, 1, 0]\n sage: DyckWord([1,0,1,0]).bounce_area_to_area_dinv_map()\n [1, 1, 0, 0]\n "
aseq = self._area_sequence_iter()
out: list[int] = []
zeros: list[int] = []
for ai in aseq:
p = (zeros + [len(out)])[ai]
out = ((([1] + out[p:]) + [0]) + out[:p])
zeros = ([0] + [((j + len(out)) - p) for j in zeros[:ai]])
return DyckWord(out)
def area(self) -> int:
"\n Return the area for ``self`` corresponding to the area\n of the Dyck path.\n\n One can view a balanced Dyck word as a lattice path from\n `(0,0)` to `(n,n)` in the first quadrant by letting\n '1's represent steps in the direction `(1,0)` and '0's\n represent steps in the direction `(0,1)`. The resulting\n path will remain weakly above the diagonal `y = x`.\n\n The area statistic is the number of complete\n squares in the integer lattice which are below the path and above\n the line `y = x`. The 'half-squares' directly above the\n line `y = x` do not contribute to this statistic.\n\n EXAMPLES::\n\n sage: dw = DyckWord([1,0,1,0])\n sage: dw.area() # 2 half-squares, 0 complete squares\n 0\n\n ::\n\n sage: dw = DyckWord([1,1,1,0,1,1,1,0,0,0,1,1,0,0,1,0,0,0])\n sage: dw.area()\n 19\n\n ::\n\n sage: DyckWord([1,1,1,1,0,0,0,0]).area()\n 6\n sage: DyckWord([1,1,1,0,1,0,0,0]).area()\n 5\n sage: DyckWord([1,1,1,0,0,1,0,0]).area()\n 4\n sage: DyckWord([1,1,1,0,0,0,1,0]).area()\n 3\n sage: DyckWord([1,0,1,1,0,1,0,0]).area()\n 2\n sage: DyckWord([1,1,0,1,1,0,0,0]).area()\n 4\n sage: DyckWord([1,1,0,0,1,1,0,0]).area()\n 2\n sage: DyckWord([1,0,1,1,1,0,0,0]).area()\n 3\n sage: DyckWord([1,0,1,1,0,0,1,0]).area()\n 1\n sage: DyckWord([1,0,1,0,1,1,0,0]).area()\n 1\n sage: DyckWord([1,1,0,0,1,0,1,0]).area()\n 1\n sage: DyckWord([1,1,0,1,0,0,1,0]).area()\n 2\n sage: DyckWord([1,1,0,1,0,1,0,0]).area()\n 3\n sage: DyckWord([1,0,1,0,1,0,1,0]).area()\n 0\n "
return sum(self._area_sequence_iter())
def bounce_path(self) -> DyckWord:
'\n Return the bounce path of ``self`` formed by starting at `(n,n)` and\n traveling West until encountering the first vertical step of ``self``,\n then South until encountering the diagonal, then West again to hit\n the path, etc. until the `(0,0)` point is reached. The path followed\n by this walk is the bounce path.\n\n .. SEEALSO:: :meth:`bounce`\n\n EXAMPLES::\n\n sage: DyckWord([1,1,0,1,0,0]).bounce_path()\n [1, 0, 1, 1, 0, 0]\n sage: DyckWord([1,1,1,0,0,0]).bounce_path()\n [1, 1, 1, 0, 0, 0]\n sage: DyckWord([1,0,1,0,1,0]).bounce_path()\n [1, 0, 1, 0, 1, 0]\n sage: DyckWord([1,1,1,1,0,0,1,0,0,0]).bounce_path()\n [1, 1, 0, 0, 1, 1, 1, 0, 0, 0]\n\n TESTS::\n\n sage: DyckWord([]).bounce_path()\n []\n sage: DyckWord([1,0]).bounce_path()\n [1, 0]\n\n '
area_seq = self.to_area_sequence()
i = (len(area_seq) - 1)
n = 5
while (i > 0):
n -= 1
a = area_seq[i]
i_new = (i - a)
while (i > i_new):
i -= 1
area_seq[i] = (area_seq[(i + 1)] - 1)
i -= 1
return DyckWord(area_sequence=area_seq)
def bounce(self) -> int:
'\n Return the bounce statistic of ``self`` due to J. Haglund,\n see [Hag2008]_.\n\n One can view a balanced Dyck word as a lattice path from `(0,0)` to\n `(n,n)` in the first quadrant by letting \'1\'s represent steps in\n the direction `(0,1)` and \'0\'s represent steps in the direction\n `(1,0)`. The resulting path will remain weakly above the diagonal\n `y = x`.\n\n We describe the bounce statistic of such a path in terms of what is\n known as the "bounce path".\n\n We can think of our bounce path as describing the trail of a billiard\n ball shot West from `(n, n)`, which "bounces" down whenever it\n encounters a vertical step and "bounces" left when it encounters the\n line `y = x`.\n\n The bouncing ball will strike the diagonal at the places\n\n .. MATH::\n\n (0, 0), (j_1, j_1), (j_2, j_2), \\ldots, (j_r-1, j_r-1), (j_r, j_r)\n = (n, n).\n\n We define the bounce to be the sum `\\sum_{i=1}^{r-1} j_i`.\n\n EXAMPLES::\n\n sage: DyckWord([1,1,1,0,1,1,1,0,0,0,1,1,0,0,1,0,0,0]).bounce()\n 7\n sage: DyckWord([1,1,1,1,0,0,0,0]).bounce()\n 0\n sage: DyckWord([1,1,1,0,1,0,0,0]).bounce()\n 1\n sage: DyckWord([1,1,1,0,0,1,0,0]).bounce()\n 2\n sage: DyckWord([1,1,1,0,0,0,1,0]).bounce()\n 3\n sage: DyckWord([1,0,1,1,0,1,0,0]).bounce()\n 3\n sage: DyckWord([1,1,0,1,1,0,0,0]).bounce()\n 1\n sage: DyckWord([1,1,0,0,1,1,0,0]).bounce()\n 2\n sage: DyckWord([1,0,1,1,1,0,0,0]).bounce()\n 1\n sage: DyckWord([1,0,1,1,0,0,1,0]).bounce()\n 4\n sage: DyckWord([1,0,1,0,1,1,0,0]).bounce()\n 3\n sage: DyckWord([1,1,0,0,1,0,1,0]).bounce()\n 5\n sage: DyckWord([1,1,0,1,0,0,1,0]).bounce()\n 4\n sage: DyckWord([1,1,0,1,0,1,0,0]).bounce()\n 2\n sage: DyckWord([1,0,1,0,1,0,1,0]).bounce()\n 6\n '
x_pos = (len(self) // 2)
y_pos = (len(self) // 2)
b = 0
mode = 'left'
makeup_steps = 0
l = self._list[:]
l.reverse()
for move in l:
if (mode == 'left'):
if (move == close_symbol):
x_pos -= 1
elif (move == open_symbol):
y_pos -= 1
if (x_pos == y_pos):
b += x_pos
else:
mode = 'drop'
elif (mode == 'drop'):
if (move == close_symbol):
makeup_steps += 1
elif (move == open_symbol):
y_pos -= 1
if (x_pos == y_pos):
b += x_pos
mode = 'left'
x_pos -= makeup_steps
makeup_steps = 0
return b
def dinv(self, labeling=None) -> int:
'\n Return the dinv statistic of ``self`` due to M. Haiman, see [Hag2008]_.\n\n If a labeling is provided then this function returns the dinv of the\n labeled Dyck word.\n\n INPUT:\n\n - ``labeling`` -- an optional argument to be viewed as the labelings\n of the vertical edges of the Dyck path\n\n OUTPUT:\n\n - an integer representing the ``dinv`` statistic of the Dyck path\n or the labelled Dyck path.\n\n EXAMPLES::\n\n sage: DyckWord([1,0,1,0,1,0,1,0,1,0]).dinv()\n 10\n sage: DyckWord([1,1,1,1,1,0,0,0,0,0]).dinv()\n 0\n sage: DyckWord([1,1,1,1,0,1,0,0,0,0]).dinv()\n 1\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).dinv()\n 13\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).dinv([1,2,3,4,5,6,7])\n 11\n sage: DyckWord([1,1,0,1,0,0,1,1,0,1,0,1,0,0]).dinv([6,7,5,3,4,2,1])\n 2\n '
alist = self.to_area_sequence()
cnt = 0
for (j, aj) in enumerate(alist):
if (labeling is not None):
lj = labeling[j]
for i in range(j):
if (((alist[i] == aj) and ((labeling is None) or (labeling[i] < lj))) or (((alist[i] - aj) == 1) and ((labeling is None) or (labeling[i] > lj)))):
cnt += 1
return cnt
@combinatorial_map(name='to alternating sign matrix')
def to_alternating_sign_matrix(self):
'\n Return ``self`` as an alternating sign matrix.\n\n This is an inclusion map from Dyck words of length `2n` to certain\n `n \\times n` alternating sign matrices.\n\n EXAMPLES::\n\n sage: DyckWord([1,1,1,0,1,0,0,0]).to_alternating_sign_matrix() # needs sage.modules\n [ 0 0 1 0]\n [ 1 0 -1 1]\n [ 0 1 0 0]\n [ 0 0 1 0]\n sage: DyckWord([1,0,1,0,1,1,0,0]).to_alternating_sign_matrix() # needs sage.modules\n [1 0 0 0]\n [0 1 0 0]\n [0 0 0 1]\n [0 0 1 0]\n '
parkfn = self.reverse().to_non_decreasing_parking_function()
parkfn2 = [((len(parkfn) + 1) - parkfn[i]) for i in range(len(parkfn))]
monotone_triangle = [([0] * (len(parkfn2) - j)) for j in range(len(parkfn2))]
for i in range(len(monotone_triangle)):
for j in range(len(monotone_triangle[i])):
monotone_triangle[i][j] = (len(monotone_triangle[i]) - j)
monotone_triangle[i][0] = parkfn2[i]
A = AlternatingSignMatrices(len(parkfn))
return A.from_monotone_triangle(monotone_triangle)
|
class DyckWords(UniqueRepresentation, Parent):
'\n Dyck words.\n\n A Dyck word is a sequence `(w_1, \\ldots, w_n)` consisting of 1 s and 0 s,\n with the property that for any `i` with `1 \\leq i \\leq n`, the sequence\n `(w_1, \\ldots, w_i)` contains at least as many 1 s as 0 s.\n\n A Dyck word is balanced if the total number of 1 s is equal to the total\n number of 0 s. The number of balanced Dyck words of length `2k` is given\n by the :func:`Catalan number<sage.combinat.combinat.catalan_number>` `C_k`.\n\n EXAMPLES:\n\n This class can be called with three keyword parameters ``k1``, ``k2``\n and ``complete``.\n\n If neither ``k1`` nor ``k2`` are specified, then :class:`DyckWords`\n returns the combinatorial class of all balanced (=complete) Dyck words,\n unless the keyword ``complete`` is set to False (in which case it\n returns the class of all Dyck words).\n\n ::\n\n sage: DW = DyckWords(); DW\n Complete Dyck words\n sage: [] in DW\n True\n sage: [1, 0, 1, 0] in DW\n True\n sage: [1, 1, 0] in DW\n False\n sage: ADW = DyckWords(complete=False); ADW\n Dyck words\n sage: [] in ADW\n True\n sage: [1, 0, 1, 0] in ADW\n True\n sage: [1, 1, 0] in ADW\n True\n sage: [1, 0, 0] in ADW\n False\n\n If just ``k1`` is specified, then it returns the balanced Dyck words with\n ``k1`` opening parentheses and ``k1`` closing parentheses.\n\n ::\n\n sage: DW2 = DyckWords(2); DW2\n Dyck words with 2 opening parentheses and 2 closing parentheses\n sage: DW2.first()\n [1, 0, 1, 0]\n sage: DW2.last()\n [1, 1, 0, 0]\n sage: DW2.cardinality()\n 2\n sage: DyckWords(100).cardinality() == catalan_number(100)\n True\n\n If ``k2`` is specified in addition to ``k1``, then it returns the\n Dyck words with ``k1`` opening parentheses and ``k2`` closing parentheses.\n\n ::\n\n sage: DW32 = DyckWords(3,2); DW32\n Dyck words with 3 opening parentheses and 2 closing parentheses\n sage: DW32.list()\n [[1, 0, 1, 0, 1],\n [1, 0, 1, 1, 0],\n [1, 1, 0, 0, 1],\n [1, 1, 0, 1, 0],\n [1, 1, 1, 0, 0]]\n '
@staticmethod
def __classcall_private__(cls, k1=None, k2=None, complete=True):
'\n Choose the correct parent based upon input.\n\n EXAMPLES::\n\n sage: DW1 = DyckWords(3,3)\n sage: DW2 = DyckWords(3)\n sage: DW1 is DW2\n True\n '
if (k2 is None):
if (k1 is None):
if complete:
return CompleteDyckWords_all()
return DyckWords_all()
k1 = ZZ(k1)
if (k1 < 0):
raise ValueError(('k1 (= %s) must be nonnegative' % k1))
return CompleteDyckWords_size(k1)
else:
k1 = ZZ(k1)
k2 = ZZ(k2)
if ((k1 < 0) or ((k2 is not None) and (k2 < 0))):
raise ValueError(('k1 (= %s) and k2 (= %s) must be nonnegative, with k1 >= k2' % (k1, k2)))
if (k1 < k2):
raise ValueError(('k1 (= %s) must be >= k2 (= %s)' % (k1, k2)))
if (k1 == k2):
return CompleteDyckWords_size(k1)
return DyckWords_size(k1, k2)
Element = DyckWord
class options(GlobalOptions):
'\n Set and display the options for Dyck words. If no parameters\n are set, then the function returns a copy of the options dictionary.\n\n The ``options`` to Dyck words can be accessed as the method\n :meth:`DyckWords.options` of :class:`DyckWords` and\n related parent classes.\n\n @OPTIONS\n\n EXAMPLES::\n\n sage: D = DyckWord([1, 1, 0, 1, 0, 0])\n sage: D\n [1, 1, 0, 1, 0, 0]\n sage: DyckWords.options.display="lattice"\n sage: D\n ___\n _| x\n | x .\n | . .\n sage: DyckWords.options(diagram_style="line")\n sage: D\n /\\/\\\n / \\\n sage: DyckWords.options._reset()\n '
NAME = 'DyckWords'
module = 'sage.combinat.dyck_word'
display = dict(default='list', description='Specifies how Dyck words should be printed', values=dict(list='displayed as a list', lattice='displayed on the lattice defined by ``diagram_style``'), case_sensitive=False)
ascii_art = dict(default='path', description='Specifies how the ascii art of Dyck words should be printed', values=dict(path='Using the path string', pretty_output='Using pretty printing'), alias=dict(pretty_print='pretty_output', path_string='path'), case_sensitive=False)
diagram_style = dict(default='grid', values=dict(grid='printing as paths on a grid using N and E steps', line='printing as paths on a line using NE and SE steps'), alias={'N-E': 'grid', 'NE-SE': 'line'}, case_sensitive=False)
latex_tikz_scale = dict(default=1, description='The default value for the tikz scale when latexed', checker=(lambda x: True))
latex_diagonal = dict(default=False, description='The default value for displaying the diagonal when latexed', checker=(lambda x: isinstance(x, bool)))
latex_line_width_scalar = dict(default=2, description='The default value for the line width as a multiple of the tikz scale when latexed', checker=(lambda x: True))
latex_color = dict(default='black', description='The default value for the color when latexed', checker=(lambda x: isinstance(x, str)))
latex_bounce_path = dict(default=False, description='The default value for displaying the bounce path when latexed', checker=(lambda x: isinstance(x, bool)))
latex_peaks = dict(default=False, description='The default value for displaying the peaks when latexed', checker=(lambda x: isinstance(x, bool)))
latex_valleys = dict(default=False, description='The default value for displaying the valleys when latexed', checker=(lambda x: isinstance(x, bool)))
def _element_constructor_(self, word):
'\n Construct an element of ``self``.\n\n EXAMPLES::\n\n sage: D = DyckWords()\n sage: elt = D([1, 1, 0, 1, 0, 0]); elt\n [1, 1, 0, 1, 0, 0]\n sage: elt.parent() is D\n True\n '
if (isinstance(word, DyckWord) and (word.parent() is self)):
return word
return self.element_class(self, list(word))
def __contains__(self, x) -> bool:
'\n TESTS::\n\n sage: D = DyckWords(complete=False)\n sage: [] in D\n True\n sage: [1] in D\n True\n sage: [0] in D\n False\n sage: [1, 0] in D\n True\n '
if isinstance(x, DyckWord):
return True
if (not isinstance(x, list)):
return False
return is_a(x)
def from_heights(self, heights) -> DyckWord:
"\n Compute a Dyck word knowing its heights.\n\n We view the Dyck word as a Dyck path from `(0, 0)` to\n `(2n, 0)` in the first quadrant by letting ``1``'s represent\n steps in the direction `(1, 1)` and ``0``'s represent steps in\n the direction `(1, -1)`.\n\n The :meth:`~DyckWord.heights` is the sequence of the `y`-coordinates of\n the `2n+1` lattice points along this path.\n\n EXAMPLES::\n\n sage: from sage.combinat.dyck_word import DyckWord\n sage: D = DyckWords(complete=False)\n sage: D.from_heights((0,))\n []\n sage: D.from_heights((0, 1, 0))\n [1, 0]\n sage: D.from_heights((0, 1, 2, 1, 0))\n [1, 1, 0, 0]\n\n This also works for incomplete Dyck words::\n\n sage: D.from_heights((0, 1, 2, 1, 2, 1))\n [1, 1, 0, 1, 0]\n sage: D.from_heights((0, 1, 2, 1))\n [1, 1, 0]\n\n .. SEEALSO:: :meth:`~DyckWord.heights`, :meth:`min_from_heights`\n\n TESTS::\n\n sage: all(dw == D.from_heights(dw.heights())\n ....: for i in range(7) for dw in DyckWords(i))\n True\n\n sage: D.from_heights((1, 2, 1))\n Traceback (most recent call last):\n ...\n ValueError: heights must start with 0: (1, 2, 1)\n sage: D.from_heights((0, 1, 4, 1))\n Traceback (most recent call last):\n ...\n ValueError: consecutive heights must differ by exactly 1: (0, 1, 4, 1)\n sage: D.from_heights(())\n Traceback (most recent call last):\n ...\n ValueError: heights must start with 0: ()\n "
l1 = (len(heights) - 1)
res = ([0] * l1)
if ((not heights) or (heights[0] != 0)):
raise ValueError(('heights must start with 0: %s' % (heights,)))
for i in range(l1):
if (heights[i] == (heights[(i + 1)] - 1)):
res[i] = 1
elif (heights[i] != (heights[(i + 1)] + 1)):
raise ValueError(('consecutive heights must differ by exactly 1: %s' % (heights,)))
return self.element_class(self, res)
def min_from_heights(self, heights) -> DyckWord:
'\n Compute the smallest Dyck word which achieves or surpasses\n a given sequence of heights.\n\n INPUT:\n\n - ``heights`` -- a nonempty list or iterable consisting of\n nonnegative integers, the first of which is `0`\n\n OUTPUT:\n\n - The smallest Dyck word whose sequence of heights is\n componentwise higher-or-equal to ``heights``. Here,\n "smaller" can be understood both in the sense of\n lexicographic order on the Dyck words, and in the sense\n of every vertex of the path having the smallest possible\n height.\n\n .. SEEALSO::\n\n - :meth:`~DyckWord.heights`\n - :meth:`from_heights`\n\n EXAMPLES::\n\n sage: D = DyckWords(complete=False)\n sage: D.min_from_heights((0,))\n []\n sage: D.min_from_heights((0, 1, 0))\n [1, 0]\n sage: D.min_from_heights((0, 0, 2, 0, 0))\n [1, 1, 0, 0]\n sage: D.min_from_heights((0, 0, 2, 0, 2, 0))\n [1, 1, 0, 1, 0]\n sage: D.min_from_heights((0, 0, 1, 0, 1, 0))\n [1, 1, 0, 1, 0]\n\n TESTS::\n\n sage: D.min_from_heights(())\n Traceback (most recent call last):\n ...\n ValueError: heights must start with 0: ()\n '
if ((not heights) or (heights[0] != 0)):
raise ValueError(('heights must start with 0: %s' % (heights,)))
heights = list(heights)
for i in range(0, len(heights), 2):
if (heights[i] % 2):
heights[i] += 1
for i in range(1, len(heights), 2):
if ((heights[i] % 2) == 0):
heights[i] += 1
for i in range((len(heights) - 1)):
if (heights[(i + 1)] < heights[i]):
heights[(i + 1)] = (heights[i] - 1)
for i in range((len(heights) - 1), 0, (- 1)):
if (heights[i] > heights[(i - 1)]):
heights[(i - 1)] = (heights[i] - 1)
return self.from_heights(heights)
|
class DyckWords_all(DyckWords):
'\n All Dyck words.\n '
def __init__(self):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: TestSuite(DyckWords(complete=False)).run()\n '
DyckWords.__init__(self, category=InfiniteEnumeratedSets())
def _repr_(self) -> str:
'\n TESTS::\n\n sage: DyckWords(complete=False)\n Dyck words\n '
return 'Dyck words'
def _an_element_(self) -> DyckWord:
'\n TESTS::\n\n sage: DyckWords(complete=False).an_element()\n [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]\n '
return DyckWords(5).an_element()
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: it = DyckWords(complete=False).__iter__()\n sage: [next(it) for x in range(10)]\n [[],\n [1],\n [1, 0],\n [1, 1],\n [1, 0, 0],\n [1, 0, 1],\n [1, 1, 0],\n [1, 1, 1],\n [1, 0, 1, 0],\n [1, 1, 0, 0]]\n '
n = 0
(yield self.element_class(self, []))
while True:
for k in range(1, (n + 1)):
for x in DyckWords_size(k, (n - k)):
(yield self.element_class(self, list(x)))
n += 1
|
class DyckWordBacktracker(GenericBacktracker):
"\n This class is an iterator for all Dyck words\n with `n` opening parentheses and `n - k` closing parentheses using\n the backtracker class. It is used by the :class:`DyckWords_size` class.\n\n This is not really meant to be called directly, partially because\n it fails in a couple corner cases: ``DWB(0)`` yields ``[0]``, not the\n empty word, and ``DWB(k, k+1)`` yields something (it shouldn't yield\n anything). This could be fixed with a sanity check in ``_rec()``, but\n then we'd be doing the sanity check *every time* we generate new\n objects; instead, we do *one* sanity check in :class:`DyckWords` and\n assume here that the sanity check has already been made.\n\n AUTHOR:\n\n - Dan Drake (2008-05-30)\n "
def __init__(self, k1, k2):
'\n TESTS::\n\n sage: from sage.combinat.dyck_word import DyckWordBacktracker\n sage: len(list(DyckWordBacktracker(5, 5)))\n 42\n sage: len(list(DyckWordBacktracker(6,4)))\n 90\n sage: len(list(DyckWordBacktracker(7,0)))\n 1\n '
GenericBacktracker.__init__(self, [], (0, 0))
k1 = ZZ(k1)
k2 = ZZ(k2)
self.n = (k1 + k2)
self.endht = (k1 - k2)
def _rec(self, path, state):
'\n TESTS::\n\n sage: from sage.combinat.dyck_word import DyckWordBacktracker\n sage: dwb = DyckWordBacktracker(3, 3)\n sage: list(dwb._rec([1,1,0],(3, 2)))\n [([1, 1, 0, 0], (4, 1), False), ([1, 1, 0, 1], (4, 3), False)]\n sage: list(dwb._rec([1,1,0,0],(4, 0)))\n [([1, 1, 0, 0, 1], (5, 1), False)]\n sage: list(DyckWordBacktracker(4, 4)._rec([1,1,1,1],(4, 4)))\n [([1, 1, 1, 1, 0], (5, 3), False)]\n '
(len, ht) = state
if (len < (self.n - 1)):
if ((ht > (self.endht - (self.n - len))) and (ht > 0)):
(yield ((path + [0]), ((len + 1), (ht - 1)), False))
if (ht < (self.endht + (self.n - len))):
(yield ((path + [1]), ((len + 1), (ht + 1)), False))
elif (ht < self.endht):
(yield ((path + [1]), None, True))
else:
(yield ((path + [0]), None, True))
|
class DyckWords_size(DyckWords):
'\n Dyck words with `k_1` openers and `k_2` closers.\n '
def __init__(self, k1, k2):
'\n TESTS:\n\n Check that :trac:`18244` is fixed::\n\n sage: DyckWords(13r, 8r).cardinality()\n 87210\n sage: parent(_)\n Integer Ring\n sage: TestSuite(DyckWords(4,2)).run()\n '
self.k1 = ZZ(k1)
self.k2 = ZZ(k2)
DyckWords.__init__(self, category=FiniteEnumeratedSets())
def _repr_(self) -> str:
'\n TESTS::\n\n sage: DyckWords(4)\n Dyck words with 4 opening parentheses and 4 closing parentheses\n '
return ('Dyck words with %s opening parentheses and %s closing parentheses' % (self.k1, self.k2))
def __contains__(self, x) -> bool:
'\n EXAMPLES::\n\n sage: [1, 0, 0, 1] in DyckWords(2,2)\n False\n sage: [1, 0, 1, 0] in DyckWords(2,2)\n True\n sage: [1, 0, 1, 0, 1] in DyckWords(3,2)\n True\n sage: [1, 0, 1, 1, 0] in DyckWords(3,2)\n True\n sage: [1, 0, 1, 1] in DyckWords(3,1)\n True\n '
return is_a(x, self.k1, self.k2)
def __iter__(self):
'\n Return an iterator for Dyck words with ``k1`` opening and ``k2``\n closing parentheses.\n\n EXAMPLES::\n\n sage: list(DyckWords(0))\n [[]]\n sage: list(DyckWords(1))\n [[1, 0]]\n sage: list(DyckWords(2))\n [[1, 0, 1, 0], [1, 1, 0, 0]]\n sage: len(DyckWords(5))\n 42\n sage: list(DyckWords(3,2))\n [[1, 0, 1, 0, 1],\n [1, 0, 1, 1, 0],\n [1, 1, 0, 0, 1],\n [1, 1, 0, 1, 0],\n [1, 1, 1, 0, 0]]\n '
if (self.k1 == 0):
(yield self.element_class(self, []))
elif (self.k2 == 0):
(yield self.element_class(self, ([open_symbol] * self.k1)))
else:
for w in DyckWordBacktracker(self.k1, self.k2):
(yield self.element_class(self, w))
def cardinality(self) -> int:
'\n Return the number of Dyck words with `k_1` openers and `k_2` closers.\n\n This number is\n\n .. MATH::\n\n \\frac{k_1 - k_2 + 1}{k_1 + 1} \\binom{k_1 + k_2}{k_2}\n = \\binom{k_1 + k_2}{k_2} - \\binom{k_1 + k_2}{k_2 - 1}\n\n if `k_2 \\leq k_1 + 1`, and `0` if `k_2 > k_1` (these numbers are the\n same if `k_2 = k_1 + 1`).\n\n EXAMPLES::\n\n sage: DyckWords(3, 2).cardinality()\n 5\n sage: all(all(DyckWords(p, q).cardinality()\n ....: == len(DyckWords(p, q).list()) for q in range(p + 1))\n ....: for p in range(7))\n True\n '
from sage.arith.misc import binomial
return ((((self.k1 - self.k2) + 1) * binomial((self.k1 + self.k2), self.k2)) // (self.k1 + 1))
|
class CompleteDyckWords(DyckWords):
'\n Abstract base class for all complete Dyck words.\n '
Element = DyckWord_complete
def __contains__(self, x) -> bool:
'\n TESTS::\n\n sage: [] in DyckWords()\n True\n sage: [1] in DyckWords()\n False\n sage: [0] in DyckWords()\n False\n '
if isinstance(x, DyckWord_complete):
return True
if (not isinstance(x, list)):
return False
if (len(x) % 2):
return False
return is_a(x, (len(x) // 2))
def from_Catalan_code(self, code) -> DyckWord:
"\n Return the Dyck word associated to the given Catalan code\n ``code``.\n\n A Catalan code of length `n` is a sequence\n `(a_1, a_2, \\ldots, a_n)` of `n` integers `a_i` such that:\n\n - `0 \\leq a_i \\leq n-i` for every `i`;\n\n - if `i < j` and `a_i > 0` and `a_j > 0` and\n `a_{i+1} = a_{i+2} = \\cdots = a_{j-1} = 0`,\n then `a_i - a_j < j-i`.\n\n It turns out that the Catalan codes of length `n` are in\n bijection with Dyck words.\n\n The Catalan code of a Dyck word is example (x) in Richard Stanley's\n exercises on combinatorial interpretations for Catalan objects.\n The code in this example is the reverse of the description provided\n there. See [Sta-EC2]_ and [StaCat98]_.\n\n EXAMPLES::\n\n sage: DyckWords().from_Catalan_code([])\n []\n sage: DyckWords().from_Catalan_code([0])\n [1, 0]\n sage: DyckWords().from_Catalan_code([0, 1])\n [1, 1, 0, 0]\n sage: DyckWords().from_Catalan_code([0, 0])\n [1, 0, 1, 0]\n "
code = list(code)
if (not code):
return self.element_class(self, [])
res = self.from_Catalan_code(code[:(- 1)])
cuts = ([0] + res.returns_to_zero())
lst = ((([1] + res[:cuts[code[(- 1)]]]) + [0]) + res[cuts[code[(- 1)]]:])
return self.element_class(self, lst)
def from_area_sequence(self, code) -> DyckWord:
'\n Return the Dyck word associated to the given area sequence\n ``code``.\n\n See :meth:`~DyckWord.to_area_sequence` for a definition of the area\n sequence of a Dyck word.\n\n .. SEEALSO:: :meth:`~DyckWord_complete.area`, :meth:`~DyckWord.to_area_sequence`.\n\n INPUT:\n\n - ``code`` -- a list of integers satisfying ``code[0] == 0``\n and ``0 <= code[i+1] <= code[i]+1``.\n\n EXAMPLES::\n\n sage: DyckWords().from_area_sequence([])\n []\n sage: DyckWords().from_area_sequence([0])\n [1, 0]\n sage: DyckWords().from_area_sequence([0, 1])\n [1, 1, 0, 0]\n sage: DyckWords().from_area_sequence([0, 0])\n [1, 0, 1, 0]\n '
if (not is_area_sequence(code)):
raise ValueError('the given sequence is not a sequence giving the number of cells between the Dyck path and the diagonal')
dyck_word = []
for i in range(len(code)):
if i:
dyck_word.extend(([close_symbol] * ((code[(i - 1)] - code[i]) + 1)))
dyck_word.append(open_symbol)
dyck_word.extend(([close_symbol] * ((2 * len(code)) - len(dyck_word))))
return self.element_class(self, dyck_word)
def from_noncrossing_partition(self, ncp) -> DyckWord:
'\n Convert a noncrossing partition ``ncp`` to a Dyck word.\n\n EXAMPLES::\n\n sage: DyckWord(noncrossing_partition=[[1,2]]) # indirect doctest\n [1, 1, 0, 0]\n sage: DyckWord(noncrossing_partition=[[1],[2]])\n [1, 0, 1, 0]\n\n sage: dws = DyckWords(5).list()\n sage: ncps = [x.to_noncrossing_partition() for x in dws]\n sage: dws2 = [DyckWord(noncrossing_partition=x) for x in ncps]\n sage: dws == dws2\n True\n '
l = ([0] * sum((len(v) for v in ncp)))
for v in ncp:
l[(max(v) - 1)] = len(v)
res = []
for i in l:
res += ([open_symbol] + ([close_symbol] * i))
return self.element_class(self, res)
def from_non_decreasing_parking_function(self, pf) -> DyckWord:
'\n Bijection from :class:`non-decreasing parking\n functions<sage.combinat.non_decreasing_parking_function.NonDecreasingParkingFunctions>`.\n\n See there the method\n :meth:`~sage.combinat.non_decreasing_parking_function.NonDecreasingParkingFunction.to_dyck_word`\n for more information.\n\n EXAMPLES::\n\n sage: D = DyckWords()\n sage: D.from_non_decreasing_parking_function([])\n []\n sage: D.from_non_decreasing_parking_function([1])\n [1, 0]\n sage: D.from_non_decreasing_parking_function([1,1])\n [1, 1, 0, 0]\n sage: D.from_non_decreasing_parking_function([1,2])\n [1, 0, 1, 0]\n sage: D.from_non_decreasing_parking_function([1,1,1])\n [1, 1, 1, 0, 0, 0]\n sage: D.from_non_decreasing_parking_function([1,2,3])\n [1, 0, 1, 0, 1, 0]\n sage: D.from_non_decreasing_parking_function([1,1,3,3,4,6,6])\n [1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0]\n\n TESTS::\n\n sage: D.from_non_decreasing_parking_function(NonDecreasingParkingFunction([]))\n []\n sage: D.from_non_decreasing_parking_function(NonDecreasingParkingFunction([1,1,3,3,4,6,6]))\n [1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0]\n '
return self.from_area_sequence([((i - pf[i]) + 1) for i in range(len(pf))])
|
class CompleteDyckWords_all(CompleteDyckWords, DyckWords_all):
'\n All complete Dyck words.\n '
def _repr_(self) -> str:
'\n TESTS::\n\n sage: DyckWords()\n Complete Dyck words\n '
return 'Complete Dyck words'
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: it = DyckWords().__iter__()\n sage: [next(it) for x in range(10)]\n [[],\n [1, 0],\n [1, 0, 1, 0],\n [1, 1, 0, 0],\n [1, 0, 1, 0, 1, 0],\n [1, 0, 1, 1, 0, 0],\n [1, 1, 0, 0, 1, 0],\n [1, 1, 0, 1, 0, 0],\n [1, 1, 1, 0, 0, 0],\n [1, 0, 1, 0, 1, 0, 1, 0]]\n '
n = 0
while True:
for x in CompleteDyckWords_size(n):
(yield self.element_class(self, list(x)))
n += 1
class height_poset(UniqueRepresentation, Parent):
"\n The poset of complete Dyck words compared componentwise by ``heights``.\n\n This is, ``D`` is smaller than or equal to ``D'`` if it is\n weakly below ``D'``.\n\n This is implemented by comparison of area sequences.\n "
def __init__(self):
'\n TESTS::\n\n sage: poset = DyckWords().height_poset()\n sage: TestSuite(poset).run()\n '
Parent.__init__(self, facade=DyckWords_all(), category=Posets())
def _an_element_(self):
'\n TESTS::\n\n sage: DyckWords().height_poset().an_element() # indirect doctest\n [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]\n '
return DyckWords_all().an_element()
def __call__(self, obj):
'\n TESTS::\n\n sage: poset = DyckWords().height_poset()\n sage: poset([1,0,1,0])\n [1, 0, 1, 0]\n '
return DyckWords_all()(obj)
def le(self, dw1, dw2):
'\n Compare two Dyck words of equal size, and return ``True`` if\n all of the heights of ``dw1`` are less than or equal to the\n respective heights of ``dw2`` .\n\n .. SEEALSO::\n\n :meth:`~sage.combinat.dyck_word.DyckWord.to_area_sequence`\n\n EXAMPLES::\n\n sage: poset = DyckWords().height_poset()\n sage: poset.le(DyckWord([]), DyckWord([]))\n True\n sage: poset.le(DyckWord([1,0]), DyckWord([1,0]))\n True\n sage: poset.le(DyckWord([1,0,1,0]), DyckWord([1,1,0,0]))\n True\n sage: poset.le(DyckWord([1,1,0,0]), DyckWord([1,0,1,0]))\n False\n sage: [poset.le(dw1, dw2)\n ....: for dw1 in DyckWords(3) for dw2 in DyckWords(3)]\n [True, True, True, True, True, False, True, False, True, True,\n False, False, True, True, True, False, False, False, True,\n True, False, False, False, False, True]\n '
if (len(dw1) != len(dw2)):
raise ValueError(f'length mismatch: {dw1} and {dw2}')
ar1 = dw1._area_sequence_iter()
ar2 = dw2._area_sequence_iter()
return all(((a1 <= a2) for (a1, a2) in zip(ar1, ar2)))
|
class CompleteDyckWords_size(CompleteDyckWords, DyckWords_size):
'\n All complete Dyck words of a given size.\n '
def __init__(self, k):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: TestSuite(DyckWords(4)).run()\n '
CompleteDyckWords.__init__(self, category=FiniteEnumeratedSets())
DyckWords_size.__init__(self, k, k)
def __contains__(self, x) -> bool:
'\n TESTS::\n\n sage: [1, 0] in DyckWords(1)\n True\n sage: [1, 0] in DyckWords(2)\n False\n sage: [1, 1, 0, 0] in DyckWords(2)\n True\n sage: [1, 0, 0, 1] in DyckWords(2)\n False\n '
return (CompleteDyckWords.__contains__(self, x) and ((len(x) // 2) == self.k1))
def cardinality(self) -> int:
'\n Return the number of complete Dyck words of semilength `n`, i.e. the\n `n`-th :func:`Catalan number<sage.combinat.combinat.catalan_number>`.\n\n EXAMPLES::\n\n sage: DyckWords(4).cardinality()\n 14\n sage: ns = list(range(9))\n sage: dws = [DyckWords(n) for n in ns]\n sage: all(dw.cardinality() == len(dw.list()) for dw in dws)\n True\n '
return catalan_number(self.k1)
def random_element(self) -> DyckWord:
"\n Return a random complete Dyck word of semilength `n`.\n\n The algorithm is based on a classical combinatorial fact. One\n chooses at random a word with `n` 0's and `n+1` 1's. One then\n considers every 1 as an ascending step and every 0 as a\n descending step, and one finds the lowest point of the path\n (with respect to a slightly tilted slope). One then cuts the\n path at this point and builds a Dyck word by exchanging the\n two parts of the word and removing the initial step.\n\n .. TODO::\n\n extend this to m-Dyck words\n\n EXAMPLES::\n\n sage: dw = DyckWords(8)\n sage: dw.random_element() # random\n [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0]\n\n sage: D = DyckWords(8)\n sage: D.random_element() in D\n True\n "
from sage.misc.prandom import shuffle
n = self.k1
w = (([0] * n) + ([1] * (n + 1)))
shuffle(w)
idx = 0
height = 0
height_min = 0
for i in range((2 * n)):
if (w[i] == 1):
height += n
else:
height -= (n + 1)
if (height < height_min):
height_min = height
idx = (i + 1)
w = (w[idx:] + w[:idx])
return self.element_class(self, w[1:])
def _iter_by_recursion(self):
'\n Iterate over ``self`` by recursively using the position of\n the first return to 0.\n\n EXAMPLES::\n\n sage: DW = DyckWords(4)\n sage: L = [d for d in DW._iter_by_recursion()]; L\n [[1, 0, 1, 0, 1, 0, 1, 0],\n [1, 0, 1, 0, 1, 1, 0, 0],\n [1, 0, 1, 1, 0, 0, 1, 0],\n [1, 0, 1, 1, 0, 1, 0, 0],\n [1, 0, 1, 1, 1, 0, 0, 0],\n [1, 1, 0, 0, 1, 0, 1, 0],\n [1, 1, 0, 0, 1, 1, 0, 0],\n [1, 1, 0, 1, 0, 0, 1, 0],\n [1, 1, 1, 0, 0, 0, 1, 0],\n [1, 1, 0, 1, 0, 1, 0, 0],\n [1, 1, 0, 1, 1, 0, 0, 0],\n [1, 1, 1, 0, 0, 1, 0, 0],\n [1, 1, 1, 0, 1, 0, 0, 0],\n [1, 1, 1, 1, 0, 0, 0, 0]]\n sage: len(L) == DW.cardinality()\n True\n '
if (self.k1 <= 2):
if (self.k1 == 0):
(yield self.element_class(self, []))
elif (self.k1 == 1):
(yield self.element_class(self, [1, 0]))
elif (self.k1 == 2):
(yield self.element_class(self, [1, 0, 1, 0]))
(yield self.element_class(self, [1, 1, 0, 0]))
return
P = [CompleteDyckWords_size(i) for i in range(self.k1)]
for i in range(self.k1):
for p in P[i]._iter_by_recursion():
list_1p0 = (([1] + list(p)) + [0])
for s in P[((- i) - 1)]._iter_by_recursion():
(yield self.element_class(self, (list_1p0 + list(s))))
|
def is_area_sequence(seq) -> bool:
'\n Test if a sequence `l` of integers satisfies `l_0 = 0` and\n `0 \\leq l_{i+1} \\leq l_i + 1` for `i > 0`.\n\n EXAMPLES::\n\n sage: from sage.combinat.dyck_word import is_area_sequence\n sage: is_area_sequence([0,2,0])\n False\n sage: is_area_sequence([1,2,3])\n False\n sage: is_area_sequence([0,1,0])\n True\n sage: is_area_sequence([0,1,2])\n True\n sage: is_area_sequence([])\n True\n '
if (not seq):
return True
return ((seq[0] == 0) and all(((0 <= seq[(i + 1)] <= (seq[i] + 1)) for i in range((len(seq) - 1)))))
|
def is_a(obj, k1=None, k2=None) -> bool:
'\n Test if ``obj`` is a Dyck word with exactly ``k1`` open symbols and\n exactly ``k2`` close symbols.\n\n If ``k1`` is not specified, then the number of open symbols can be\n arbitrary. If ``k1`` is specified but ``k2`` is not, then ``k2`` is\n set to be ``k1``.\n\n EXAMPLES::\n\n sage: from sage.combinat.dyck_word import is_a\n sage: is_a([1,1,0,0])\n True\n sage: is_a([1,0,1,0])\n True\n sage: is_a([1,1,0,0], 2)\n True\n sage: is_a([1,1,0,0], 3)\n False\n sage: is_a([1,1,0,0], 3, 2)\n False\n sage: is_a([1,1,0])\n True\n sage: is_a([0,1,0])\n False\n sage: is_a([1,0,0])\n False\n sage: is_a([1,1,0],2,1)\n True\n sage: is_a([1,1,0],2)\n False\n sage: is_a([1,1,0],1,1)\n False\n '
if (k1 is not None):
if (k2 is None):
k2 = k1
elif (k1 < k2):
raise ValueError(('k1 (= %s) must be >= k2 (= %s)' % (k1, k2)))
n_opens = 0
n_closes = 0
for p in obj:
if (p == open_symbol):
n_opens += 1
elif (p == close_symbol):
if (n_opens == n_closes):
return False
n_closes += 1
else:
return False
return (((k1 is None) and (k2 is None)) or ((n_opens == k1) and (n_closes == k2)))
|
def pealing(D, return_touches=False):
'\n A helper function for computing the bijection from a Dyck word to a\n `231`-avoiding permutation using the bijection "Stump". For details\n see [Stu2008]_.\n\n .. SEEALSO::\n\n :meth:`~sage.combinat.dyck_word.DyckWord_complete.to_noncrossing_partition`\n\n EXAMPLES::\n\n sage: from sage.combinat.dyck_word import pealing\n sage: pealing(DyckWord([1,1,0,0]))\n [1, 0, 1, 0]\n sage: pealing(DyckWord([1,0,1,0]))\n [1, 0, 1, 0]\n sage: pealing(DyckWord([1, 1, 0, 0, 1, 1, 1, 0, 0, 0]))\n [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]\n sage: pealing(DyckWord([1,1,0,0]),return_touches=True)\n ([1, 0, 1, 0], [[1, 2]])\n sage: pealing(DyckWord([1,0,1,0]),return_touches=True)\n ([1, 0, 1, 0], [])\n sage: pealing(DyckWord([1, 1, 0, 0, 1, 1, 1, 0, 0, 0]),return_touches=True)\n ([1, 0, 1, 0, 1, 0, 1, 0, 1, 0], [[1, 2], [3, 5]])\n '
n = D.semilength()
area = D.to_area_sequence()
new_area = []
touch_sequences = []
touches = []
for i in range((n - 1)):
if (area[(i + 1)] == 0):
touches.append((i + 1))
if (len(touches) > 1):
touch_sequences.append(touches)
touches = []
elif (area[i] == 0):
touches = []
new_area.append(0)
elif (area[(i + 1)] == 1):
new_area.append(0)
touches.append((i + 1))
else:
new_area.append((area[(i + 1)] - 2))
new_area.append(0)
if area[(n - 1)]:
touches.append(n)
if (len(touches) > 1):
touch_sequences.append(touches)
D = DyckWords().from_area_sequence(new_area)
if return_touches:
return (D, touch_sequences)
else:
return D
|
@richcmp_method
class Face(SageObject):
'\n A class to model a unit face of arbitrary dimension.\n\n A unit face in dimension `d` is represented by\n a `d`-dimensional vector ``v`` and a type ``t`` in `\\{1, \\ldots, d\\}`.\n The type of the face corresponds to the canonical unit vector\n to which the face is orthogonal.\n The optional ``color`` argument is used in plotting functions.\n\n INPUT:\n\n - ``v`` - tuple of integers\n - ``t`` - integer in ``[1, ..., len(v)]``, type of the face. The face of type `i`\n is orthogonal to the canonical vector `e_i`.\n - ``color`` - color (optional, default: ``None``) color of the face,\n used for plotting only. If ``None``, its value is guessed from the\n face type.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face\n sage: f = Face((0,2,0), 3)\n sage: f.vector()\n (0, 2, 0)\n sage: f.type()\n 3\n\n ::\n\n sage: f = Face((0,2,0), 3, color=(0.5, 0.5, 0.5))\n sage: f.color()\n RGB color (0.5, 0.5, 0.5)\n '
def __init__(self, v, t, color=None):
'\n Face constructor. See class doc for more information.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face\n sage: f = Face((0,2,0), 3)\n sage: f.vector()\n (0, 2, 0)\n sage: f.type()\n 3\n\n TESTS:\n\n We test that types can be given by an int (see :trac:`10699`)::\n\n sage: f = Face((0,2,0), int(1))\n '
self._vector = (ZZ ** len(v))(v)
self._vector.set_immutable()
if (not ((t in ZZ) and (1 <= t <= len(v)))):
raise ValueError('the type must be an integer between 1 and len(v)')
self._type = t
if (color is None):
if (self._type == 1):
color = Color((1, 0, 0))
elif (self._type == 2):
color = Color((0, 1, 0))
elif (self._type == 3):
color = Color((0, 0, 1))
else:
color = Color()
self._color = Color(color)
def __repr__(self) -> str:
'\n String representation of a face.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face\n sage: f = Face((0,0,0,3), 3)\n sage: f\n [(0, 0, 0, 3), 3]*\n\n ::\n\n sage: f = Face((0,0,0,3), 3)\n sage: f\n [(0, 0, 0, 3), 3]*\n '
return ('[%s, %s]*' % (self.vector(), self.type()))
__richcmp__ = richcmp_by_eq_and_lt('_eq', '_lt')
def _eq(self, other) -> bool:
'\n Equality of faces.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face\n sage: f = Face((0,0,0,3), 3)\n sage: g = Face((0,0,0,3), 3)\n sage: f == g\n True\n '
return (isinstance(other, Face) and (self.vector() == other.vector()) and (self.type() == other.type()))
def _lt(self, other) -> bool:
'\n Compare ``self`` and ``other``.\n\n The vectors of the faces are first compared,\n and the types of the faces are compared if the vectors are equal.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face\n sage: Face([-2,1,0], 2) < Face([-1,2,2],3)\n True\n sage: Face([-2,1,0], 2) < Face([-2,1,0],3)\n True\n sage: Face([-2,1,0], 2) < Face([-2,1,0],2)\n False\n '
if (self.vector() < other.vector()):
return True
if (self.vector() == other.vector()):
return (self.type() < other.type())
return False
def __hash__(self) -> int:
'\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face\n sage: f = Face((0,0,0,3), 3)\n sage: g = Face((0,0,0,3), 3)\n sage: hash(f) == hash(g)\n True\n '
return hash((self.vector(), self.type()))
def __add__(self, other):
'\n Addition of self with a Face, a Patch or a finite iterable of faces.\n\n INPUT:\n\n - ``other`` - a Patch or a Face or a finite iterable of faces\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: f = Face([0,0,0], 3)\n sage: g = Face([0,1,-1], 2)\n sage: f + g\n Patch: [[(0, 0, 0), 3]*, [(0, 1, -1), 2]*]\n sage: P = Patch([Face([0,0,0], 1), Face([0,0,0], 2)])\n sage: f + P\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(0, 0, 0), 3]*]\n\n Adding a finite iterable of faces::\n\n sage: from sage.combinat.e_one_star import Face\n sage: f = Face([0,0,0], 3)\n sage: f + [f,f]\n Patch: [[(0, 0, 0), 3]*]\n '
if isinstance(other, Face):
return Patch([self, other])
else:
return Patch(other).union(self)
def vector(self):
'\n Return the vector of the face.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face\n sage: f = Face((0,2,0), 3)\n sage: f.vector()\n (0, 2, 0)\n '
return self._vector
def type(self):
'\n Return the type of the face.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face\n sage: f = Face((0,2,0), 3)\n sage: f.type()\n 3\n\n ::\n\n sage: f = Face((0,2,0), 3)\n sage: f.type()\n 3\n '
return self._type
def color(self, color=None):
"\n Return or change the color of the face.\n\n INPUT:\n\n - ``color`` - string, rgb tuple, color (optional, default: ``None``)\n the new color to assign to the face. If ``None``, it returns the\n color of the face.\n\n OUTPUT:\n\n color or None\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face\n sage: f = Face((0,2,0), 3)\n sage: f.color()\n RGB color (0.0, 0.0, 1.0)\n sage: f.color('red')\n sage: f.color()\n RGB color (1.0, 0.0, 0.0)\n "
if (color is not None):
self._color = Color(color)
else:
return self._color
def _plot(self, projmat, face_contour, opacity) -> Graphics:
'\n Return a 2D graphic object representing the face.\n\n INPUT:\n\n - ``projmat`` - 2*3 projection matrix (used only for faces in three dimensions)\n - ``face_contour`` - dict, maps the face type to vectors describing\n the contour of unit faces (used only for faces in three dimensions)\n - ``opacity`` - the alpha value for the color of the face\n\n OUTPUT:\n\n 2D graphic object\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face\n sage: f = Face((0,0,3), 3)\n sage: projmat = matrix(2, [-1.7320508075688772*0.5, 1.7320508075688772*0.5, 0, -0.5, -0.5, 1])\n sage: face_contour = {}\n sage: face_contour[1] = map(vector, [(0,0,0),(0,1,0),(0,1,1),(0,0,1)])\n sage: face_contour[2] = map(vector, [(0,0,0),(0,0,1),(1,0,1),(1,0,0)])\n sage: face_contour[3] = map(vector, [(0,0,0),(1,0,0),(1,1,0),(0,1,0)])\n sage: G = f._plot(projmat, face_contour, 0.75) # needs sage.plot\n\n ::\n\n sage: f = Face((0,0), 2)\n sage: f._plot(None, None, 1) # needs sage.plot\n Graphics object consisting of 1 graphics primitive\n '
v = self.vector()
t = self.type()
G = Graphics()
if (len(v) == 2):
if (t == 1):
G += line([v, (v + vector([0, 1]))], rgbcolor=self.color(), thickness=1.5, alpha=opacity)
elif (t == 2):
G += line([v, (v + vector([1, 0]))], rgbcolor=self.color(), thickness=1.5, alpha=opacity)
elif (len(v) == 3):
G += polygon([(projmat * (u + v)) for u in face_contour[t]], alpha=opacity, thickness=1, rgbcolor=self.color())
else:
raise NotImplementedError('plotting is implemented only for patches in two or three dimensions.')
return G
def _plot3d(self, face_contour):
'\n 3D representation of a unit face (Jmol).\n\n INPUT:\n\n - ``face_contour`` - dict, maps the face type to vectors describing\n the contour of unit faces\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face\n sage: f = Face((0,0,3), 3)\n sage: face_contour = {1: map(vector, [(0,0,0),(0,1,0),(0,1,1),(0,0,1)]), 2: map(vector, [(0,0,0),(0,0,1),(1,0,1),(1,0,0)]), 3: map(vector, [(0,0,0),(1,0,0),(1,1,0),(0,1,0)])}\n sage: G = f._plot3d(face_contour) #not tested\n '
v = self.vector()
t = self.type()
c = self.color()
G = polygon([(u + v) for u in face_contour[t]], rgbcolor=c)
return G
|
class Patch(SageObject):
'\n A class to model a collection of faces. A patch is represented by an immutable set of Faces.\n\n .. NOTE::\n\n The dimension of a patch is the length of the vectors of the faces in the patch,\n which is assumed to be the same for every face in the patch.\n\n .. NOTE::\n\n Since version 4.7.1, Patches are immutable, except for the colors of the faces,\n which are not taken into account for equality tests and hash functions.\n\n INPUT:\n\n - ``faces`` - finite iterable of faces\n - ``face_contour`` - dict (optional, default:``None``) maps the face\n type to vectors describing the contour of unit faces. If None,\n defaults contour are assumed for faces of type 1, 2, 3 or 1, 2, 3.\n Used in plotting methods only.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: P\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(0, 0, 0), 3]*]\n\n ::\n\n sage: face_contour = {}\n sage: face_contour[1] = map(vector, [(0,0,0),(0,1,0),(0,1,1),(0,0,1)])\n sage: face_contour[2] = map(vector, [(0,0,0),(0,0,1),(1,0,1),(1,0,0)])\n sage: face_contour[3] = map(vector, [(0,0,0),(1,0,0),(1,1,0),(0,1,0)])\n sage: Patch([Face((0,0,0),t) for t in [1,2,3]], face_contour=face_contour)\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(0, 0, 0), 3]*]\n '
def __init__(self, faces, face_contour=None):
"\n Constructor of a patch (set of faces).\n\n See class doc for more information.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: P\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(0, 0, 0), 3]*]\n\n TESTS:\n\n We test that colors are not anymore mixed up between\n Patches (see :trac:`11255`)::\n\n sage: P = Patch([Face([0,0,0],2)])\n sage: Q = Patch(P)\n sage: next(iter(P)).color()\n RGB color (0.0, 1.0, 0.0)\n sage: next(iter(Q)).color('yellow')\n sage: next(iter(P)).color()\n RGB color (0.0, 1.0, 0.0)\n "
self._faces = frozenset((Face(f.vector(), f.type(), f.color()) for f in faces))
try:
f0 = next(iter(self._faces))
except StopIteration:
self._dimension = None
else:
self._dimension = len(f0.vector())
if (face_contour is not None):
self._face_contour = face_contour
else:
self._face_contour = {1: [vector(t) for t in [(0, 0, 0), (0, 1, 0), (0, 1, 1), (0, 0, 1)]], 2: [vector(t) for t in [(0, 0, 0), (0, 0, 1), (1, 0, 1), (1, 0, 0)]], 3: [vector(t) for t in [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]]}
def __eq__(self, other) -> bool:
'\n Equality test for Patch.\n\n INPUT:\n\n - ``other`` - an object\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: P = Patch([Face((0,0,0),1), Face((0,0,0),2), Face((0,0,0),3)])\n sage: Q = Patch([Face((0,1,0),1), Face((0,0,0),3)])\n sage: P == P\n True\n sage: P == Q\n False\n sage: P == 4\n False\n\n ::\n\n sage: s = WordMorphism({1:[1,3], 2:[1,2,3], 3:[3]})\n sage: t = WordMorphism({1:[1,2,3], 2:[2,3], 3:[3]})\n sage: P = Patch([Face((0,0,0), 1), Face((0,0,0), 2), Face((0,0,0), 3)])\n sage: E1Star(s)(P) == E1Star(t)(P)\n False\n sage: E1Star(s*t)(P) == E1Star(t)(E1Star(s)(P))\n True\n '
return (isinstance(other, Patch) and (self._faces == other._faces))
def __hash__(self) -> int:
"\n Hash function of Patch.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: x = [Face((0,0,0),t) for t in [1,2,3]]\n sage: P = Patch(x)\n sage: hash(P) #random\n -4839605361791007520\n\n TESTS:\n\n We test that two equal patches have the same hash (see :trac:`11255`)::\n\n sage: P = Patch([Face([0,0,0],1), Face([0,0,0],2)])\n sage: Q = Patch([Face([0,0,0],2), Face([0,0,0],1)])\n sage: P == Q\n True\n sage: hash(P) == hash(Q)\n True\n\n Changing the color does not affect the hash value::\n\n sage: p = Patch([Face((0,0,0), t) for t in [1,2,3]])\n sage: H1 = hash(p)\n sage: p.repaint(['blue'])\n sage: H2 = hash(p)\n sage: H1 == H2\n True\n "
return hash(self._faces)
def __len__(self) -> int:
'\n Return the number of faces contained in the patch.\n\n OUTPUT:\n\n integer\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: x = [Face((0,0,0),t) for t in [1,2,3]]\n sage: P = Patch(x)\n sage: len(P) #indirect doctest\n 3\n '
return len(self._faces)
def __iter__(self):
"\n Return an iterator over the faces of the patch.\n\n OUTPUT:\n\n iterator\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: x = [Face((0,0,0),t) for t in [1,2,3]]\n sage: P = Patch(x)\n sage: it = iter(P)\n sage: type(next(it))\n <class 'sage.combinat.e_one_star.Face'>\n sage: type(next(it))\n <class 'sage.combinat.e_one_star.Face'>\n sage: type(next(it))\n <class 'sage.combinat.e_one_star.Face'>\n sage: type(next(it))\n Traceback (most recent call last):\n ...\n StopIteration\n "
return iter(self._faces)
def __add__(self, other):
'\n Addition of patches (union).\n\n INPUT:\n\n - ``other`` - a Patch or a Face or a finite iterable of faces\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: P = Patch([Face([0,0,0], 1), Face([0,0,0], 2)])\n sage: Q = P.translate([1,-1,0])\n sage: P + Q\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(1, -1, 0), 1]*, [(1, -1, 0), 2]*]\n sage: P + Face([0,0,0],3)\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(0, 0, 0), 3]*]\n sage: P + [Face([0,0,0],3), Face([1,1,1],2)]\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(0, 0, 0), 3]*, [(1, 1, 1), 2]*]\n '
return self.union(other)
def __sub__(self, other):
'\n Subtraction of patches (difference).\n\n INPUT:\n\n - ``other`` - a Patch or a Face or a finite iterable of faces\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: P - Face([0,0,0],2)\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 3]*]\n sage: P - P\n Patch: []\n '
return self.difference(other)
def __repr__(self) -> str:
'\n String representation of a patch.\n\n Displays all the faces if there less than 20,\n otherwise displays only the number of faces.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: x = [Face((0,0,0),t) for t in [1,2,3]]\n sage: P = Patch(x)\n sage: P\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(0, 0, 0), 3]*]\n\n ::\n\n sage: x = [Face((0,0,a),1) for a in range(25)]\n sage: P = Patch(x)\n sage: P\n Patch of 25 faces\n '
if (len(self) <= 20):
L = list(self)
L.sort(key=(lambda x: (x.vector(), x.type())))
return ('Patch: %s' % L)
else:
return ('Patch of %s faces' % len(self))
def union(self, other) -> Patch:
'\n Return a Patch consisting of the union of self and other.\n\n INPUT:\n\n - ``other`` - a Patch or a Face or a finite iterable of faces\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: P = Patch([Face((0,0,0),1), Face((0,0,0),2)])\n sage: P.union(Face((1,2,3), 3))\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(1, 2, 3), 3]*]\n sage: P.union([Face((1,2,3), 3), Face((2,3,3), 2)])\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(1, 2, 3), 3]*, [(2, 3, 3), 2]*]\n '
if isinstance(other, Face):
return Patch(self._faces.union([other]))
else:
return Patch(self._faces.union(other))
def difference(self, other) -> Patch:
'\n Return the difference of self and other.\n\n INPUT:\n\n - ``other`` - a finite iterable of faces or a single face\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: P.difference(Face([0,0,0],2))\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 3]*]\n sage: P.difference(P)\n Patch: []\n '
if isinstance(other, Face):
return Patch(self._faces.difference([other]))
else:
return Patch(self._faces.difference(other))
def dimension(self) -> (None | int):
'\n Return the dimension of the vectors of the faces of self\n\n It returns ``None`` if self is the empty patch.\n\n The dimension of a patch is the length of the vectors of the faces in the patch,\n which is assumed to be the same for every face in the patch.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: P.dimension()\n 3\n\n TESTS::\n\n sage: from sage.combinat.e_one_star import Patch\n sage: p = Patch([])\n sage: p.dimension() is None\n True\n\n It works when the patch is created from an iterator::\n\n sage: p = Patch(Face((0,0,0),t) for t in [1,2,3])\n sage: p.dimension()\n 3\n '
return self._dimension
def faces_of_vector(self, v) -> list[Face]:
'\n Return a list of the faces whose vector is ``v``.\n\n INPUT:\n\n - ``v`` - a vector\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: P = Patch([Face((0,0,0),1), Face((1,2,0),3), Face((1,2,0),1)])\n sage: sorted(P.faces_of_vector([1,2,0]))\n [[(1, 2, 0), 1]*, [(1, 2, 0), 3]*]\n '
v = vector(v)
return [f for f in self if (f.vector() == v)]
def faces_of_type(self, t) -> list[Face]:
'\n Return a list of the faces that have type ``t``.\n\n INPUT:\n\n - ``t`` - integer or any other type\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: P = Patch([Face((0,0,0),1), Face((1,2,0),3), Face((1,2,0),1)])\n sage: sorted(P.faces_of_type(1))\n [[(0, 0, 0), 1]*, [(1, 2, 0), 1]*]\n '
return [f for f in self if (f.type() == t)]
def faces_of_color(self, color) -> list[Face]:
"\n Return a list of the faces that have the given color.\n\n INPUT:\n\n - ``color`` - color\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: P = Patch([Face((0,0,0),1, 'red'), Face((1,2,0),3, 'blue'), Face((1,2,0),1, 'red')])\n sage: sorted(P.faces_of_color('red'))\n [[(0, 0, 0), 1]*, [(1, 2, 0), 1]*]\n "
color = tuple(Color(color))
return [f for f in self if (tuple(f.color()) == color)]
def translate(self, v) -> Patch:
'\n Return a translated copy of self by vector ``v``.\n\n INPUT:\n\n - ``v`` - vector or tuple\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: P = Patch([Face((0,0,0),1), Face((1,2,0),3), Face((1,2,0),1)])\n sage: P.translate([-1,-2,0])\n Patch: [[(-1, -2, 0), 1]*, [(0, 0, 0), 1]*, [(0, 0, 0), 3]*]\n '
v = vector(v)
return Patch((Face((f.vector() + v), f.type(), f.color()) for f in self))
def occurrences_of(self, other) -> list:
'\n Return all positions at which other appears in self, that is,\n all vectors v such that ``set(other.translate(v)) <= set(self)``.\n\n INPUT:\n\n - ``other`` - a Patch\n\n OUTPUT:\n\n a list of vectors\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import Face, Patch, E1Star\n sage: P = Patch([Face([0,0,0], 1), Face([0,0,0], 2), Face([0,0,0], 3)])\n sage: Q = Patch([Face([0,0,0], 1), Face([0,0,0], 2)])\n sage: P.occurrences_of(Q)\n [(0, 0, 0)]\n sage: Q = Q.translate([1,2,3])\n sage: P.occurrences_of(Q)\n [(-1, -2, -3)]\n\n ::\n\n sage: E = E1Star(WordMorphism({1:[1,2], 2:[1,3], 3:[1]}))\n sage: P = Patch([Face([0,0,0], 1), Face([0,0,0], 2), Face([0,0,0], 3)])\n sage: P = E(P,4)\n sage: Q = Patch([Face([0,0,0], 1), Face([0,0,0], 2)])\n sage: L = P.occurrences_of(Q)\n sage: sorted(L)\n [(0, 0, 0), (0, 0, 1), (0, 1, -1), (1, 0, -1), (1, 1, -3), (1, 1, -2)]\n '
f0 = next(iter(other))
x = f0.vector()
t = f0.type()
L = self.faces_of_type(t)
positions = []
for f in L:
y = f.vector()
if other.translate((y - x))._faces.issubset(self._faces):
positions.append((y - x))
return positions
def repaint(self, cmap='Set1') -> None:
"\n Repaint all the faces of self from the given color map.\n\n This only changes the colors of the faces of self.\n\n INPUT:\n\n - ``cmap`` - color map (default: ``'Set1'``). It can be one of the\n following:\n\n - string -- A coloring map. For available coloring map names type:\n ``sorted(colormaps)``\n - list -- a list of colors to assign cyclically to the faces.\n A list of a single color colors all the faces with the same color.\n - dict -- a dict of face types mapped to colors, to color the\n faces according to their type.\n - ``{}``, the empty dict - shortcut for\n ``{1:'red', 2:'green', 3:'blue'}``.\n\n EXAMPLES:\n\n Using a color map::\n\n sage: from sage.combinat.e_one_star import Face, Patch\n sage: color = (0, 0, 0)\n sage: P = Patch([Face((0,0,0),t,color) for t in [1,2,3]])\n sage: for f in P: f.color()\n RGB color (0.0, 0.0, 0.0)\n RGB color (0.0, 0.0, 0.0)\n RGB color (0.0, 0.0, 0.0)\n sage: P.repaint()\n sage: next(iter(P)).color() #random\n RGB color (0.498..., 0.432..., 0.522...)\n\n Using a list of colors::\n\n sage: P = Patch([Face((0,0,0),t,color) for t in [1,2,3]])\n sage: P.repaint([(0.9, 0.9, 0.9), (0.65,0.65,0.65), (0.4,0.4,0.4)])\n sage: for f in P: f.color()\n RGB color (0.9, 0.9, 0.9)\n RGB color (0.65, 0.65, 0.65)\n RGB color (0.4, 0.4, 0.4)\n\n Using a dictionary to color faces according to their type::\n\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: P.repaint({1:'black', 2:'yellow', 3:'green'})\n sage: P.plot() #not tested\n sage: P.repaint({})\n sage: P.plot() #not tested\n "
if (cmap == {}):
cmap = {1: 'red', 2: 'green', 3: 'blue'}
if isinstance(cmap, dict):
for f in self:
f.color(cmap[f.type()])
elif isinstance(cmap, list):
L = len(cmap)
for (i, f) in enumerate(self):
f.color(cmap[(i % L)])
elif isinstance(cmap, str):
global cm
if (cm is None):
from matplotlib import cm
assert (cm is not None)
if (cmap not in cm.datad):
raise RuntimeError(('color map %s not known (type sorted(colors) for valid names)' % cmap))
cmap = cm.__dict__[cmap]
dim = float(len(self))
for (i, f) in enumerate(self):
f.color(cmap((i / dim))[:3])
else:
raise TypeError(('type of cmap (=%s) must be dict, list or str' % cmap))
def plot(self, projmat=None, opacity=0.75) -> Graphics:
'\n Return a 2D graphic object depicting the patch.\n\n INPUT:\n\n - ``projmat`` - matrix (optional, default: ``None``) the projection\n matrix. Its number of lines must be two. Its number of columns\n must equal the dimension of the ambient space of the faces. If\n ``None``, the isometric projection is used by default.\n\n - ``opacity`` - float between ``0`` and ``1`` (optional, default: ``0.75``)\n opacity of the face\n\n .. WARNING::\n\n Plotting is implemented only for patches in two or three dimensions.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: P.plot() # needs sage.plot\n Graphics object consisting of 3 graphics primitives\n\n ::\n\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: P = E(P, 5)\n sage: P.plot() # needs sage.plot\n Graphics object consisting of 57 graphics primitives\n\n Plot with a different projection matrix::\n\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: M = matrix(2, 3, [1,0,-1,0.3,1,-3])\n sage: P = E(P, 3)\n sage: P.plot(projmat=M) # needs sage.plot\n Graphics object consisting of 17 graphics primitives\n\n Plot patches made of unit segments::\n\n sage: P = Patch([Face([0,0], 1), Face([0,0], 2)])\n sage: E = E1Star(WordMorphism({1:[1,2],2:[1]}))\n sage: F = E1Star(WordMorphism({1:[1,1,2],2:[2,1]}))\n sage: E(P,5).plot() # needs sage.plot\n Graphics object consisting of 21 graphics primitives\n sage: F(P,3).plot() # needs sage.plot\n Graphics object consisting of 34 graphics primitives\n '
if (self.dimension() == 2):
G = Graphics()
for face in self:
G += face._plot(None, None, 1)
G.set_aspect_ratio(1)
return G
if (self.dimension() == 3):
if (projmat is None):
projmat = matrix(2, [((- 1.7320508075688772) * 0.5), (1.7320508075688772 * 0.5), 0, (- 0.5), (- 0.5), 1])
G = Graphics()
for face in self:
G += face._plot(projmat, self._face_contour, opacity)
G.set_aspect_ratio(1)
return G
else:
raise NotImplementedError('plotting is implemented only for patches in two or three dimensions.')
def plot3d(self):
'\n Return a 3D graphics object depicting the patch.\n\n .. WARNING::\n\n 3D plotting is implemented only for patches in three dimensions.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: P.plot3d() #not tested\n\n ::\n\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: P = E(P, 5)\n sage: P.repaint()\n sage: P.plot3d() #not tested\n '
if (self.dimension() != 3):
raise NotImplementedError('3D plotting is implemented only for patches in three dimensions')
face_list = [face._plot3d(self._face_contour) for face in self]
G = sum(face_list)
return G
def plot_tikz(self, projmat=None, print_tikz_env=True, edgecolor='black', scale=0.25, drawzero=False, extra_code_before='', extra_code_after='') -> str:
'\n Return a string containing some TikZ code to be included into\n a LaTeX document, depicting the patch.\n\n .. WARNING::\n\n Tikz Plotting is implemented only for patches in three dimensions.\n\n INPUT:\n\n - ``projmat`` - matrix (optional, default: ``None``) the projection\n matrix. Its number of lines must be two. Its number of columns\n must equal the dimension of the ambient space of the faces. If\n ``None``, the isometric projection is used by default.\n - ``print_tikz_env`` - bool (optional, default: ``True``) if ``True``,\n the tikzpicture environment are printed\n - ``edgecolor`` - string (optional, default: ``\'black\'``) either\n ``\'black\'`` or ``\'facecolor\'`` (color of unit face edges)\n - ``scale`` - real number (optional, default: ``0.25``) scaling\n constant for the whole figure\n - ``drawzero`` - bool (optional, default: ``False``) if ``True``,\n mark the origin by a black dot\n - ``extra_code_before`` - string (optional, default: ``\'\'``) extra code to\n include in the tikz picture\n - ``extra_code_after`` - string (optional, default: ``\'\'``) extra code to\n include in the tikz picture\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: s = P.plot_tikz()\n sage: len(s)\n 602\n sage: print(s) #not tested\n \\begin{tikzpicture}\n [x={(-0.216506cm,-0.125000cm)}, y={(0.216506cm,-0.125000cm)}, z={(0.000000cm,0.250000cm)}]\n \\definecolor{facecolor}{rgb}{0.000,1.000,0.000}\n \\fill[fill=facecolor, draw=black, shift={(0,0,0)}]\n (0, 0, 0) -- (0, 0, 1) -- (1, 0, 1) -- (1, 0, 0) -- cycle;\n \\definecolor{facecolor}{rgb}{1.000,0.000,0.000}\n \\fill[fill=facecolor, draw=black, shift={(0,0,0)}]\n (0, 0, 0) -- (0, 1, 0) -- (0, 1, 1) -- (0, 0, 1) -- cycle;\n \\definecolor{facecolor}{rgb}{0.000,0.000,1.000}\n \\fill[fill=facecolor, draw=black, shift={(0,0,0)}]\n (0, 0, 0) -- (1, 0, 0) -- (1, 1, 0) -- (0, 1, 0) -- cycle;\n \\end{tikzpicture}\n\n ::\n\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: P = E(P, 4)\n sage: from sage.misc.latex import latex #not tested\n sage: latex.add_to_preamble(\'\\\\usepackage{tikz}\') #not tested\n sage: view(P) #not tested\n\n Plot using shades of gray (useful for article figures)::\n\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: P.repaint([(0.9, 0.9, 0.9), (0.65,0.65,0.65), (0.4,0.4,0.4)])\n sage: P = E(P, 4)\n sage: s = P.plot_tikz()\n\n Plotting with various options::\n\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: M = matrix(2,3,[float(u) for u in [1,0,-0.7071,0,1,-0.7071]])\n sage: P = E(P, 3)\n sage: s = P.plot_tikz(projmat=M, edgecolor=\'facecolor\', scale=0.6, drawzero=True)\n\n Adding X, Y, Z axes using the extra code feature::\n\n sage: length = 1.5\n sage: space = 0.3\n sage: axes = \'\'\n sage: axes += "\\\\draw[->, thick, black] (0,0,0) -- (%s, 0, 0);\\n" % length\n sage: axes += "\\\\draw[->, thick, black] (0,0,0) -- (0, %s, 0);\\n" % length\n sage: axes += "\\\\node at (%s,0,0) {$x$};\\n" % (length + space)\n sage: axes += "\\\\node at (0,%s,0) {$y$};\\n" % (length + space)\n sage: axes += "\\\\node at (0,0,%s) {$z$};\\n" % (length + space)\n sage: axes += "\\\\draw[->, thick, black] (0,0,0) -- (0, 0, %s);\\n" % length\n sage: cube = Patch([Face((0,0,0),1), Face((0,0,0),2), Face((0,0,0),3)])\n sage: options = dict(scale=0.5,drawzero=True,extra_code_before=axes)\n sage: s = cube.plot_tikz(**options)\n sage: len(s)\n 986\n sage: print(s) #not tested\n \\begin{tikzpicture}\n [x={(-0.433013cm,-0.250000cm)}, y={(0.433013cm,-0.250000cm)}, z={(0.000000cm,0.500000cm)}]\n \\draw[->, thick, black] (0,0,0) -- (1.50000000000000, 0, 0);\n \\draw[->, thick, black] (0,0,0) -- (0, 1.50000000000000, 0);\n \\node at (1.80000000000000,0,0) {$x$};\n \\node at (0,1.80000000000000,0) {$y$};\n \\node at (0,0,1.80000000000000) {$z$};\n \\draw[->, thick, black] (0,0,0) -- (0, 0, 1.50000000000000);\n \\definecolor{facecolor}{rgb}{0.000,1.000,0.000}\n \\fill[fill=facecolor, draw=black, shift={(0,0,0)}]\n (0, 0, 0) -- (0, 0, 1) -- (1, 0, 1) -- (1, 0, 0) -- cycle;\n \\definecolor{facecolor}{rgb}{1.000,0.000,0.000}\n \\fill[fill=facecolor, draw=black, shift={(0,0,0)}]\n (0, 0, 0) -- (0, 1, 0) -- (0, 1, 1) -- (0, 0, 1) -- cycle;\n \\definecolor{facecolor}{rgb}{0.000,0.000,1.000}\n \\fill[fill=facecolor, draw=black, shift={(0,0,0)}]\n (0, 0, 0) -- (1, 0, 0) -- (1, 1, 0) -- (0, 1, 0) -- cycle;\n \\node[circle,fill=black,draw=black,minimum size=1.5mm,inner sep=0pt] at (0,0,0) {};\n \\end{tikzpicture}\n '
if (self.dimension() != 3):
raise NotImplementedError('Tikz plotting is implemented only for patches in three dimensions')
if (projmat is None):
projmat = (matrix(2, [((- 1.7320508075688772) * 0.5), (1.7320508075688772 * 0.5), 0, (- 0.5), (- 0.5), 1]) * scale)
e1 = (projmat * vector([1, 0, 0]))
e2 = (projmat * vector([0, 1, 0]))
e3 = (projmat * vector([0, 0, 1]))
face_contour = self._face_contour
color = None
s = ''
if print_tikz_env:
s += '\\begin{tikzpicture}\n'
s += ('[x={(%fcm,%fcm)}, y={(%fcm,%fcm)}, z={(%fcm,%fcm)}]\n' % (e1[0], e1[1], e2[0], e2[1], e3[0], e3[1]))
s += extra_code_before
for f in self:
t = f.type()
(x, y, z) = f.vector()
if ((color is None) or (color != f.color())):
color = f.color()
s += ('\\definecolor{facecolor}{rgb}{%.3f,%.3f,%.3f}\n' % (color[0], color[1], color[2]))
s += ('\\fill[fill=facecolor, draw=%s, shift={(%d,%d,%d)}]\n' % (edgecolor, x, y, z))
s += (' -- '.join(map(str, face_contour[t])) + ' -- cycle;\n')
s += extra_code_after
if drawzero:
s += '\\node[circle,fill=black,draw=black,minimum size=1.5mm,inner sep=0pt] at (0,0,0) {};\n'
if print_tikz_env:
s += '\\end{tikzpicture}'
return LatexExpr(s)
_latex_ = plot_tikz
|
class E1Star(SageObject):
"\n A class to model the `E_1^*(\\sigma)` map associated with\n a unimodular substitution `\\sigma`.\n\n INPUT:\n\n - ``sigma`` - unimodular ``WordMorphism``, i.e. such that its incidence\n matrix has determinant `\\pm 1`.\n\n - ``method`` - 'prefix' or 'suffix' (optional, default: 'suffix')\n Enables to use an alternative definition `E_1^*(\\sigma)` substitutions,\n where the abelianized of the prefix` is used instead of the suffix.\n\n .. NOTE::\n\n The alphabet of the domain and the codomain of `\\sigma` must be\n equal, and they must be of the form ``[1, ..., d]``, where ``d``\n is a positive integer corresponding to the length of the vectors\n of the faces on which `E_1^*(\\sigma)` will act.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: E(P)\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(0, 0, 0), 3]*, [(0, 1, -1), 2]*, [(1, 0, -1), 1]*]\n\n ::\n\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma, method='prefix')\n sage: E(P)\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(0, 0, 0), 3]*, [(0, 0, 1), 1]*, [(0, 0, 1), 2]*]\n\n ::\n\n sage: x = [Face((0,0,0,0),1), Face((0,0,0,0),4)]\n sage: P = Patch(x)\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1,4], 4:[1]})\n sage: E = E1Star(sigma)\n sage: E(P)\n Patch: [[(0, 0, 0, 0), 3]*, [(0, 0, 0, 0), 4]*, [(0, 0, 1, -1), 3]*, [(0, 1, 0, -1), 2]*, [(1, 0, 0, -1), 1]*]\n "
def __init__(self, sigma, method='suffix'):
'\n E1Star constructor. See class doc for more information.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: E\n E_1^*(1->12, 2->13, 3->1)\n '
if (not isinstance(sigma, WordMorphism)):
raise TypeError(('sigma (=%s) must be an instance of WordMorphism' % sigma))
if (sigma.domain().alphabet() != sigma.codomain().alphabet()):
raise ValueError(('the domain and codomain of (%s) must be the same' % sigma))
if (abs(det(matrix(sigma))) != 1):
raise ValueError(('the substitution (%s) must be unimodular' % sigma))
first_letter = sigma.codomain().alphabet()[0]
if ((first_letter not in ZZ) or (first_letter < 1)):
raise ValueError(f'the substitution ({sigma}) must be defined on positive integers')
self._sigma = WordMorphism(sigma)
self._d = self._sigma.domain().alphabet().cardinality()
alphabet = self._sigma.domain().alphabet()
X = {}
for k in alphabet:
subst_im = self._sigma.image(k)
for (n, letter) in enumerate(subst_im):
if (method == 'suffix'):
image_word = subst_im[(n + 1):]
elif (method == 'prefix'):
image_word = subst_im[:n]
else:
raise ValueError("option 'method' can only be 'prefix' or 'suffix'")
if (letter not in X):
X[letter] = []
v = (self.inverse_matrix() * vector(image_word.abelian_vector()))
X[letter].append((v, k))
self._base_iter = X
def __eq__(self, other) -> bool:
"\n Equality test for E1Star morphisms.\n\n INPUT:\n\n - ``other`` - an object\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: s = WordMorphism({1:[1,3], 2:[1,2,3], 3:[3]})\n sage: t = WordMorphism({1:[1,2,3], 2:[2,3], 3:[3]})\n sage: S = E1Star(s)\n sage: T = E1Star(t)\n sage: S == T\n False\n sage: S2 = E1Star(s, method='prefix')\n sage: S == S2\n False\n "
return (isinstance(other, E1Star) and (self._base_iter == other._base_iter))
def __call__(self, patch, iterations=1) -> Patch:
'\n Applies a generalized substitution to a Patch; this returns a new object.\n\n The color of every new face in the image is given the same color as its preimage.\n\n INPUT:\n\n - ``patch`` - a patch\n - ``iterations`` - integer (optional, default: 1) number of iterations\n\n OUTPUT:\n\n a patch\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: E(P)\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(0, 0, 0), 3]*, [(0, 1, -1), 2]*, [(1, 0, -1), 1]*]\n sage: E(P, iterations=4)\n Patch of 31 faces\n\n TESTS:\n\n We test that iterations=0 works (see :trac:`10699`)::\n\n sage: P = Patch([Face((0,0,0),t) for t in [1,2,3]])\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: E(P, iterations=0)\n Patch: [[(0, 0, 0), 1]*, [(0, 0, 0), 2]*, [(0, 0, 0), 3]*]\n '
if (iterations == 0):
return Patch(patch)
elif (iterations < 0):
raise ValueError(('iterations (=%s) must be >= 0' % iterations))
else:
old_faces = patch
for _ in range(iterations):
new_faces = []
for f in old_faces:
new_faces.extend(self._call_on_face(f, color=f.color()))
old_faces = new_faces
return Patch(new_faces)
def __mul__(self, other) -> E1Star:
"\n Return the product of ``self`` and ``other``.\n\n The product satisfies the following rule:\n `E_1^*(\\sigma\\circ\\sigma') = E_1^*(\\sigma')` \\circ E_1^*(\\sigma)`\n\n INPUT:\n\n - ``other`` - an instance of E1Star\n\n OUTPUT:\n\n an instance of E1Star\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: s = WordMorphism({1:[2],2:[3],3:[1,2]})\n sage: t = WordMorphism({1:[1,3,1],2:[1],3:[1,1,3,2]})\n sage: E1Star(s) * E1Star(t)\n E_1^*(1->1, 2->1132, 3->1311)\n sage: E1Star(t * s)\n E_1^*(1->1, 2->1132, 3->1311)\n "
if (not isinstance(other, E1Star)):
raise TypeError(('other (=%s) must be an instance of E1Star' % other))
return E1Star((other.sigma() * self.sigma()))
def __repr__(self) -> str:
'\n String representation of a patch.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: E\n E_1^*(1->12, 2->13, 3->1)\n '
return ('E_1^*(%s)' % str(self._sigma))
def _call_on_face(self, face, color=None):
'\n Return an iterator of faces obtained by applying ``self`` on the face.\n\n INPUT:\n\n - ``face`` - a face\n - ``color`` - string, RGB tuple or color, (optional, default: None)\n RGB color\n\n OUTPUT:\n\n iterator of faces\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: f = Face((0,2,0), 1)\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: list(E._call_on_face(f))\n [[(3, 0, -3), 1]*, [(2, 1, -3), 2]*, [(2, 0, -2), 3]*]\n '
if (len(face.vector()) != self._d):
raise ValueError('the dimension of the faces must be equal to the size of the alphabet of the substitution')
x_new = (self.inverse_matrix() * face.vector())
t = face.type()
return (Face((x_new + v), k, color=color) for (v, k) in self._base_iter[t])
@cached_method
def matrix(self):
'\n Return the matrix associated with ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: E.matrix()\n [1 1 1]\n [1 0 0]\n [0 1 0]\n '
return self._sigma.incidence_matrix()
@cached_method
def inverse_matrix(self):
'\n Return the inverse of the matrix associated with ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: E.inverse_matrix()\n [ 0 1 0]\n [ 0 0 1]\n [ 1 -1 -1]\n\n '
return self.matrix().inverse()
def sigma(self) -> WordMorphism:
'\n Return the ``WordMorphism`` associated with ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.e_one_star import E1Star, Face, Patch\n sage: sigma = WordMorphism({1:[1,2], 2:[1,3], 3:[1]})\n sage: E = E1Star(sigma)\n sage: E.sigma()\n WordMorphism: 1->12, 2->13, 3->1\n '
return self._sigma
|
def full_group_by(l, key=None):
'\n Group iterable ``l`` by values of ``key``.\n\n INPUT:\n\n - iterable ``l``\n - key function ``key``\n\n OUTPUT:\n\n A list of pairs ``(k, elements)`` such that ``key(e)=k`` for all\n ``e`` in ``elements``.\n\n This is similar to :func:`itertools.groupby` except that lists are\n returned instead of iterables and no prior sorting is required.\n\n We do not require\n\n - that the keys are sortable (in contrast to the\n approach via :func:`sorted` and :func:`itertools.groupby`) and\n - that the keys are hashable (in contrast to the\n implementation proposed in `<https://stackoverflow.com/a/15250161>`_).\n\n However, it is required\n\n - that distinct keys have distinct ``str``-representations.\n\n The implementation is inspired by\n `<https://stackoverflow.com/a/15250161>`_, but non-hashable keys are\n allowed.\n\n EXAMPLES::\n\n sage: # needs sage.symbolic\n sage: from sage.combinat.finite_state_machine import full_group_by\n sage: t = [2/x, 1/x, 2/x]\n sage: r = full_group_by([0, 1, 2], key=lambda i: t[i])\n sage: sorted(r, key=lambda p: p[1])\n [(2/x, [0, 2]), (1/x, [1])]\n sage: from itertools import groupby\n sage: for k, elements in groupby(sorted([0, 1, 2],\n ....: key=lambda i:t[i]),\n ....: key=lambda i:t[i]):\n ....: print("{} {}".format(k, list(elements)))\n 2/x [0]\n 1/x [1]\n 2/x [2]\n\n Note that the behavior is different from :func:`itertools.groupby`\n because neither `1/x<2/x` nor `2/x<1/x` does hold.\n\n Here, the result ``r`` has been sorted in order to guarantee a\n consistent order for the doctest suite.\n '
if (key is None):
key = (lambda x: x)
elements = defaultdict(list)
original_keys = {}
for item in l:
k = key(item)
s = str(k)
if (s in original_keys):
if (original_keys[s] != k):
raise ValueError('two distinct elements with representation {}'.format(s))
else:
original_keys[s] = k
elements[s].append(item)
return [(original_keys[s], elements[s]) for s in sorted(elements)]
|
def equal(iterator):
'\n Checks whether all elements of ``iterator`` are equal.\n\n INPUT:\n\n - ``iterator`` -- an iterator of the elements to check\n\n OUTPUT:\n\n ``True`` or ``False``.\n\n This implements `<https://stackoverflow.com/a/3844832/1052778>`_.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import equal\n sage: equal([0, 0, 0])\n True\n sage: equal([0, 1, 0])\n False\n sage: equal([])\n True\n sage: equal(iter([None, None]))\n True\n\n We can test other properties of the elements than the elements\n themselves. In the following example, we check whether all tuples\n have the same lengths::\n\n sage: equal(len(x) for x in [(1, 2), (2, 3), (3, 1)])\n True\n sage: equal(len(x) for x in [(1, 2), (1, 2, 3), (3, 1)])\n False\n '
try:
iterator = iter(iterator)
first = next(iterator)
return all(((first == rest) for rest in iterator))
except StopIteration:
return True
|
def startswith(list_, prefix):
'\n Determine whether list starts with the given prefix.\n\n INPUT:\n\n - ``list_`` -- list\n - ``prefix`` -- list representing the prefix\n\n OUTPUT:\n\n ``True`` or ``False``.\n\n Similar to :meth:`str.startswith`.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import startswith\n sage: startswith([1, 2, 3], [1, 2])\n True\n sage: startswith([1], [1, 2])\n False\n sage: startswith([1, 3, 2], [1, 2])\n False\n '
if (len(prefix) > len(list_)):
return False
return (list_[:len(prefix)] == prefix)
|
def FSMLetterSymbol(letter):
"\n Return a string associated to the input letter.\n\n INPUT:\n\n - ``letter`` -- the input letter or ``None`` (representing the\n empty word).\n\n OUTPUT:\n\n If ``letter`` is ``None`` the symbol for the empty word\n ``FSMEmptyWordSymbol`` is returned, otherwise the string\n associated to the letter.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMLetterSymbol\n sage: FSMLetterSymbol(0)\n '0'\n sage: FSMLetterSymbol(None)\n '-'\n "
return (FSMEmptyWordSymbol if (letter is None) else repr(letter))
|
def FSMWordSymbol(word):
"\n Return a string of ``word``. It may returns the symbol of the\n empty word ``FSMEmptyWordSymbol``.\n\n INPUT:\n\n - ``word`` -- the input word.\n\n OUTPUT:\n\n A string of ``word``.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMWordSymbol\n sage: FSMWordSymbol([0, 1, 1])\n '0,1,1'\n "
if (not isinstance(word, list)):
return FSMLetterSymbol(word)
if (not word):
return FSMEmptyWordSymbol
return ','.join((FSMLetterSymbol(letter) for letter in word))
|
def is_FSMState(S):
"\n Tests whether or not ``S`` inherits from :class:`FSMState`.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import is_FSMState, FSMState\n sage: is_FSMState(FSMState('A'))\n True\n "
return isinstance(S, FSMState)
|
class FSMState(SageObject):
'\n Class for a state of a finite state machine.\n\n INPUT:\n\n - ``label`` -- the label of the state.\n\n - ``word_out`` -- (default: ``None``) a word that is written when\n the state is reached.\n\n - ``is_initial`` -- (default: ``False``)\n\n - ``is_final`` -- (default: ``False``)\n\n - ``final_word_out`` -- (default: ``None``) a word that is written when\n the state is reached as the last state of some input; only for final\n states.\n\n - ``initial_probability`` -- (default: ``None``) The probability of\n starting in this state if it is a state of a Markov chain.\n\n - ``hook`` -- (default: ``None``) A function which is called when\n the state is reached during processing input. It takes two input\n parameters: the first is the current state (to allow using the same\n hook for several states), the second is the current process\n iterator object (to have full access to everything; e.g. the\n next letter from the input tape can be read in). It can output\n the next transition, i.e. the transition to take next. If it\n returns ``None`` the process iterator chooses. Moreover, this\n function can raise a ``StopIteration`` exception to stop\n processing of a finite state machine the input immediately. See\n also the example below.\n\n - ``color`` -- (default: ``None``) In order to distinguish states,\n they can be given an arbitrary "color" (an arbitrary object).\n This is used in :meth:`FiniteStateMachine.equivalence_classes`:\n states of different colors are never considered to be\n equivalent. Note that :meth:`Automaton.determinisation` requires\n that ``color`` is hashable.\n\n - ``allow_label_None`` -- (default: ``False``) If ``True`` allows also\n ``None`` as label. Note that a state with label ``None`` is used in\n :class:`FSMProcessIterator`.\n\n OUTPUT:\n\n A state of a finite state machine.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState(\'state 1\', word_out=0, is_initial=True)\n sage: A\n \'state 1\'\n sage: A.label()\n \'state 1\'\n sage: B = FSMState(\'state 2\')\n sage: A == B\n False\n\n We can also define a final output word of a final state which is\n used if the input of a transducer leads to this state. Such final\n output words are used in subsequential transducers. ::\n\n sage: C = FSMState(\'state 3\', is_final=True, final_word_out=\'end\')\n sage: C.final_word_out\n [\'end\']\n\n The final output word can be a single letter, ``None`` or a list of\n letters::\n\n sage: A = FSMState(\'A\')\n sage: A.is_final = True\n sage: A.final_word_out = 2\n sage: A.final_word_out\n [2]\n sage: A.final_word_out = [2, 3]\n sage: A.final_word_out\n [2, 3]\n\n Only final states can have a final output word which is not\n ``None``::\n\n sage: B = FSMState(\'B\')\n sage: B.final_word_out is None\n True\n sage: B.final_word_out = 2\n Traceback (most recent call last):\n ...\n ValueError: Only final states can have a final output word,\n but state B is not final.\n\n Setting the ``final_word_out`` of a final state to ``None`` is the\n same as setting it to ``[]`` and is also the default for a final\n state::\n\n sage: C = FSMState(\'C\', is_final=True)\n sage: C.final_word_out\n []\n sage: C.final_word_out = None\n sage: C.final_word_out\n []\n sage: C.final_word_out = []\n sage: C.final_word_out\n []\n\n It is not allowed to use ``None`` as a label::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: FSMState(None)\n Traceback (most recent call last):\n ...\n ValueError: Label None reserved for a special state,\n choose another label.\n\n This can be overridden by::\n\n sage: FSMState(None, allow_label_None=True)\n None\n\n Note that :meth:`Automaton.determinisation` requires that ``color``\n is hashable::\n\n sage: A = Automaton([[0, 0, 0]], initial_states=[0])\n sage: A.state(0).color = []\n sage: A.determinisation()\n Traceback (most recent call last):\n ...\n TypeError: unhashable type: \'list\'\n sage: A.state(0).color = ()\n sage: A.determinisation()\n Automaton with 1 state\n\n We can use a hook function of a state to stop processing. This is\n done by raising a ``StopIteration`` exception. The following code\n demonstrates this::\n\n sage: T = Transducer([(0, 1, 9, \'a\'), (1, 2, 9, \'b\'),\n ....: (2, 3, 9, \'c\'), (3, 4, 9, \'d\')],\n ....: initial_states=[0],\n ....: final_states=[4],\n ....: input_alphabet=[9])\n sage: def stop(process, state, output):\n ....: raise StopIteration()\n sage: T.state(3).hook = stop\n sage: T.process([9, 9, 9, 9])\n (False, 3, [\'a\', \'b\', \'c\'])\n\n TESTS:\n\n Test for ``is_initial``::\n\n sage: T = Automaton([(0,0,0)])\n sage: T.initial_states()\n []\n sage: T.state(0).is_initial = True\n sage: T.initial_states()\n [0]\n\n Test for ``initial_probability``::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: S = FSMState(\'state\', initial_probability=1/3)\n sage: S.initial_probability\n 1/3\n '
is_initial = False
initial_probability = None
def __init__(self, label, word_out=None, is_initial=False, is_final=False, final_word_out=None, initial_probability=None, hook=None, color=None, allow_label_None=False):
"\n See :class:`FSMState` for more information.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: FSMState('final', is_final=True)\n 'final'\n\n TESTS::\n\n sage: A = FSMState('A', is_final=True)\n sage: A.final_word_out\n []\n sage: A.is_final = True\n sage: A = FSMState('A', is_final=True, final_word_out='end')\n sage: A.final_word_out\n ['end']\n sage: A = FSMState('A', is_final=True,\n ....: final_word_out=['e', 'n', 'd'])\n sage: A.final_word_out\n ['e', 'n', 'd']\n sage: A = FSMState('A', is_final=True, final_word_out=[])\n sage: A.final_word_out\n []\n sage: A = FSMState('A', is_final=True, final_word_out=None)\n sage: A.final_word_out\n []\n sage: A = FSMState('A', is_final=False)\n sage: A.final_word_out is None\n True\n sage: A.is_final = False\n sage: A = FSMState('A', is_final=False, final_word_out='end')\n Traceback (most recent call last):\n ...\n ValueError: Only final states can have a final output word,\n but state A is not final.\n sage: A = FSMState('A', is_final=False,\n ....: final_word_out=['e', 'n', 'd'])\n Traceback (most recent call last):\n ...\n ValueError: Only final states can have a final output word,\n but state A is not final.\n sage: A = FSMState('A', is_final=False, final_word_out=None)\n sage: A.final_word_out is None\n True\n sage: A = FSMState('A', is_final=False, final_word_out=[])\n Traceback (most recent call last):\n ...\n ValueError: Only final states can have a final output word,\n but state A is not final.\n "
if ((not allow_label_None) and (label is None)):
raise ValueError('Label None reserved for a special state, choose another label.')
self._label_ = label
if isinstance(word_out, list):
self.word_out = word_out
elif (word_out is not None):
self.word_out = [word_out]
else:
self.word_out = []
self.is_initial = is_initial
self._final_word_out_ = None
self.is_final = is_final
self.final_word_out = final_word_out
self.initial_probability = initial_probability
if (hook is not None):
if callable(hook):
self.hook = hook
else:
raise TypeError('Wrong argument for hook.')
self.color = color
def __lt__(self, other):
'\n Return ``True`` if label of ``self`` is less than label of ``other``.\n\n INPUT:\n\n - `other` -- a state.\n\n OUTPUT:\n\n ``True`` or ``False``\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: FSMState(0) < FSMState(1)\n True\n '
return (self.label() < other.label())
@property
def final_word_out(self):
"\n The final output word of a final state which is written if the\n state is reached as the last state of the input of the finite\n state machine. For a non-final state, the value is ``None``.\n\n ``final_word_out`` can be a single letter, a list or ``None``,\n but for a final-state, it is always saved as a list.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A', is_final=True, final_word_out=2)\n sage: A.final_word_out\n [2]\n sage: A.final_word_out = 3\n sage: A.final_word_out\n [3]\n sage: A.final_word_out = [3, 4]\n sage: A.final_word_out\n [3, 4]\n sage: A.final_word_out = None\n sage: A.final_word_out\n []\n sage: B = FSMState('B')\n sage: B.final_word_out is None\n True\n\n A non-final state cannot have a final output word::\n\n sage: B.final_word_out = [3, 4]\n Traceback (most recent call last):\n ...\n ValueError: Only final states can have a final\n output word, but state B is not final.\n "
return self._final_word_out_
@final_word_out.setter
def final_word_out(self, final_word_out):
"\n Sets the value of the final output word of a final state.\n\n INPUT:\n\n - ``final_word_out`` -- a list, any element or ``None``.\n\n OUTPUT:\n\n Nothing.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: B = FSMState('B')\n sage: B.final_word_out = []\n Traceback (most recent call last):\n ...\n ValueError: Only final states can have a final\n output word, but state B is not final.\n sage: B.final_word_out = None\n sage: B.final_word_out is None\n True\n\n The exception is raised also when the initial state is a tuple\n (see :trac:`18990`)::\n\n sage: A = Transducer(initial_states=[(0, 0)])\n sage: A.state((0, 0)).final_word_out = []\n Traceback (most recent call last):\n ...\n ValueError: Only final states can have a final output word,\n but state (0, 0) is not final.\n\n No exception is raised if we set the state to be a final one::\n\n sage: A.state((0, 0)).is_final=True\n sage: A.state((0, 0)).final_word_out = []\n sage: A.state((0, 0)).final_word_out == []\n True\n "
if (not self.is_final):
if (final_word_out is not None):
raise ValueError(('Only final states can have a final output word, but state %s is not final.' % (self.label(),)))
else:
self._final_word_out_ = None
elif isinstance(final_word_out, list):
self._final_word_out_ = final_word_out
elif (final_word_out is not None):
self._final_word_out_ = [final_word_out]
else:
self._final_word_out_ = []
@property
def is_final(self):
"\n Describes whether the state is final or not.\n\n ``True`` if the state is final and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A', is_final=True, final_word_out=3)\n sage: A.is_final\n True\n sage: A.is_final = False\n Traceback (most recent call last):\n ...\n ValueError: State A cannot be non-final, because it has a\n final output word. Only final states can have a final output\n word.\n sage: A.final_word_out = None\n sage: A.is_final = False\n sage: A.is_final\n False\n "
return (self.final_word_out is not None)
@is_final.setter
def is_final(self, is_final):
"\n Defines the state as a final state or a non-final state.\n\n INPUT:\n\n - ``is_final`` -- ``True`` if the state should be final and\n ``False`` otherwise.\n\n OUTPUT:\n\n Nothing.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A', is_final=True)\n sage: A.final_word_out\n []\n sage: A.is_final = False\n sage: A.final_word_out is None\n True\n sage: A = FSMState('A', is_final=True, final_word_out='a')\n sage: A.is_final = False\n Traceback (most recent call last):\n ...\n ValueError: State A cannot be non-final, because it has a\n final output word. Only final states can have a final output\n word.\n\n The exception is raised also when the final state is a tuple\n (see :trac:`18990`)::\n\n sage: A = Transducer(final_states=[(0, 0)])\n sage: A.state((0, 0)).final_word_out = [1]\n sage: A.state((0, 0)).is_final = False\n Traceback (most recent call last):\n ...\n ValueError: State (0, 0) cannot be non-final, because it has\n a final output word. Only final states can have a final\n output word.\n\n No exception is raised if we empty the final_word_out of the\n state::\n\n sage: A.state((0, 0)).final_word_out = []\n sage: A.state((0, 0)).is_final = False\n sage: A.state((0, 0)).is_final\n False\n\n sage: A = FSMState('A', is_final=True, final_word_out=[])\n sage: A.is_final = False\n sage: A.final_word_out is None\n True\n "
if (is_final and (self.final_word_out is None)):
self._final_word_out_ = []
elif (not is_final):
if (not self.final_word_out):
self._final_word_out_ = None
else:
raise ValueError(('State %s cannot be non-final, because it has a final output word. Only final states can have a final output word. ' % (self.label(),)))
def label(self):
"\n Return the label of the state.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n The label of the state.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('state')\n sage: A.label()\n 'state'\n "
return self._label_
def __copy__(self):
"\n Return a (shallow) copy of the state.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A new state.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A')\n sage: A.is_initial = True\n sage: A.is_final = True\n sage: A.final_word_out = [1]\n sage: A.color = 'green'\n sage: A.initial_probability = 1/2\n sage: B = copy(A)\n sage: B.fully_equal(A)\n True\n sage: A.label() is B.label()\n True\n sage: A.is_initial is B.is_initial\n True\n sage: A.is_final is B.is_final\n True\n sage: A.final_word_out is B.final_word_out\n True\n sage: A.color is B.color\n True\n sage: A.initial_probability is B.initial_probability\n True\n "
new = FSMState(self.label(), self.word_out, self.is_initial, self.is_final, color=self.color, final_word_out=self.final_word_out, initial_probability=self.initial_probability)
if hasattr(self, 'hook'):
new.hook = self.hook
return new
copy = __copy__
def __deepcopy__(self, memo):
"\n Return a deep copy of the state.\n\n INPUT:\n\n - ``memo`` -- a dictionary storing already processed elements.\n\n OUTPUT:\n\n A new state.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A')\n sage: deepcopy(A)\n 'A'\n "
try:
label = self._deepcopy_relabel_
except AttributeError:
label = deepcopy(self.label(), memo)
new = FSMState(label, deepcopy(self.word_out, memo), self.is_initial, self.is_final)
if hasattr(self, 'hook'):
new.hook = deepcopy(self.hook, memo)
new.color = deepcopy(self.color, memo)
new.final_word_out = deepcopy(self.final_word_out, memo)
new.initial_probability = deepcopy(self.initial_probability, memo)
return new
def deepcopy(self, memo=None):
'\n Return a deep copy of the state.\n\n INPUT:\n\n - ``memo`` -- (default: ``None``) a dictionary storing already\n processed elements.\n\n OUTPUT:\n\n A new state.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState((1, 3), color=[1, 2],\n ....: is_final=True, final_word_out=3,\n ....: initial_probability=1/3)\n sage: B = deepcopy(A)\n sage: B\n (1, 3)\n sage: B.label() == A.label()\n True\n sage: B.label is A.label\n False\n sage: B.color == A.color\n True\n sage: B.color is A.color\n False\n sage: B.is_final == A.is_final\n True\n sage: B.is_final is A.is_final\n True\n sage: B.final_word_out == A.final_word_out\n True\n sage: B.final_word_out is A.final_word_out\n False\n sage: B.initial_probability == A.initial_probability\n True\n '
return deepcopy(self, memo)
def relabeled(self, label, memo=None):
"\n Return a deep copy of the state with a new label.\n\n INPUT:\n\n - ``label`` -- the label of new state.\n\n - ``memo`` -- (default: ``None``) a dictionary storing already\n processed elements.\n\n OUTPUT:\n\n A new state.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A')\n sage: A.relabeled('B')\n 'B'\n "
self._deepcopy_relabel_ = label
new = deepcopy(self, memo)
del self._deepcopy_relabel_
return new
def __getstate__(self):
"\n Return state for pickling excluding outgoing transitions.\n\n INPUT:\n\n None\n\n OUTPUT:\n\n A dictionary.\n\n Outgoing transitions are in fact stored in states,\n but must be pickled by the finite state machine\n in order to avoid deep recursion.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: S = FSMState('S')\n sage: S == loads(dumps(S))\n True\n sage: A = Automaton([[0, 1, 0]])\n sage: T = A.state(0)\n sage: T1 = loads(dumps(T))\n sage: T == T1\n True\n sage: T.transitions\n [Transition from 0 to 1: 0|-]\n sage: T1.transitions\n Traceback (most recent call last):\n ...\n AttributeError: 'FSMState' object has no attribute 'transitions'...\n sage: A1 = loads(dumps(A))\n sage: all(A.state(j) == A1.state(j) for j in [0, 1])\n True\n sage: all(A.state(j).transitions == A1.state(j).transitions\n ....: for j in [0, 1])\n True\n "
odict = self.__dict__.copy()
try:
del odict['transitions']
except KeyError:
pass
return odict
def __hash__(self):
"\n Return a hash value for the object.\n\n OUTPUT:\n\n The hash of this state.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A')\n sage: hash(A) #random\n -269909568\n "
return hash(self.label())
def _repr_(self):
'\n Return the string "label".\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: FSMState(\'A\')\n \'A\'\n '
return pretty(self.label())
def __eq__(self, other):
"\n Return ``True`` if two states are the same, i.e., if they have\n the same labels.\n\n INPUT:\n\n - ``self`` -- a state.\n\n - ``other`` -- a state.\n\n OUTPUT:\n\n ``True`` or ``False``.\n\n Note that the hooks and whether the states are initial or\n final are not checked. To fully compare two states (including\n these attributes), use :meth:`.fully_equal`.\n\n As only the labels are used when hashing a state, only the\n labels can actually be compared by the equality relation.\n Note that the labels are unique within one finite state machine,\n so this may only lead to ambiguities when comparing states\n belonging to different finite state machines.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A')\n sage: B = FSMState('A', is_initial=True)\n sage: A == B\n True\n "
if (not is_FSMState(other)):
return False
return (self.label() == other.label())
def __ne__(self, other):
"\n Tests for inequality, complement of __eq__.\n\n INPUT:\n\n - ``self`` -- a state.\n\n - ``other`` -- a state.\n\n OUTPUT:\n\n ``True`` or ``False``\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A', is_initial=True)\n sage: B = FSMState('A', is_final=True)\n sage: A != B\n False\n "
return (not (self == other))
def fully_equal(self, other, compare_color=True):
"\n Check whether two states are fully equal, i.e., including all\n attributes except ``hook``.\n\n INPUT:\n\n - ``self`` -- a state.\n\n - ``other`` -- a state.\n\n - ``compare_color`` -- If ``True`` (default) colors are\n compared as well, otherwise not.\n\n OUTPUT:\n\n ``True`` or ``False``.\n\n Note that usual comparison by ``==`` does only compare the labels.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: A = FSMState('A')\n sage: B = FSMState('A', is_initial=True)\n sage: A.fully_equal(B)\n False\n sage: A == B\n True\n sage: A.is_initial = True; A.color = 'green'\n sage: A.fully_equal(B)\n False\n sage: A.fully_equal(B, compare_color=False)\n True\n "
color = ((not compare_color) or (self.color == other.color))
return ((self == other) and (self.is_initial == other.is_initial) and (self.is_final == other.is_final) and (self.final_word_out == other.final_word_out) and (self.word_out == other.word_out) and color and (self.initial_probability == other.initial_probability))
def __bool__(self):
"\n Return ``True``.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import FSMState\n sage: bool(FSMState('A'))\n True\n "
return True
def _epsilon_successors_(self, fsm=None):
"\n Return the dictionary with states reachable from ``self``\n without reading anything from an input tape as keys. The\n values are lists of outputs.\n\n INPUT:\n\n - ``fsm`` -- the finite state machine to which ``self``\n belongs.\n\n OUTPUT:\n\n A dictionary mapping states to a list of output words.\n\n The states in the output are the epsilon successors of\n ``self``. Each word of the list of words is an output word\n written when taking a path from ``self`` to the corresponding\n state.\n\n TESTS::\n\n sage: T = Transducer([(0, 1, None, 'a'), (1, 2, None, 'b')])\n sage: T.state(0)._epsilon_successors_(T)\n {1: [['a']], 2: [['a', 'b']]}\n sage: T.state(1)._epsilon_successors_(T)\n {2: [['b']]}\n sage: T.state(2)._epsilon_successors_(T)\n {}\n\n ::\n\n sage: T.state(0)._epsilon_successors_()\n {1: [['a']], 2: [['a', 'b']]}\n\n ::\n\n sage: T.add_transition(2, 0, None, 'c')\n Transition from 2 to 0: -|'c'\n sage: T.state(0)._epsilon_successors_()\n {0: [['a', 'b', 'c']], 1: [['a']], 2: [['a', 'b']]}\n\n ::\n\n sage: T.add_transition(0, 2, None, ['a', 'b'])\n Transition from 0 to 2: -|'a','b'\n sage: T.state(0)._epsilon_successors_()\n {0: [['a', 'b', 'c']], 1: [['a']], 2: [['a', 'b']]}\n "
if (not hasattr(self, 'transitions')):
raise ValueError(('State %s does not belong to a finite state machine.' % (self,)))
it = _FSMProcessIteratorEpsilon_(fsm, input_tape=[], initial_state=self)
for _ in it:
pass
_epsilon_successors_dict_ = it.visited_states
_epsilon_successors_dict_[self].remove([])
if (not _epsilon_successors_dict_[self]):
del _epsilon_successors_dict_[self]
for (s, outputs) in _epsilon_successors_dict_.items():
_epsilon_successors_dict_[s] = [t for (t, _) in itertools.groupby(sorted(outputs))]
return _epsilon_successors_dict_
def _in_epsilon_cycle_(self, fsm=None):
"\n Return whether ``self`` is in an epsilon-cycle or not.\n\n INPUT:\n\n - ``fsm`` -- the finite state machine to which ``self``\n belongs.\n\n OUTPUT:\n\n ``True`` or ``False``.\n\n TESTS::\n\n sage: A = Automaton([(0, 1, None, 'a'), (1, 2, None, 'b'),\n ....: (2, 0, None, 'c'), (4, 1, None, 'd')])\n sage: A.state(0)._epsilon_successors_(A)\n {0: [['a', 'b', 'c']], 1: [['a']], 2: [['a', 'b']]}\n sage: A.state(0)._in_epsilon_cycle_(A)\n True\n sage: A.state(4)._epsilon_successors_(A)\n {0: [['d', 'b', 'c']], 1: [['d'], ['d', 'b', 'c', 'a']],\n 2: [['d', 'b']]}\n sage: A.state(4)._in_epsilon_cycle_(A)\n False\n "
return (self in self._epsilon_successors_(fsm))
def _epsilon_cycle_output_empty_(self, fsm=None):
"\n Return whether all epsilon-cycles in which ``self`` is\n contained have an empty output (i.e., do not write any output\n word).\n\n INPUT:\n\n - ``fsm`` -- the finite state machine to which ``self``\n belongs.\n\n OUTPUT:\n\n ``True`` or ``False``\n\n A ``ValueError`` is raised when ``self`` is not in an epsilon\n cycle.\n\n TESTS::\n\n sage: A = Automaton([(0, 1, None, 'a'), (1, 2, None, None),\n ....: (2, 0, None, None), (4, 1, None, None)])\n sage: A.state(0)._epsilon_successors_(A)\n {0: [['a']], 1: [['a']], 2: [['a']]}\n sage: A.state(0)._epsilon_cycle_output_empty_(A)\n False\n sage: A.state(4)._epsilon_cycle_output_empty_(A)\n Traceback (most recent call last):\n ...\n ValueError: State 4 is not in an epsilon cycle.\n sage: A = Automaton([(0, 1, None, None), (1, 2, None, None),\n ....: (2, 0, None, None), (4, 1, None, None)])\n sage: A.state(0)._epsilon_successors_(A)\n {0: [[]], 1: [[]], 2: [[]]}\n sage: A.state(0)._epsilon_cycle_output_empty_(A)\n True\n sage: A.process([], initial_state=A.state(0))\n [(False, 0), (False, 1), (False, 2)]\n sage: A.add_transition(0, 0, None, 'x')\n Transition from 0 to 0: -|'x'\n sage: A.state(0)._epsilon_successors_(A)\n {0: [[], ['x']], 1: [[]], 2: [[]]}\n sage: A.state(0)._epsilon_cycle_output_empty_(A)\n False\n sage: A.process([], initial_state=A.state(0))\n Traceback (most recent call last):\n ...\n RuntimeError: State 0 is in an epsilon cycle (no input),\n but output is written.\n sage: T = Transducer([(0, 1, None, None), (1, 2, None, None),\n ....: (2, 0, None, None), (0, 0, None, None)])\n sage: T.state(0)._epsilon_successors_(T)\n {0: [[]], 1: [[]], 2: [[]]}\n sage: T.state(0)._epsilon_cycle_output_empty_(T)\n True\n "
try:
return (not any(self._epsilon_successors_(fsm)[self]))
except KeyError:
raise ValueError(('State %s is not in an epsilon cycle.' % (self,)))
|
def is_FSMTransition(T):
"\n Tests whether or not ``T`` inherits from :class:`FSMTransition`.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import is_FSMTransition, FSMTransition\n sage: is_FSMTransition(FSMTransition('A', 'B'))\n True\n "
return isinstance(T, FSMTransition)
|
class FSMTransition(SageObject):
"\n Class for a transition of a finite state machine.\n\n INPUT:\n\n - ``from_state`` -- state from which transition starts.\n\n - ``to_state`` -- state in which transition ends.\n\n - ``word_in`` -- the input word of the transitions (when the\n finite state machine is used as automaton)\n\n - ``word_out`` -- the output word of the transitions (when the\n finite state machine is used as transducer)\n\n OUTPUT:\n\n A transition of a finite state machine.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition\n sage: A = FSMState('A')\n sage: B = FSMState('B')\n sage: S = FSMTransition(A, B, 0, 1)\n sage: T = FSMTransition('A', 'B', 0, 1)\n sage: T == S\n True\n sage: U = FSMTransition('A', 'B', 0)\n sage: U == T\n False\n\n "
from_state = None
'State from which the transition starts. Read-only.'
to_state = None
'State in which the transition ends. Read-only.'
word_in = None
'Input word of the transition. Read-only.'
word_out = None
'Output word of the transition. Read-only.'
def __init__(self, from_state, to_state, word_in=None, word_out=None, hook=None):
"\n See :class:`FSMTransition` for more information.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: FSMTransition('A', 'B', 0, 1)\n Transition from 'A' to 'B': 0|1\n "
if is_FSMState(from_state):
self.from_state = from_state
else:
self.from_state = FSMState(from_state)
if is_FSMState(to_state):
self.to_state = to_state
else:
self.to_state = FSMState(to_state)
if isinstance(word_in, list):
self.word_in = word_in
elif (word_in is not None):
self.word_in = [word_in]
else:
self.word_in = []
if isinstance(word_out, list):
self.word_out = word_out
elif (word_out is not None):
self.word_out = [word_out]
else:
self.word_out = []
if (hook is not None):
if callable(hook):
self.hook = hook
else:
raise TypeError('Wrong argument for hook.')
def __lt__(self, other):
'\n Return True if ``self`` is less than ``other`` with respect to the\n key ``(self.from_state, self.word_in, self.to_state, self.word_out)``.\n\n INPUT:\n\n - ``other`` -- a transition.\n\n OUTPUT:\n\n ``True`` or ``False``\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: FSMTransition(0,1,0,0) < FSMTransition(1,0,0,0)\n True\n '
return ((self.from_state, self.word_in, self.to_state, self.word_out) < (other.from_state, other.word_in, other.to_state, other.word_out))
def __copy__(self):
"\n Return a (shallow) copy of the transition.\n\n OUTPUT:\n\n A new transition.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: t = FSMTransition('A', 'B', 0)\n sage: copy(t)\n Transition from 'A' to 'B': 0|-\n "
new = FSMTransition(self.from_state, self.to_state, self.word_in, self.word_out)
if hasattr(self, 'hook'):
new.hook = self.hook
return new
copy = __copy__
def __deepcopy__(self, memo):
"\n Return a deep copy of the transition.\n\n INPUT:\n\n - ``memo`` -- a dictionary storing already processed elements.\n\n OUTPUT:\n\n A new transition.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: t = FSMTransition('A', 'B', 0)\n sage: deepcopy(t)\n Transition from 'A' to 'B': 0|-\n "
new = FSMTransition(deepcopy(self.from_state, memo), deepcopy(self.to_state, memo), deepcopy(self.word_in, memo), deepcopy(self.word_out, memo))
if hasattr(self, 'hook'):
new.hook = deepcopy(self.hook, memo)
return new
def deepcopy(self, memo=None):
"\n Return a deep copy of the transition.\n\n INPUT:\n\n - ``memo`` -- (default: ``None``) a dictionary storing already\n processed elements.\n\n OUTPUT:\n\n A new transition.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: t = FSMTransition('A', 'B', 0)\n sage: deepcopy(t)\n Transition from 'A' to 'B': 0|-\n "
return deepcopy(self, memo)
__hash__ = None
def _repr_(self):
'\n Represents a transitions as from state to state and input, output.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: FSMTransition(\'A\', \'B\', 0, 0)._repr_()\n "Transition from \'A\' to \'B\': 0|0"\n\n '
return ('Transition from %s to %s: %s' % (repr(self.from_state), repr(self.to_state), self._in_out_label_()))
def _in_out_label_(self):
'\n Return the input and output of a transition as "word_in|word_out".\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string of the input and output labels.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: FSMTransition(\'A\', \'B\', 0, 1)._in_out_label_()\n \'0|1\'\n '
return ('%s|%s' % (FSMWordSymbol(self.word_in), FSMWordSymbol(self.word_out)))
def __eq__(self, other):
"\n Return ``True`` if the two transitions are the same, i.e., if the\n both go from the same states to the same states and read and\n write the same words.\n\n Note that the hooks are not checked.\n\n INPUT:\n\n - ``self`` -- a transition.\n\n - ``other`` -- a transition.\n\n OUTPUT:\n\n ``True`` or ``False``\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition\n sage: A = FSMState('A', is_initial=True)\n sage: t1 = FSMTransition('A', 'B', 0, 1)\n sage: t2 = FSMTransition(A, 'B', 0, 1)\n sage: t1 == t2\n True\n "
if (not is_FSMTransition(other)):
return False
return ((self.from_state == other.from_state) and (self.to_state == other.to_state) and (self.word_in == other.word_in) and (self.word_out == other.word_out))
def __ne__(self, other):
"\n Test for inequality, complement of __eq__.\n\n INPUT:\n\n - ``self`` -- a transition.\n\n - ``other`` -- a transition.\n\n OUTPUT:\n\n ``True`` or ``False``\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition\n sage: A = FSMState('A', is_initial=True)\n sage: t1 = FSMTransition('A', 'B', 0, 1)\n sage: t2 = FSMTransition(A, 'B', 0, 1)\n sage: t1 != t2\n False\n "
return (not (self == other))
def __bool__(self):
"\n Return ``True``.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: bool(FSMTransition('A', 'B', 0))\n True\n "
return True
|
def is_FiniteStateMachine(FSM):
'\n Tests whether or not ``FSM`` inherits from :class:`FiniteStateMachine`.\n\n TESTS::\n\n sage: from sage.combinat.finite_state_machine import is_FiniteStateMachine\n sage: is_FiniteStateMachine(FiniteStateMachine())\n True\n sage: is_FiniteStateMachine(Automaton())\n True\n sage: is_FiniteStateMachine(Transducer())\n True\n '
return isinstance(FSM, FiniteStateMachine)
|
def duplicate_transition_ignore(old_transition, new_transition):
'\n Default function for handling duplicate transitions in finite\n state machines. This implementation ignores the occurrence.\n\n See the documentation of the ``on_duplicate_transition`` parameter\n of :class:`FiniteStateMachine`.\n\n INPUT:\n\n - ``old_transition`` -- A transition in a finite state machine.\n\n - ``new_transition`` -- A transition, identical to ``old_transition``,\n which is to be inserted into the finite state machine.\n\n OUTPUT:\n\n The same transition, unchanged.\n\n EXAMPLES::\n\n sage: from sage.combinat.finite_state_machine import duplicate_transition_ignore\n sage: from sage.combinat.finite_state_machine import FSMTransition\n sage: duplicate_transition_ignore(FSMTransition(0, 0, 1),\n ....: FSMTransition(0, 0, 1))\n Transition from 0 to 0: 1|-\n '
return old_transition
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.