code stringlengths 17 6.64M |
|---|
def RBIBD_120_8_1():
"\n Return a resolvable `BIBD(120,8,1)`\n\n This function output a list ``L`` of `17\\times 15` blocks such that\n ``L[i*15:(i+1)*15]`` is a partition of `120`.\n\n Construction shared by Julian R. Abel:\n\n Seiden's method: Start with a cyclic `(273,17,1)-BIBD` and let `B` be an\n hyperoval, i.e. a set of 18 points which intersects any block of the\n BIBD in either 0 points (153 blocks) or 2 points (120 blocks). Dualise\n this design and take these last 120 blocks as points in the design;\n blocks in the design will correspond to the `273-18=255` non-hyperoval\n points.\n\n The design is also resolvable. In the original `PG(2,16)` take any\n point `T` in the hyperoval and consider a block `B1` containing `T`.\n The `15` points in `B1` that do not belong to the hyperoval correspond\n to `15` blocks forming a parallel class in the dualised design. The\n other `16` parallel classes come in a similar way, by using point `T`\n and the other `16` blocks containing `T`.\n\n .. SEEALSO::\n\n :func:`OA_9_120`\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.database import RBIBD_120_8_1\n sage: from sage.combinat.designs.bibd import is_pairwise_balanced_design\n sage: RBIBD = RBIBD_120_8_1() # needs sage.modules\n sage: is_pairwise_balanced_design(RBIBD,120,[8]) # needs sage.modules\n True\n\n It is indeed resolvable, and the parallel classes are given by 17 slices of\n consecutive 15 blocks::\n\n sage: for i in range(17): # needs sage.modules\n ....: assert len(set(sum(RBIBD[i*15:(i+1)*15],[]))) == 120\n\n The BIBD is available from the constructor::\n\n sage: _ = designs.balanced_incomplete_block_design(120,8) # needs sage.modules\n "
from .incidence_structures import IncidenceStructure
n = 273
B = [1, 2, 4, 8, 16, 32, 64, 91, 117, 128, 137, 182, 195, 205, 234, 239, 256]
BIBD = [[((x + c) % n) for x in B] for c in range(n)]
hyperoval = [128, 192, 194, 4, 262, 140, 175, 48, 81, 180, 245, 271, 119, 212, 249, 189, 62, 255]
p = hyperoval[0]
equiv = []
new_BIBD = []
for B in BIBD:
if any(((x in hyperoval) for x in B)):
if (p in B):
equiv.append([x for x in B if (x not in hyperoval)])
else:
new_BIBD.append([x for x in B])
BIBD = new_BIBD
r = {v: i for (i, v) in enumerate((x for x in range(n) if (x not in hyperoval)))}
BIBD = [[r[x] for x in B] for B in BIBD]
equiv = [[r[x] for x in B] for B in equiv]
BIBD = IncidenceStructure(range(255), BIBD)
M = BIBD.incidence_matrix()
equiv = [[M.nonzero_positions_in_row(x) for x in S] for S in equiv]
return [B for S in equiv for B in S]
|
def BIBD_45_9_8(from_code=False):
'\n Return a `(45,9,1)`-BIBD.\n\n This BIBD is obtained from the codewords of minimal weight in the\n :func:`~sage.coding.code_constructions.ExtendedQuadraticResidueCode` of\n length 48. This construction appears in VII.11.2 from [DesignHandbook]_,\n which cites [HT95]_.\n\n INPUT:\n\n - ``from_code`` (boolean) -- whether to build the design from hardcoded data\n (default) or from the code object (much longer).\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.database import BIBD_45_9_8\n sage: from sage.combinat.designs.bibd import BalancedIncompleteBlockDesign\n sage: B = BalancedIncompleteBlockDesign(45, BIBD_45_9_8(), lambd=8); B\n (45,9,8)-Balanced Incomplete Block Design\n\n TESTS:\n\n From the definition (takes around 12s)::\n\n sage: B2 = Hypergraph(BIBD_45_9_8(from_code=True)) # not tested # needs sage.rings.finite_rings\n sage: B2.is_isomorphic(B) # not tested # needs sage.rings.finite_rings\n True\n\n REFERENCE:\n\n .. [HT95] \\W. Huffman and V. Tonchev,\n The existence of extremal self-dual `[50, 25, 10]` codes and\n quasi-symmetric `2-(49, 9, 6)` designs,\n Designs, Codes and Cryptography\n September 1995, Volume 6, Issue 2, pp 97-106\n '
if from_code:
from sage.coding.code_constructions import ExtendedQuadraticResidueCode
from sage.rings.finite_rings.finite_field_constructor import FiniteField
C = ExtendedQuadraticResidueCode(47, FiniteField(2))
min_weight = [map(int, x)[3:] for x in C if ((x.hamming_weight() == 12) and (x[0] == 1) and (x[1] == 1) and (x[2] == 1))]
return [[i for (i, v) in enumerate(x) if v] for x in min_weight]
from sage.rings.integer import Integer
B = ['acs1v', 'l8lsx', '4ga1vw', '6q9amr', 'nb3ui8', 'sgjocw', '11vsoy2', '28791ts', '30tm1z8', '38ktnwh', '3saz8jk', '41qkwme', '4g3jxmt', '56qhwuc', '711w45k', '8nz2gx4', '903uha8', '957z8dc', '9wejz7k', 'fs905ic', 'ftzzh28', 'gb4g448', 'hvreal0', 'nqlhxu8', 'rmluazm', 'vlyqayx', 'w52detk', 'zisjk02', 'zw9811c', '10i7qfl1', '13ibtse8', '1rbsbvvc', '1sdy0o5c', '1z14s09e', '2nbz5a80', '2uuhib2a', '2wkn4r9d', '3iaaat5w', '3iiwq53s', '3j9ubv43', '3mpxpngz', '3qamndc0', '3saomh3t', '3uhhi5cw', '4334rx4x', '4dxy3xts', '4tn9w2z1', '4vlr2h00', '59f1meqm', '59h6udc1', '5cep4nc0', '5ddcxsw2', '70msua7k', '70ofjm82', '70p8jig0', '721o664h', '72jutmfk', '74jowaad', '78ihrfgo', '7meufihs', '7wv5mtxj', '84akgj0w', '8m9vyb60', '8s0c6p04', '8soi6m8g', '9kawy0ow', 'awnpg9a8', 'biu8xww0', 'e1lptwxx', 'e79x2we8', 'eh0t1q9y', 'eh65daci', 'ehxytwjk', 'extc1udk', 'f4toqhpg', 'fgeqg214', 'ftiem9lk', 'fw77kcnc', 'h5kt9cf4', 'hjwhwym8', 'hz8d60xs', 'jb6bp0g0', 'l22bzw1w', 'l3pj9hq8', 'lbj1fubp', 'lxal1lk2', 's27vq70q', 's2bb5mki', 's2w95y0w', 's3cek9og', 's4703jk4', 's67g5qf5', 's8kgdkat', 'sckruupw', 'se4vzkao', 'si57d0vl', 'sjhd20i8', 'sqne2mf6', 'sxtju9ds', 'ttd710kw', 'ttkayw5e', 'u96baslc', 'vtdhrbj5', 'y79i706c', 'zycu7tsa', '10uwf8sh4', '11boo6mmc', '12sxyeebs', '163xyccg3', '16cpesdfk', '18q18bpc0', '1k4hvvgq4', '1k5f63ok4', '1k5olig3u', '1k6fsqalm', '1kacr2gi8', '1kcc6rzu1', '1kkpot632', '1kwdghpts', '1l2644l68', '1l3yxmj9s', '1m04wgmyo', '1mtm16z5s', '1np6u1q0w', '1nuo1tbfk', '1oy4n1mo0', '1r5lsxju0', '1sx57vdfq', '1v4j675ds', '1y5oldkzm', '1ydfr4jno', '1ylc38ah4', '1z14mw0td', '223vcx1xc', '26xq9hn29', '2c7wa6r0w', '2cbc8qbcw', '2jn9ojll5', '2qjlkoz69', '2tr1zn5ds', '348vfurgh', '348vlaoc0', '348ynt0qx', '34ahl37ds', '34b3cgc8y', '34ooa1ix0', '34r4ejl82', '35p5m8r28', '360i7uazl', '36289j761', '3650mzlzg', '36aev2c00', '36noxmex2', '36vlw3k3k', '37rw4rghs', '37t554ikq', '387avhseb', '3b9o5lbwi', '3ewmteale', '3ibz0r8n4', '3id5iv5ky', '3ihxwcvvc', '3k5k1k174', '3pau9ujnl', '3wf1e2dck', '43rfm4du8', '47pqff6yo', '4e2i4y684', '4hio30v0o', '4odb0lr5s', '4odcmkvt0', '4p94elixc', '4p9zffz0k', '4qciqf9mp', '4ywafln9c', '5hf4nw08w', '68ijggco4', '68jq73cxs', '68maap98g', '68prdfhqg', '68qm8divl', '691ibd2ps', '69dbnd8ur', '69esd0djg', '69w6eo0sh', '6ad6zcetk', '6aonwwkjk', '6aozhe8zl', '6cvyitslw', '6dr7i6olg', '6fibvzxtw', '6fmd4bv28', '6gmqtkr9e', '6j14n6n7k', '6miukvtc1', '6mjvifon4', '6mormb3fm', '6mr9hvhna', '6q533lm6w', '6rsie7cbk', '6tjgpxic0', '70k7ao9m0', '7103zqlvk', '71i1x52bm', '7447g0dfw', '7sogja9z4', '7up5z9m9u', '7w7esu6fm', '7zmqtlrpd', '81tsbnzsw', '8kofgi1he', '8mhi35nc1', '9cv1pjiaw', '9d6ef1dah', '9dftsor9c', '9du8c1vcw', '9jr5vsnj4', 'a8b405mps', 'ajqhmxkj4', 'ax2xsvfic']
B = [Integer(x, base=36) for x in B]
return [[i for i in range(45) if (x & (1 << i))] for x in B]
|
def BIBD_66_6_1():
'\n Return a (66,6,1)-BIBD.\n\n This BIBD was obtained from La Jolla covering repository\n (https://math.ccrwest.org/cover.html) where it is attributed to Colin Barker.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.database import BIBD_66_6_1\n sage: from sage.combinat.designs.bibd import BalancedIncompleteBlockDesign\n sage: BalancedIncompleteBlockDesign(66, BIBD_66_6_1())\n (66,6,1)-Balanced Incomplete Block Design\n '
BIBD = [frozenset([(((x + (i * 5)) % 65) if (x < 65) else x) for x in b]) for i in range(65) for b in [[6, 38, 42, 46, 53, 62], [9, 11, 21, 49, 56, 60], [18, 31, 37, 44, 52, 60], [0, 12, 29, 46, 51, 63], [0, 6, 21, 30, 43, 48], [4, 17, 22, 36, 47, 59], [0, 1, 2, 3, 4, 65], [23, 39, 44, 53, 59, 63], [12, 22, 28, 48, 55, 60], [19, 22, 25, 40, 49, 50], [4, 30, 37, 50, 58, 61]]]
return [list(t) for t in frozenset(BIBD)]
|
def BIBD_76_6_1():
'\n Return a (76,6,1)-BIBD.\n\n This BIBD was obtained from La Jolla covering repository\n (https://math.ccrwest.org/cover.html) where it is attributed to Colin Barker.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.database import BIBD_76_6_1\n sage: from sage.combinat.designs.bibd import BalancedIncompleteBlockDesign\n sage: BalancedIncompleteBlockDesign(76, BIBD_76_6_1())\n (76,6,1)-Balanced Incomplete Block Design\n '
BIBD = [frozenset([(((x + (i * 4)) % 76) if (x < 76) else x) for x in b]) for i in range(76) for b in [[3, 5, 21, 33, 72, 73], [4, 37, 57, 58, 64, 75], [7, 14, 44, 47, 59, 63], [10, 20, 61, 63, 71, 72], [13, 26, 30, 39, 45, 67], [11, 21, 25, 30, 55, 58], [2, 5, 34, 52, 54, 70], [6, 8, 29, 48, 70, 71], [10, 15, 36, 41, 44, 56], [0, 6, 13, 27, 44, 72]]]
return [list(t) for t in frozenset(BIBD)]
|
def BIBD_96_6_1():
'\n Return a (96,6,1)-BIBD.\n\n This BIBD was obtained from La Jolla covering repository\n (https://math.ccrwest.org/cover.html) where it is attributed to Colin Barker.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.database import BIBD_96_6_1\n sage: from sage.combinat.designs.bibd import BalancedIncompleteBlockDesign\n sage: BalancedIncompleteBlockDesign(96, BIBD_96_6_1())\n (96,6,1)-Balanced Incomplete Block Design\n '
BIBD = [frozenset([(((x + (i * 2)) % 96) if (x < 96) else x) for x in b]) for i in range(96) for b in [[3, 13, 32, 47, 68, 87], [9, 36, 70, 75, 81, 88], [22, 52, 72, 76, 78, 79], [15, 23, 41, 43, 46, 58], [7, 8, 21, 57, 66, 94], [8, 22, 30, 51, 55, 93], [15, 31, 47, 63, 79, 95], [2, 18, 34, 50, 66, 82]]]
return [list(t) for t in frozenset(BIBD)]
|
def BIBD_106_6_1():
'\n Return a (106,6,1)-BIBD.\n\n This constructions appears in II.3.32 from [DesignHandbook]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.database import BIBD_106_6_1\n sage: from sage.combinat.designs.bibd import BalancedIncompleteBlockDesign\n sage: BalancedIncompleteBlockDesign(106, BIBD_106_6_1())\n (106,6,1)-Balanced Incomplete Block Design\n '
bibd = [((0, 0), (1, 0), (3, 0), (11, 0), (38, 0), (0, 1)), ((0, 0), (13, 0), (30, 0), (23, 1), (35, 1), (51, 1)), ((0, 0), (5, 0), (19, 0), (25, 0), (36, 1), (39, 1)), ((0, 0), (4, 0), (28, 1), (30, 1), (37, 1), (47, 1)), ((0, 0), (7, 0), (29, 0), (8, 1), (16, 1), (48, 1)), ((0, 0), (2, 1), (7, 1), (25, 1), (29, 1), (49, 1)), ((0, 0), (9, 0), (21, 0), (12, 1), (13, 1), (27, 1))]
return [[(((x + i) % 53) + (y * 53)) for (x, y) in B] for i in range(53) for B in bibd]
|
def BIBD_111_6_1():
'\n Return a (111,6,1)-BIBD.\n\n This constructions appears in II.3.32 from [DesignHandbook]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.database import BIBD_111_6_1\n sage: from sage.combinat.designs.bibd import BalancedIncompleteBlockDesign\n sage: BalancedIncompleteBlockDesign(111, BIBD_111_6_1())\n (111,6,1)-Balanced Incomplete Block Design\n '
from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet
from .incidence_structures import IncidenceStructure
bibd = [((0, 0), (1, 0), (3, 0), (7, 0), (17, 0), (0, 1)), ((0, 0), (5, 0), (19, 1), (28, 1), (10, 2), (30, 2)), ((5, 0), (33, 0), (13, 1), (34, 1), (19, 2), (7, 2)), ((9, 0), (27, 0), (16, 1), (11, 1), (12, 2), (36, 2)), ((10, 0), (23, 0), (26, 1), (8, 1), (1, 2), (6, 2)), ((13, 0), (24, 0), (19, 1), (18, 1), (5, 2), (32, 2)), ((26, 0), (34, 0), (1, 1), (7, 1), (10, 2), (33, 2))]
gens = (lambda B: [frozenset(((((x * 10) % 37), ((y + 1) % 3)) for (x, y) in B)), frozenset(((((x + 1) % 37), y) for (x, y) in B))])
bibd = RecursivelyEnumeratedSet([frozenset(e) for e in bibd], successors=gens)
return IncidenceStructure(bibd)._blocks
|
def BIBD_126_6_1():
'\n Return a (126,6,1)-BIBD.\n\n This constructions appears in VI.16.92 from [DesignHandbook]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.database import BIBD_126_6_1\n sage: from sage.combinat.designs.bibd import BalancedIncompleteBlockDesign\n sage: BalancedIncompleteBlockDesign(126, BIBD_126_6_1())\n (126,6,1)-Balanced Incomplete Block Design\n '
from itertools import product
bibd = [[(((x + xx) % 5), ((y + yy) % 5), ((z + zz) % 5)) for (x, y, z) in B] for (xx, yy, zz) in product(range(5), repeat=3) for B in [[(0, 0, 1), (0, 0, 4), (1, 2, 2), (1, 3, 3), (4, 2, 1), (4, 3, 4)], [(0, 0, 2), (0, 0, 3), (1, 4, 4), (1, 1, 1), (4, 4, 2), (4, 1, 3)], [(0, 4, 3), (0, 1, 2), (2, 2, 0), (2, 3, 0), (3, 3, 2), (3, 2, 3)], [(0, 3, 1), (0, 2, 4), (2, 4, 0), (2, 1, 0), (3, 1, 4), (3, 4, 1)]]]
bibd.extend([[(125, 0, 0), (0, x, y), (1, x, y), (2, x, y), (3, x, y), (4, x, y)] for (x, y) in product(range(5), repeat=2)])
return [[((x + (y * 5)) + (z * 25)) for (x, y, z) in B] for B in bibd]
|
def BIBD_136_6_1():
'\n Return a (136,6,1)-BIBD.\n\n This constructions appears in II.3.32 from [DesignHandbook]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.database import BIBD_136_6_1\n sage: from sage.combinat.designs.bibd import BalancedIncompleteBlockDesign\n sage: BalancedIncompleteBlockDesign(136, BIBD_136_6_1())\n (136,6,1)-Balanced Incomplete Block Design\n '
from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet
from .incidence_structures import IncidenceStructure
inf = (None, None)
bibd = [((0, 0), (3, 0), (15, 0), (35, 0), (6, 2), (10, 2)), ((0, 0), (22, 0), (11, 1), (30, 1), (1, 2), (18, 2)), ((0, 0), (5, 0), (18, 1), (41, 1), (13, 2), (42, 2)), ((0, 0), (11, 0), (17, 0), (4, 2), (5, 2), (28, 2)), ((0, 0), (1, 0), (0, 1), (16, 1), (0, 2), (31, 2)), (inf, (0, 0), (9, 0), (18, 0), (27, 0), (36, 0))]
gens = (lambda B: [frozenset((((((x * 16) % 45), ((y + 1) % 3)) if ((x, y) != inf) else inf) for (x, y) in B)), frozenset((((((x + 1) % 45), y) if ((x, y) != inf) else inf) for (x, y) in B))])
bibd = RecursivelyEnumeratedSet([frozenset(e) for e in bibd], successors=gens)
return IncidenceStructure(bibd)._blocks
|
def BIBD_141_6_1():
'\n Return a (141,6,1)-BIBD.\n\n This constructions appears in II.3.32 from [DesignHandbook]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.database import BIBD_141_6_1\n sage: from sage.combinat.designs.bibd import BalancedIncompleteBlockDesign\n sage: BalancedIncompleteBlockDesign(141, BIBD_141_6_1())\n (141,6,1)-Balanced Incomplete Block Design\n '
from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet
from .incidence_structures import IncidenceStructure
a = 'a'
inf = (None, None)
bibd = [((0, 0), (16, 0), (24, 0), (24, 1), (15, 2), (25, 2)), ((0, 0), (3, 0), (26, 0), (13, 1), (33, 1), (34, a)), ((0, 0), (13, 0), (18, 0), (15, 1), (7, 2), (0, a)), ((0, 0), (2, 0), (14, 1), (23, 1), (26, a), (32, a)), ((0, 0), (4, 0), (29, 1), (6, 2), (9, a), (20, a)), ((0, 0), (1, 0), (12, 2), (2, a), (4, a), (19, a)), (inf, (0, 0), (7, 0), (14, 0), (21, 0), (28, 0)), (inf, (0, a), (7, a), (14, a), (21, a), (28, a))]
gens = (lambda B: [frozenset((((((x * 16) % 35), (((y + 1) % 3) if (y != a) else a)) if ((x, y) != inf) else inf) for (x, y) in B)), frozenset((((((x + 1) % 35), y) if ((x, y) != inf) else inf) for (x, y) in B))])
bibd = RecursivelyEnumeratedSet([frozenset(e) for e in bibd], successors=gens)
return IncidenceStructure(bibd)._blocks
|
def BIBD_171_6_1():
'\n Return a (171,6,1)-BIBD.\n\n This constructions appears in II.3.32 from [DesignHandbook]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.database import BIBD_171_6_1\n sage: from sage.combinat.designs.bibd import BalancedIncompleteBlockDesign\n sage: BalancedIncompleteBlockDesign(171, BIBD_171_6_1())\n (171,6,1)-Balanced Incomplete Block Design\n '
from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet
from .incidence_structures import IncidenceStructure
bibd = [((0, 0), (19, 0), (39, 0), (41, 0), (14, 1), (38, 2)), ((0, 0), (21, 0), (44, 0), (48, 0), (26, 1), (11, 2)), ((0, 0), (1, 0), (43, 0), (8, 2), (15, 2), (44, 2)), ((0, 0), (3, 0), (31, 0), (23, 1), (43, 1), (36, 2)), ((0, 0), (40, 0), (50, 0), (11, 1), (25, 2), (34, 2)), ((0, 0), (12, 0), (0, 1), (27, 1), (0, 2), (18, 2)), ((37, 0), (42, 0), (31, 1), (9, 1), (46, 2), (6, 2))]
gens = (lambda B: [frozenset(((((x * 7) % 57), ((y + 1) % 3)) for (x, y) in B)), frozenset(((((x + 1) % 57), y) for (x, y) in B))])
bibd = RecursivelyEnumeratedSet([frozenset(e) for e in bibd], successors=gens)
return IncidenceStructure(bibd)._blocks
|
def HigmanSimsDesign():
'\n Return the Higman-Sims designs, which is a `(176, 50, 14)`-BIBD.\n\n This design is built from a from the :func:`WittDesign\n <sage.combinat.designs.block_design.WittDesign>` `W` on 24 points. We define\n two points `a,b`, and consider:\n\n - The collection `W_a` of all blocks of `W` containing `a` but not\n containing `b`.\n\n - The collection `W_b` of all blocks of `W` containing `b` but not\n containing `a`.\n\n The design is then obtained from the incidence structure produced by the\n blocks `A\\in W_a` and `B\\in W_b` whose intersection has cardinality 2. This\n construction, due to M.Smith, can be found in [KY04]_ or in 10.A.(v) of\n [BL1984]_.\n\n EXAMPLES::\n\n sage: H = designs.HigmanSimsDesign(); H # optional - gap_package_design\n Incidence structure with 176 points and 176 blocks\n sage: H.is_t_design(return_parameters=1) # optional - gap_package_design\n (True, (2, 176, 50, 14))\n\n Make sure that the automorphism group of this designs is isomorphic to the\n automorphism group of the\n :func:`~sage.graphs.generators.smallgraphs.HigmanSimsGraph`. Note that the\n first of those permutation groups acts on 176 points, while the second acts\n on 100::\n\n sage: gH = H.automorphism_group() # optional - gap_package_design\n sage: gG = graphs.HigmanSimsGraph().automorphism_group() # optional - gap_package_design\n sage: gG.is_isomorphic(gG) # long time, optional - gap_package_design\n True\n\n REFERENCE:\n\n .. [KY04] \\S. Klee and L. Yates,\n Tight Subdesigns of the Higman-Sims Design,\n Rose-Hulman Undergraduate Math. J 5.2 (2004).\n https://www.rose-hulman.edu/mathjournal/archives/2004/vol5-n2/paper9/v5n2-9pd.pdf\n '
from sage.combinat.designs.block_design import WittDesign
from .incidence_structures import IncidenceStructure
W = WittDesign(24)
(a, b) = (0, 1)
Wa = [set(B) for B in W if ((a in B) and (b not in B))]
Wb = [set(B) for B in W if ((b in B) and (a not in B))]
H = [[i for (i, A) in enumerate(Wa) if (len((A & B)) != 2)] for B in Wb]
return IncidenceStructure(H)
|
def BIBD_196_6_1():
'\n Return a (196,6,1)-BIBD.\n\n This constructions appears in II.3.32 from [DesignHandbook]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.database import BIBD_196_6_1\n sage: from sage.combinat.designs.bibd import BalancedIncompleteBlockDesign\n sage: BalancedIncompleteBlockDesign(196, BIBD_196_6_1())\n (196,6,1)-Balanced Incomplete Block Design\n '
from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet
from .incidence_structures import IncidenceStructure
a = 'a'
bibd = [((0, 0), (2, 0), (12, 0), (45, 0), (3, 1), (11, a)), ((0, 0), (3, 0), (8, 0), (5, 1), (17, 1), (39, a)), ((0, 0), (9, 0), (36, 0), (24, 1), (44, 1), (37, a)), ((0, 0), (15, 0), (34, 1), (41, 1), (47, 2), (18, a)), ((0, 0), (7, 0), (31, 0), (13, 1), (35, 2), (41, a)), ((0, 0), (14, 0), (32, 1), (10, 2), (22, a), (44, a)), ((0, 0), (23, 0), (21, 1), (39, 1), (19, a), (25, a)), ((0, 0), (33, 1), (0, a), (5, a), (29, a), (47, a)), ((0, 0), (1, 0), (0, 1), (30, 1), (0, 2), (18, 2)), ((8, 0), (19, 0), (44, 1), (31, 1), (46, 2), (48, 2))]
gens = (lambda B: [frozenset(((((x * 30) % 49), (((y + 1) % 3) if (y != a) else a)) for (x, y) in B)), frozenset(((((x + 1) % 49), y) for (x, y) in B))])
bibd = RecursivelyEnumeratedSet([frozenset(e) for e in bibd], successors=gens)
return IncidenceStructure(bibd)._blocks
|
def BIBD_201_6_1():
'\n Return a (201,6,1)-BIBD.\n\n This constructions appears in II.3.32 from [DesignHandbook]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.database import BIBD_201_6_1\n sage: from sage.combinat.designs.bibd import BalancedIncompleteBlockDesign\n sage: BalancedIncompleteBlockDesign(201, BIBD_201_6_1())\n (201,6,1)-Balanced Incomplete Block Design\n '
from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet
from .incidence_structures import IncidenceStructure
bibd = [((0, 0), (1, 0), (4, 2), (9, 2), (34, 2), (62, 2)), ((0, 1), (2, 1), (15, 1), (8, 2), (27, 2), (49, 2)), ((0, 0), (3, 0), (22, 0), (54, 1), (13, 2), (40, 2)), ((0, 0), (36, 0), (40, 0), (31, 1), (34, 1), (5, 2)), ((0, 0), (50, 0), (55, 0), (6, 1), (24, 1), (26, 2)), ((0, 0), (2, 0), (3, 1), (14, 1), (35, 1), (25, 2)), ((3, 1), (20, 1), (44, 1), (36, 2), (39, 2), (59, 2)), ((0, 0), (0, 1), (30, 1), (38, 1), (66, 1), (0, 2))]
gens = (lambda B: [frozenset(((((x * 29) % 67), y) for (x, y) in B)), frozenset(((((x + 1) % 67), y) for (x, y) in B))])
bibd = RecursivelyEnumeratedSet([frozenset(e) for e in bibd], successors=gens)
return IncidenceStructure(bibd)._blocks
|
def BIBD_79_13_2():
'\n Return a symmetric `(79,13,2)`-BIBD.\n\n The construction implemented is the one described in [Aschbacher71]_.\n A typo in that paper was corrected in [Hall71]_.\n\n .. NOTE::\n\n A symmetric `(v,k,\\lambda)` BIBD is a `(v,k,\\lambda)` BIBD with `v` blocks.\n\n EXAMPLES:\n\n sage: from sage.combinat.designs.database import BIBD_79_13_2\n sage: D = IncidenceStructure(BIBD_79_13_2()) # needs sage.libs.gap\n sage: D.is_t_design(t=2, v=79, k=13, l=2) # needs sage.libs.gap\n True\n '
from sage.libs.gap.libgap import libgap
g11 = libgap.Z(11)
one = (g11 ** 0)
zero = (0 * g11)
X = libgap([[one, one], [zero, one]])
Y = libgap([[(5 * one), zero], [zero, (9 * one)]])
Z = libgap([[(- one), zero], [zero, one]])
G = libgap.Group(X, Y, Z)
H1 = libgap.Group(X, Y)
H23 = libgap.Group(Y, Z)
H4 = libgap.Group(Z)
P1Action = G.FactorCosetAction(H1)
P23Action = G.FactorCosetAction(H23)
P4Action = G.FactorCosetAction(H4)
libgap.set_global('p1Act', P1Action)
libgap.set_global('p23Act', P23Action)
libgap.set_global('p4Act', P4Action)
action = libgap.function_factory('function(pair, g)\n local i, C, homs;\n i := pair[1];\n C := pair[2];\n homs := [p1Act, p23Act, p23Act, p4Act];\n return [i, C^(ImageElm(homs[i],g))];\n end;')
p1 = (1, 1)
p2 = (2, 1)
p3 = (3, 1)
p4 = (4, 1)
B1 = (list(libgap.Orbit(H4, p1, action)) + list(libgap.Orbit(G, p2, action)))
B2 = (list(libgap.Orbit(H4, p1, action)) + list(libgap.Orbit(G, p3, action)))
B3 = ((list(libgap([p1, p2, p3])) + list(libgap.Orbit(libgap.Group(Y), action(p4, X), action))) + list(libgap.Orbit(libgap.Group(Y), action(p4, (X ** 4)), action)))
B4 = [action(p2, (X ** 2)), action(p2, (X ** (- 2))), action(p3, (X ** 5)), action(p3, (X ** (- 5))), p4, action(p4, (X * (Y ** 2))), action(p4, ((X ** (- 1)) * (Y ** 2))), action(p4, (X * Y)), action(p4, ((X ** (- 1)) * Y)), action(p4, ((X ** 5) * Y)), action(p4, ((X ** (- 5)) * Y)), action(p4, ((X ** 5) * (Y ** 4))), action(p4, ((X ** (- 5)) * (Y ** 4)))]
points = []
for i in range(1, 5):
points += list(libgap.Orbit(G, (i, 1), action))
permAction = libgap.Action(G, points, action)
baseBlocks = [libgap.Set(list(map((lambda p: libgap.Position(points, p)), B))) for B in [B1, B2, B3, B4]]
B3Orbit = libgap.Orbit(permAction, baseBlocks[2], libgap.OnSets)
B4Orbit = libgap.Orbit(permAction, baseBlocks[3], libgap.OnSets)
blocks = ((baseBlocks[0:2] + list(B3Orbit)) + list(B4Orbit))
libgap.unset_global('p1Act')
libgap.unset_global('p23Act')
libgap.unset_global('p4Act')
return [[(int(t) - 1) for t in y] for y in blocks]
|
def BIBD_56_11_2():
'\n Return a symmetric `(56,11,2)`-BIBD.\n\n The construction implemented is given in [Hall71]_.\n\n .. NOTE::\n\n A symmetric `(v,k,\\lambda)` BIBD is a `(v,k,\\lambda)` BIBD with `v` blocks.\n\n EXAMPLES:\n\n sage: from sage.combinat.designs.database import BIBD_56_11_2\n sage: D = IncidenceStructure(BIBD_56_11_2()) # needs sage.libs.gap\n sage: D.is_t_design(t=2, v=56, k=11, l=2) # needs sage.libs.gap\n True\n '
from sage.libs.gap.libgap import libgap
from .incidence_structures import IncidenceStructure
a = (list(range(2, 57)) + [50])
a[6] = 1
a[13] = 8
a[20] = 15
a[27] = 22
a[34] = 29
a[41] = 36
a[48] = 43
b = [1, 8, 27, 36, 20, 14, 42, 41, 29, 52, 24, 30, 55, 22, 26, 21, 10, 40, 23, 53, 56, 6, 49, 46, 50, 32, 28, 3, 34, 48, 4, 15, 13, 9, 18, 31, 51, 39, 43, 35, 2, 54, 38, 25, 45, 11, 37, 12, 19, 44, 47, 17, 5, 7, 33, 16]
a = libgap.PermList(a)
b = libgap.PermList(b)
G = libgap.Group(a, b)
B = libgap.Set([1, 12, 19, 23, 30, 37, 45, 47, 48, 49, 51])
D = IncidenceStructure(libgap.Orbit(G, B, libgap.OnSets))
return D._blocks
|
def group_law(G):
'\n Return a triple ``(identity, operation, inverse)`` that define the\n operations on the group ``G``.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import group_law\n sage: group_law(Zmod(3))\n (0, <built-in function add>, <built-in function neg>)\n sage: group_law(SymmetricGroup(5)) # needs sage.groups\n ((), <built-in function mul>, <built-in function inv>)\n sage: group_law(VectorSpace(QQ, 3)) # needs sage.modules\n ((0, 0, 0), <built-in function add>, <built-in function neg>)\n '
import operator
from sage.categories.groups import Groups
from sage.categories.additive_groups import AdditiveGroups
if (G in Groups()):
return (G.one(), operator.mul, operator.inv)
elif (G in AdditiveGroups()):
return (G.zero(), operator.add, operator.neg)
else:
raise ValueError(('%s does not seem to be a group' % G))
|
def block_stabilizer(G, B):
'\n Compute the left stabilizer of the block ``B`` under the action of ``G``.\n\n This function return the list of all `x\\in G` such that `x\\cdot B=B` (as a\n set).\n\n INPUT:\n\n - ``G`` -- a group (additive or multiplicative)\n - ``B`` -- a subset of ``G``\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import block_stabilizer\n\n sage: Z8 = Zmod(8)\n sage: block_stabilizer(Z8, [Z8(0),Z8(2),Z8(4),Z8(6)])\n [0, 2, 4, 6]\n sage: block_stabilizer(Z8, [Z8(0),Z8(2)])\n [0]\n\n sage: C = cartesian_product([Zmod(4),Zmod(3)])\n sage: block_stabilizer(C, [C((0,0)),C((2,0)),C((0,1)),C((2,1))])\n [(0, 0), (2, 0)]\n\n sage: b = list(map(Zmod(45),[1, 3, 7, 10, 22, 25, 30, 35, 37, 38, 44]))\n sage: block_stabilizer(Zmod(45),b)\n [0]\n '
if (not B):
return list(G)
(identity, op, inv) = group_law(G)
b0 = inv(B[0])
S = []
for b in B:
bb0 = op(b, b0)
if all(((op(bb0, c) in B) for c in B)):
S.append(bb0)
return S
|
def is_difference_family(G, D, v=None, k=None, l=None, verbose=False):
"\n Check whether ``D`` forms a difference family in the group ``G``.\n\n INPUT:\n\n - ``G`` -- group of cardinality ``v``\n - ``D`` -- a set of ``k``-subsets of ``G``\n - ``v``, ``k`` and ``l`` -- optional parameters of the difference family\n - ``verbose`` -- boolean (default: ``False``); whether to print additional\n information\n\n .. SEEALSO::\n\n :func:`difference_family`\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import is_difference_family\n sage: G = Zmod(21)\n sage: D = [[0,1,4,14,16]]\n sage: is_difference_family(G, D, 21, 5)\n True\n\n sage: G = Zmod(41)\n sage: D = [[0,1,4,11,29],[0,2,8,17,21]]\n sage: is_difference_family(G, D, verbose=True)\n Too few:\n 5 is obtained 0 times in blocks []\n 14 is obtained 0 times in blocks []\n 27 is obtained 0 times in blocks []\n 36 is obtained 0 times in blocks []\n Too much:\n 4 is obtained 2 times in blocks [0, 1]\n 13 is obtained 2 times in blocks [0, 1]\n 28 is obtained 2 times in blocks [0, 1]\n 37 is obtained 2 times in blocks [0, 1]\n False\n sage: D = [[0,1,4,11,29],[0,2,8,17,22]]\n sage: is_difference_family(G, D)\n True\n\n sage: G = Zmod(61)\n sage: D = [[0,1,3,13,34],[0,4,9,23,45],[0,6,17,24,32]]\n sage: is_difference_family(G, D)\n True\n\n sage: # needs sage.modules\n sage: G = AdditiveAbelianGroup([3]*4)\n sage: a,b,c,d = G.gens()\n sage: D = [[d, -a+d, -c+d, a-b-d, b+c+d],\n ....: [c, a+b-d, -b+c, a-b+d, a+b+c],\n ....: [-a-b+c+d, a-b-c-d, -a+c-d, b-c+d, a+b],\n ....: [-b-d, a+b+d, a-b+c-d, a-b+c, -b+c+d]]\n sage: is_difference_family(G, D)\n True\n\n The following example has a third block with a non-trivial stabilizer::\n\n sage: G = Zmod(15)\n sage: D = [[0,1,4],[0,2,9],[0,5,10]]\n sage: is_difference_family(G,D,verbose=True)\n It is a (15,3,1)-difference family\n True\n\n The function also supports multiplicative groups (non necessarily Abelian)::\n\n sage: # needs sage.groups\n sage: G = DihedralGroup(8)\n sage: x,y = G.gens()\n sage: i = G.one()\n sage: D1 = [[i,x,x^4], [i,x^2, y*x], [i,x^5,y], [i,x^6,y*x^2], [i,x^7,y*x^5]]\n sage: is_difference_family(G, D1, 16, 3, 2)\n True\n sage: from sage.combinat.designs.bibd import BIBD_from_difference_family\n sage: bibd = BIBD_from_difference_family(G, D1, lambd=2)\n\n TESTS::\n\n sage: # needs sage.rings.finite_rings\n sage: K = GF(3^2,'z')\n sage: z = K.gen()\n sage: D = [[1,z+1,2]]\n sage: _ = is_difference_family(K, D, verbose=True)\n the number of differences (=6) must be a multiple of v-1=8\n sage: _\n False\n "
(identity, mul, inv) = group_law(G)
Glist = list(G)
D = [[G(_) for _ in d] for d in D]
if (v is None):
v = len(Glist)
elif (len(Glist) != v):
if verbose:
print(('G must have cardinality v (=%d)' % int(v)))
return False
if (k is None):
k = len(D[0])
else:
k = int(k)
for d in D:
if (len(d) != k):
if verbose:
print('the block {} does not have length {}'.format(d, k))
return False
nb_diff = 0
stab = []
for d in D:
s = block_stabilizer(G, d)
stab.append(s)
nb_diff += ((k * (k - 1)) // len(s))
if (l is None):
if ((nb_diff % (v - 1)) != 0):
if verbose:
print('the number of differences (={}) must be a multiple of v-1={}'.format(nb_diff, (v - 1)))
return False
l = (nb_diff // (v - 1))
elif (nb_diff != (l * (v - 1))):
if verbose:
print('the number of differences (={}) is not equal to l*(v-1) = {}'.format(nb_diff, (l * (v - 1))))
return False
counter = {g: 0 for g in Glist}
where = {g: set() for g in Glist}
del counter[identity]
for (i, d) in enumerate(D):
tmp_counter = {}
for b in d:
for c in d:
if (b == c):
continue
gg = mul(b, inv(c))
if (gg not in tmp_counter):
tmp_counter[gg] = 0
where[gg].add(i)
tmp_counter[gg] += 1
if (sum(tmp_counter.values()) != (k * (k - 1))):
if verbose:
print('repeated element in the {}-th block {}'.format(i, d))
return False
stabi = len(stab[i])
for gg in tmp_counter:
counter[gg] += (tmp_counter[gg] // stabi)
too_few = []
too_much = []
for g in Glist:
if (g == identity):
continue
if (counter[g] < l):
if verbose:
too_few.append(g)
else:
return False
if (counter[g] > l):
if verbose:
too_much.append(g)
else:
return False
if too_few:
print('Too few:')
for g in too_few:
print(' {} is obtained {} times in blocks {}'.format(g, counter[g], sorted(where[g])))
if too_much:
print('Too much:')
for g in too_much:
print(' {} is obtained {} times in blocks {}'.format(g, counter[g], sorted(where[g])))
if (too_few or too_much):
return False
if verbose:
print('It is a ({},{},{})-difference family'.format(v, k, l))
return True
|
def singer_difference_set(q, d):
'\n Return a difference set associated to the set of hyperplanes in a projective\n space of dimension `d` over `GF(q)`.\n\n A Singer difference set has parameters:\n\n .. MATH::\n\n v = \\frac{q^{d+1}-1}{q-1}, \\quad\n k = \\frac{q^d-1}{q-1}, \\quad\n \\lambda = \\frac{q^{d-1}-1}{q-1}.\n\n The idea of the construction is as follows. One consider the finite field\n `GF(q^{d+1})` as a vector space of dimension `d+1` over `GF(q)`. The set of\n `GF(q)`-lines in `GF(q^{d+1})` is a projective plane and its set of\n hyperplanes form a balanced incomplete block design.\n\n Now, considering a multiplicative generator `z` of `GF(q^{d+1})`, we get a\n transitive action of a cyclic group on our projective plane from which it is\n possible to build a difference set.\n\n The construction is given in details in [Stinson2004]_, section 3.3.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import singer_difference_set, is_difference_family\n sage: G,D = singer_difference_set(3,2) # needs sage.rings.finite_rings\n sage: is_difference_family(G, D, verbose=True) # needs sage.rings.finite_rings\n It is a (13,4,1)-difference family\n True\n\n sage: G,D = singer_difference_set(4,2) # needs sage.rings.finite_rings\n sage: is_difference_family(G, D, verbose=True) # needs sage.rings.finite_rings\n It is a (21,5,1)-difference family\n True\n\n sage: G,D = singer_difference_set(3,3) # needs sage.rings.finite_rings\n sage: is_difference_family(G, D, verbose=True) # needs sage.rings.finite_rings\n It is a (40,13,4)-difference family\n True\n\n sage: G,D = singer_difference_set(9,3) # needs sage.rings.finite_rings\n sage: is_difference_family(G, D, verbose=True) # needs sage.rings.finite_rings\n It is a (820,91,10)-difference family\n True\n '
q = Integer(q)
assert q.is_prime_power()
assert (d >= 2)
from sage.rings.finite_rings.finite_field_constructor import GF
from sage.rings.finite_rings.conway_polynomials import conway_polynomial
from sage.rings.finite_rings.integer_mod_ring import Zmod
(p, e) = q.factor()[0]
c = conway_polynomial(p, (e * (d + 1)))
if (e != 1):
K = GF(q, 'z')
c = c.change_ring(K).factor()[0][0]
else:
K = GF(q)
z = c.parent().gen()
powers = [0]
i = 1
x = z
k = (((q ** d) - 1) // (q - 1))
while (len(powers) < k):
if (x.degree() <= (d - 1)):
powers.append(i)
x = (x * z).mod(c)
i += 1
return (Zmod((((q ** (d + 1)) - 1) // (q - 1))), [powers])
|
def df_q_6_1(K, existence=False, check=True):
"\n Return a `(q,6,1)`-difference family over the finite field `K`.\n\n The construction uses Theorem 11 of [Wi72]_.\n\n EXAMPLES::\n\n sage: # needs sage.rings.finite_rings\n sage: from sage.combinat.designs.difference_family import is_difference_family, df_q_6_1\n sage: prime_powers = [v for v in range(31,500,30) if is_prime_power(v)]\n sage: parameters = [v for v in prime_powers\n ....: if df_q_6_1(GF(v,'a'), existence=True) is True]\n sage: parameters\n [31, 151, 181, 211, 241, 271, 331, 361, 421]\n sage: for v in parameters:\n ....: K = GF(v, 'a')\n ....: df = df_q_6_1(K, check=True)\n ....: assert is_difference_family(K, df, v, 6, 1)\n\n .. TODO::\n\n Do improvements due to Zhen and Wu 1999.\n "
v = K.cardinality()
x = K.multiplicative_generator()
one = K.one()
if ((v % 30) != 1):
if existence:
return False
raise EmptySetError('k(k-1)=30 should divide (v-1)')
t = ((v - 1) // 30)
r = (x ** ((v - 1) // 3))
r2 = (r * r)
xx = (x ** 5)
to_coset = {((x ** i) * (xx ** j)): i for i in range(5) for j in range(((v - 1) / 5))}
for c in to_coset:
if ((c == one) or (c == r) or (c == r2)):
continue
if (len(set((to_coset[elt] for elt in ((r - one), (c * (r - one)), (c - one), (c - r), (c - (r ** 2)))))) == 5):
if existence:
return True
B = [one, r, r2, c, (c * r), (c * r2)]
D = [[((xx ** i) * b) for b in B] for i in range(t)]
break
else:
if existence:
return Unknown
raise NotImplementedError('Wilson construction failed for v={}'.format(v))
if (check and (not is_difference_family(K, D, v, 6, 1))):
raise RuntimeError('Wilson 1972 construction failed! Please e-mail sage-devel@googlegroups.com')
return D
|
def radical_difference_set(K, k, l=1, existence=False, check=True):
'\n Return a difference set made of a cyclotomic coset in the finite field\n ``K`` and with parameters ``k`` and ``l``.\n\n Most of these difference sets appear in chapter VI.18.48 of the Handbook of\n combinatorial designs.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import radical_difference_set\n\n sage: D = radical_difference_set(GF(7), 3, 1); D # needs sage.rings.finite_rings\n [[1, 2, 4]]\n sage: sorted(x-y for x in D[0] for y in D[0] if x != y) # needs sage.rings.finite_rings\n [1, 2, 3, 4, 5, 6]\n\n sage: D = radical_difference_set(GF(16,\'a\'), 6, 2) # needs sage.rings.finite_rings\n sage: sorted(x-y for x in D[0] for y in D[0] if x != y) # needs sage.rings.finite_rings\n [1,\n 1,\n a,\n a,\n a + 1,\n a + 1,\n a^2,\n a^2,\n ...\n a^3 + a^2 + a + 1,\n a^3 + a^2 + a + 1]\n\n sage: for k in range(2,50): # needs sage.rings.finite_rings\n ....: for l in reversed(divisors(k*(k-1))):\n ....: v = k*(k-1)//l + 1\n ....: if is_prime_power(v) and radical_difference_set(GF(v,\'a\'),k,l,existence=True) is True:\n ....: _ = radical_difference_set(GF(v,\'a\'),k,l)\n ....: print("{:3} {:3} {:3}".format(v,k,l))\n 3 2 1\n 4 3 2\n 7 3 1\n 5 4 3\n 7 4 2\n 13 4 1\n 11 5 2\n 7 6 5\n 11 6 3\n 16 6 2\n 8 7 6\n 9 8 7\n 19 9 4\n 37 9 2\n 73 9 1\n 11 10 9\n 19 10 5\n 23 11 5\n 13 12 11\n 23 12 6\n 27 13 6\n 27 14 7\n 16 15 14\n 31 15 7\n ...\n 41 40 39\n 79 40 20\n 83 41 20\n 43 42 41\n 83 42 21\n 47 46 45\n 49 48 47\n 197 49 12\n '
v = K.cardinality()
if ((l * (v - 1)) != (k * (k - 1))):
if existence:
return False
raise EmptySetError('l*(v-1) is not equal to k*(k-1)')
if ((v - 1) == k):
if existence:
return True
add_zero = False
elif (((v % 4) == 3) and (k == ((v - 1) // 2))):
if existence:
return True
add_zero = False
elif (((v % 4) == 3) and (k == ((v + 1) // 2))):
if existence:
return True
add_zero = True
elif (((v % 8) == 5) and (k == ((v - 1) // 4)) and arith.is_square(((v - 1) // 4))):
if existence:
return True
add_zero = False
elif (((v % 8) == 5) and (k == ((v + 3) // 4)) and arith.is_square(((v - 9) // 4))):
if existence:
return True
add_zero = True
elif ((v, k, l) == (16, 6, 2)):
if existence:
return True
add_zero = True
elif ((v, k, l) == (73, 9, 1)):
if existence:
return True
add_zero = False
else:
x = K.multiplicative_generator()
D = K.cyclotomic_cosets((x ** ((v - 1) // k)), [K.one()])
if is_difference_family(K, D, v, k, l):
print('** You found a new example of radical difference set **\n** for the parameters (v,k,l)=({},{},{}). **\n** Please contact sage-devel@googlegroups.com **\n'.format(v, k, l))
if existence:
return True
add_zero = False
else:
D = K.cyclotomic_cosets((x ** ((v - 1) // (k - 1))), [K.one()])
D[0].insert(0, K.zero())
if is_difference_family(K, D, v, k, l):
print('** You found a new example of radical difference set **\n** for the parameters (v,k,l)=({},{},{}). **\n** Please contact sage-devel@googlegroups.com **\n'.format(v, k, l))
if existence:
return True
add_zero = True
elif existence:
return False
else:
raise EmptySetError('no radical difference set exist for the parameters (v,k,l) = ({},{},{}'.format(v, k, l))
x = K.multiplicative_generator()
if add_zero:
r = (x ** ((v - 1) // (k - 1)))
D = K.cyclotomic_cosets(r, [K.one()])
D[0].insert(0, K.zero())
else:
r = (x ** ((v - 1) // k))
D = K.cyclotomic_cosets(r, [K.one()])
if (check and (not is_difference_family(K, D, v, k, l))):
raise RuntimeError('Sage tried to build a radical difference set with parameters ({},{},{}) but it seems that it failed! Please e-mail sage-devel@googlegroups.com'.format(v, k, l))
return D
|
def one_cyclic_tiling(A, n):
"\n Given a subset ``A`` of the cyclic additive group `G = Z / nZ` return\n another subset `B` so that `A + B = G` and `|A| |B| = n` (i.e. any element\n of `G` is uniquely expressed as a sum `a+b` with `a` in `A` and `b` in `B`).\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import one_cyclic_tiling\n sage: tile = [0,2,4]\n sage: m = one_cyclic_tiling(tile,6); m\n [0, 3]\n sage: sorted((i+j)%6 for i in tile for j in m)\n [0, 1, 2, 3, 4, 5]\n\n sage: def print_tiling(tile, translat, n):\n ....: for x in translat:\n ....: print(''.join('X' if (i-x)%n in tile else '.' for i in range(n)))\n\n sage: tile = [0, 1, 2, 7]\n sage: m = one_cyclic_tiling(tile, 12)\n sage: print_tiling(tile, m, 12)\n XXX....X....\n ....XXX....X\n ...X....XXX.\n\n sage: tile = [0, 1, 5]\n sage: m = one_cyclic_tiling(tile, 12)\n sage: print_tiling(tile, m, 12)\n XX...X......\n ...XX...X...\n ......XX...X\n ..X......XX.\n\n sage: tile = [0, 2]\n sage: m = one_cyclic_tiling(tile, 8)\n sage: print_tiling(tile, m, 8)\n X.X.....\n ....X.X.\n .X.X....\n .....X.X\n\n ALGORITHM:\n\n Uses dancing links :mod:`sage.combinat.dlx`\n "
n = int(n)
d = len(A)
if (len(set(((a % d) for a in A))) == d):
return [(i * d) for i in range((n // d))]
from sage.combinat.dlx import DLXMatrix
rows = []
for i in range(n):
rows.append([(i + 1), [(((i + a) % n) + 1) for a in A]])
M = DLXMatrix(rows)
for c in M:
return [(i - 1) for i in c]
|
def one_radical_difference_family(K, k):
'\n Search for a radical difference family on ``K`` using dancing links\n algorithm.\n\n For the definition of radical difference family, see\n :func:`radical_difference_family`. Here, we consider only radical difference\n family with `\\lambda = 1`.\n\n INPUT:\n\n - ``K`` -- a finite field of cardinality `q`\n - ``k`` -- a positive integer so that `k(k-1)` divides `q-1`\n\n OUTPUT:\n\n Either a difference family or ``None`` if it does not exist.\n\n ALGORITHM:\n\n The existence of a radical difference family is equivalent to a one\n dimensional tiling (or packing) problem in a cyclic group. This subsequent\n problem is solved by a call to the function :func:`one_cyclic_tiling`.\n\n Let `K^*` be the multiplicative group of the finite field `K`. A radical\n family has the form `\\mathcal B = \\{x_1 B, \\ldots, x_k B\\}`, where\n `B=\\{x:x^{k}=1\\}` (for `k` odd) or `B=\\{x:x^{k-1}=1\\}\\cup \\{0\\}` (for\n `k` even). Equivalently, `K^*` decomposes as:\n\n .. MATH::\n\n K^* = \\Delta (x_1 B) \\cup \\cdots \\cup \\Delta (x_k B)\n = x_1 \\Delta B \\cup \\cdots \\cup x_k \\Delta B.\n\n We observe that `C=B\\backslash 0` is a subgroup of the (cyclic) group\n `K^*`, that can thus be generated by some element `r`. Furthermore, we\n observe that `\\Delta B` is always a union of cosets of `\\pm C` (which is\n twice larger than `C`).\n\n .. MATH::\n\n \\begin{array}{llll}\n (k\\text{ odd} ) & \\Delta B &= \\{r^i-r^j:r^i\\neq r^j\\} &= \\pm C\\cdot \\{r^i-1: 0 < i \\leq m\\}\\\\\n (k\\text{ even}) & \\Delta B &= \\{r^i-r^j:r^i\\neq r^j\\}\\cup C &= \\pm C\\cdot \\{r^i-1: 0 < i < m\\}\\cup \\pm C\n \\end{array}\n\n where\n\n .. MATH::\n\n (k\\text{ odd})\\ m = (k-1)/2 \\quad \\text{and} \\quad (k\\text{ even})\\ m = k/2.\n\n Consequently, `\\mathcal B = \\{x_1 B, \\ldots, x_k B\\}` is a radical\n difference family if and only if `\\{x_1 (\\Delta B/(\\pm C)), \\ldots, x_k\n (\\Delta B/(\\pm C))\\}` is a partition of the cyclic group `K^*/(\\pm C)`.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import (\n ....: one_radical_difference_family,\n ....: is_difference_family)\n\n sage: one_radical_difference_family(GF(13),4) # needs sage.rings.finite_rings\n [[0, 1, 3, 9]]\n\n The parameters that appear in [Bu95]_::\n\n sage: df = one_radical_difference_family(GF(449), 8); df # needs sage.rings.finite_rings\n [[0, 1, 18, 25, 176, 324, 359, 444],\n [0, 9, 88, 162, 222, 225, 237, 404],\n [0, 11, 140, 198, 275, 357, 394, 421],\n [0, 40, 102, 249, 271, 305, 388, 441],\n [0, 49, 80, 93, 161, 204, 327, 433],\n [0, 70, 99, 197, 230, 362, 403, 435],\n [0, 121, 141, 193, 293, 331, 335, 382],\n [0, 191, 285, 295, 321, 371, 390, 392]]\n sage: is_difference_family(GF(449), df, 449, 8, 1) # needs sage.rings.finite_rings\n True\n '
q = K.cardinality()
x = K.multiplicative_generator()
e = (k * (k - 1))
if ((q % e) != 1):
raise ValueError('q%e is not 1')
if ((k % 2) == 1):
m = ((k - 1) // 2)
r = (x ** ((q - 1) // k))
A = [((r ** i) - 1) for i in range(1, (m + 1))]
else:
m = (k // 2)
r = (x ** ((q - 1) // (k - 1)))
A = [((r ** i) - 1) for i in range(1, m)]
A.append(K.one())
c = ((m * (q - 1)) // e)
from sage.groups.generic import discrete_log
logA = [(discrete_log(a, x) % c) for a in A]
if (len(set(logA)) != m):
return None
tiling = one_cyclic_tiling(logA, c)
if (tiling is None):
return None
D = K.cyclotomic_cosets(r, [(x ** i) for i in tiling])
if ((k % 2) == 0):
for d in D:
d.insert(K.zero(), 0)
return D
|
def radical_difference_family(K, k, l=1, existence=False, check=True):
'\n Return a ``(v,k,l)``-radical difference family.\n\n Let fix an integer `k` and a prime power `q = t k(k-1) + 1`. Let `K` be a\n field of cardinality `q`. A `(q,k,1)`-difference family is *radical* if\n its base blocks are either: a coset of the `k`-th root of unity for `k` odd\n or a coset of `k-1`-th root of unity and `0` if `k` is even (the number `t`\n is the number of blocks of that difference family).\n\n The terminology comes from M. Buratti article [Bu95]_ but the first\n constructions go back to R. Wilson [Wi72]_.\n\n INPUT:\n\n - ``K`` - a finite field\n - ``k`` -- positive integer; the size of the blocks\n - ``l`` -- integer (default: ``1``); the `\\lambda` parameter\n - ``existence`` -- if ``True``, then return either ``True`` if Sage knows\n how to build such design, ``Unknown`` if it does not and ``False`` if it\n knows that the design does not exist\n - ``check`` -- boolean (default: ``True``); if ``True`` then the result of\n the computation is checked before being returned. This should not be\n needed but ensures that the output is correct\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import radical_difference_family\n\n sage: radical_difference_family(GF(73), 9) # needs sage.rings.finite_rings\n [[1, 2, 4, 8, 16, 32, 37, 55, 64]]\n\n sage: radical_difference_family(GF(281), 5) # needs sage.rings.finite_rings\n [[1, 86, 90, 153, 232],\n [4, 50, 63, 79, 85],\n [5, 36, 149, 169, 203],\n [7, 40, 68, 219, 228],\n [9, 121, 212, 248, 253],\n [29, 81, 222, 246, 265],\n [31, 137, 167, 247, 261],\n [32, 70, 118, 119, 223],\n [39, 56, 66, 138, 263],\n [43, 45, 116, 141, 217],\n [98, 101, 109, 256, 279],\n [106, 124, 145, 201, 267],\n [111, 123, 155, 181, 273],\n [156, 209, 224, 264, 271]]\n\n sage: for k in range(5,10): # needs sage.rings.finite_rings\n ....: print("k = {}".format(k))\n ....: list_q = []\n ....: for q in range(k*(k-1)+1, 2000, k*(k-1)):\n ....: if is_prime_power(q):\n ....: K = GF(q,\'a\')\n ....: if radical_difference_family(K, k, existence=True) is True:\n ....: list_q.append(q)\n ....: _ = radical_difference_family(K,k)\n ....: print(" ".join(str(p) for p in list_q))\n k = 5\n 41 61 81 241 281 401 421 601 641 661 701 761 821 881 1181 1201 1301 1321\n 1361 1381 1481 1601 1681 1801 1901\n k = 6\n 181 211 241 631 691 1531 1831 1861\n k = 7\n 337 421 463 883 1723\n k = 8\n 449 1009\n k = 9\n 73 1153 1873\n '
v = K.cardinality()
x = K.multiplicative_generator()
e = (k * (k - 1))
if ((l * (v - 1)) % e):
raise ValueError('k (k-1) = {} should be a multiple of l (v-1) ={}'.format((k * (k - 1)), (l * (v - 1))))
t = ((l * (v - 1)) // e)
if (t == 1):
return radical_difference_set(K, k, l, existence=existence, check=check)
elif (l == (k - 1)):
if existence:
return True
else:
return K.cyclotomic_cosets((x ** ((v - 1) // k)))[1:]
elif (l != 1):
if existence:
return Unknown
raise NotImplementedError('No radical families implemented for l > 2')
else:
D = one_radical_difference_family(K, k)
if (D is None):
if existence:
return False
raise EmptySetError('No such difference family')
elif existence:
return True
if (check and (not is_difference_family(K, D, v, k, l))):
raise RuntimeError('radical_difference_family produced a wrong difference family with parameters v={}, k={}, l={}. Please contact sage-devel@googlegroups.com'.format(v, k, l))
return D
|
def twin_prime_powers_difference_set(p, check=True):
'\n Return a difference set on `GF(p) \\times GF(p+2)`.\n\n The difference set is built from the following element of the Cartesian\n product of finite fields `GF(p) \\times GF(p+2)`:\n\n - `(x,0)` with any `x`\n - `(x,y)` with `x` and `y` squares\n - `(x,y)` with `x` and `y` non-squares\n\n For more information see :wikipedia:`Difference_set`.\n\n INPUT:\n\n - ``check`` -- boolean (default: ``True``); if ``True``, then the result of\n the computation is checked before being returned. This should not be\n needed but ensures that the output is correct\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import twin_prime_powers_difference_set\n sage: G, D = twin_prime_powers_difference_set(3)\n sage: G\n The Cartesian product of (Finite Field of size 3, Finite Field of size 5)\n sage: D\n [[(1, 1), (1, 4), (2, 2), (2, 3), (0, 0), (1, 0), (2, 0)]]\n '
from sage.rings.finite_rings.finite_field_constructor import FiniteField
from sage.categories.cartesian_product import cartesian_product
from itertools import product
Fp = FiniteField(p, 'x')
Fq = FiniteField((p + 2), 'x')
Fpset = set(Fp)
Fqset = set(Fq)
Fp_squares = set(((x ** 2) for x in Fpset))
Fq_squares = set(((x ** 2) for x in Fqset))
d = []
d.extend(product(Fp_squares.difference([0]), Fq_squares.difference([0])))
d.extend(product(Fpset.difference(Fp_squares), Fqset.difference(Fq_squares)))
d.extend(((x, 0) for x in Fpset))
G = cartesian_product([Fp, Fq])
if (check and (not is_difference_family(G, [d]))):
raise RuntimeError('twin_prime_powers_difference_set produced a wrong difference set with p={}. Please contact sage-devel@googlegroups.com'.format(p))
return (G, [d])
|
def are_mcfarland_1973_parameters(v, k, lmbda, return_parameters=False):
'\n Test whether ``(v,k,lmbda)`` is a triple that can be obtained from the\n construction from [McF1973]_.\n\n See :func:`mcfarland_1973_construction`.\n\n INPUT:\n\n - ``v``, ``k``, ``lmbda`` - integers; parameters of the difference family\n - ``return_parameters`` -- boolean (default ``False``); if ``True``, return a\n pair ``(True, (q, s))`` so that ``(q,s)`` can be used in the function\n :func:`mcfarland_1973_construction` to actually build a\n ``(v,k,lmbda)``-difference family. Or ``(False, None)`` if the\n construction is not possible\n\n EXAMPLES::\n\n sage: # needs sage.rings.finite_rings\n sage: from sage.combinat.designs.difference_family import are_mcfarland_1973_parameters\n sage: are_mcfarland_1973_parameters(64, 28, 12)\n True\n sage: are_mcfarland_1973_parameters(64, 28, 12, return_parameters=True)\n (True, (2, 2))\n sage: are_mcfarland_1973_parameters(60, 13, 5)\n False\n sage: are_mcfarland_1973_parameters(98125, 19500, 3875)\n True\n sage: are_mcfarland_1973_parameters(98125, 19500, 3875, True)\n (True, (5, 3))\n\n sage: from sage.combinat.designs.difference_family import are_mcfarland_1973_parameters\n sage: for v in range(1, 100): # needs sage.rings.finite_rings\n ....: for k in range(1,30):\n ....: for l in range(1,15):\n ....: if are_mcfarland_1973_parameters(v,k,l):\n ....: answer, (q,s) = are_mcfarland_1973_parameters(v,k,l,return_parameters=True)\n ....: print("{} {} {} {} {}".format(v,k,l,q,s))\n ....: assert answer is True\n ....: assert designs.difference_family(v,k,l,existence=True) is True\n ....: G,D = designs.difference_family(v,k,l)\n 16 6 2 2 1\n 45 12 3 3 1\n 64 28 12 2 2\n 96 20 4 4 1\n '
if ((v <= k) or (k <= lmbda)):
return ((False, None) if return_parameters else False)
k = ZZ(k)
lmbda = ZZ(lmbda)
(qs, r) = (k - lmbda).sqrtrem()
if (r or ((qs * (qs - 1)) % lmbda)):
return ((False, None) if return_parameters else False)
q = (((qs * (qs - 1)) // lmbda) + 1)
if ((q <= 1) or ((v * (q - 1)) != ((qs * q) * (((qs * q) + q) - 2))) or ((k * (q - 1)) != (qs * ((qs * q) - 1)))):
return ((False, None) if return_parameters else False)
(p1, a1) = qs.is_prime_power(get_data=True)
(p2, a2) = q.is_prime_power(get_data=True)
if ((a1 == 0) or (a2 == 0) or (p1 != p2) or (a1 % a2)):
return ((False, None) if return_parameters else False)
return ((True, (q, (a1 // a2))) if return_parameters else True)
|
def mcfarland_1973_construction(q, s):
'\n Return a difference set.\n\n The difference set returned has the following parameters\n\n .. MATH::\n\n v = \\frac{q^{s+1}(q^{s+1}+q-2)}{q-1},\n k = \\frac{q^s (q^{s+1}-1)}{q-1},\n \\lambda = \\frac{q^s(q^s-1)}{q-1}\n\n This construction is due to [McF1973]_.\n\n INPUT:\n\n - ``q``, ``s`` - integers; parameters for the difference set (see the above\n formulas for the expression of ``v``, ``k``, ``l`` in terms of ``q`` and\n ``s``)\n\n .. SEEALSO::\n\n The function :func:`are_mcfarland_1973_parameters` makes the translation\n between the parameters `(q,s)` corresponding to a given triple\n `(v,k,\\lambda)`.\n\n REFERENCES:\n\n .. [McF1973] Robert L. McFarland\n "A family of difference sets in non-cyclic groups"\n J. Combinatorial Theory (A) 15 (1973) 1--10.\n :doi:`10.1016/0097-3165(73)90031-9`\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import (\n ....: mcfarland_1973_construction, is_difference_family)\n\n sage: G,D = mcfarland_1973_construction(3, 1) # needs sage.modules\n sage: assert is_difference_family(G, D, 45, 12, 3) # needs sage.modules\n\n sage: G,D = mcfarland_1973_construction(2, 2) # needs sage.modules\n sage: assert is_difference_family(G, D, 64, 28, 12) # needs sage.modules\n '
from sage.rings.finite_rings.finite_field_constructor import GF
from sage.modules.free_module import VectorSpace
from sage.rings.finite_rings.integer_mod_ring import Zmod
from sage.categories.cartesian_product import cartesian_product
r = (((q ** (s + 1)) - 1) // (q - 1))
F = GF(q, 'a')
V = VectorSpace(F, (s + 1))
K = Zmod((r + 1))
G = cartesian_product((([F] * (s + 1)) + [K]))
D = []
for (k, H) in zip(K, V.subspaces(s)):
for v in H:
D.append(G((tuple(v) + (k,))))
return (G, [D])
|
def are_hadamard_difference_set_parameters(v, k, lmbda):
'\n Check whether ``(v,k,lmbda)`` is of the form ``(4N^2, 2N^2 - N, N^2 - N)``.\n\n INPUT:\n\n - ``(v,k,lmbda)`` -- parameters of a difference set\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import are_hadamard_difference_set_parameters\n sage: are_hadamard_difference_set_parameters(36, 15, 6)\n True\n sage: are_hadamard_difference_set_parameters(60, 13, 5)\n False\n '
N = (k - (2 * lmbda))
N2 = (N * N)
return ((v == (4 * N2)) and (k == ((2 * N2) - N)) and (lmbda == (N2 - N)))
|
@cached_function
def hadamard_difference_set_product_parameters(N):
'\n Check whether a product construction is available for Hadamard difference\n set with parameter ``N``.\n\n This function looks for two integers `N_1` and `N_2`` greater than `1`\n and so that `N = 2 N_1 N_2` and there exists Hadamard difference set with\n parameters `(4 N_i^2, 2N_i^2 - N_i, N_i^2 - N_i)`. If such pair exists,\n the output is the pair ``(N_1, N_2)`` otherwise it is ``None``.\n\n INPUT:\n\n - ``N`` -- positive integer\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import hadamard_difference_set_product_parameters\n sage: hadamard_difference_set_product_parameters(8) # needs sage.rings.finite_rings\n (2, 2)\n '
if (N % 2):
return False
for N1 in (N // 2).divisors()[1:]:
if ((4 * N1) > N):
break
v1 = ((4 * N1) * N1)
k1 = (((2 * N1) * N1) - N1)
l1 = ((N1 * N1) - N1)
if (not difference_family(v1, k1, l1, existence=True)):
continue
N2 = (N // (2 * N1))
v2 = ((4 * N2) * N2)
k2 = (((2 * N2) * N2) - N2)
l2 = ((N2 * N2) - N2)
if (not difference_family(v2, k2, l2, existence=True)):
continue
return (N1, N2)
return None
|
def hadamard_difference_set_product(G1, D1, G2, D2):
'\n Make a product of two Hadamard difference sets.\n\n This product construction appears in [Tu1984]_.\n\n INPUT:\n\n - ``G1,D1``, ``G2,D2`` -- two Hadamard difference sets\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import hadamard_difference_set_product\n sage: from sage.combinat.designs.difference_family import is_difference_family\n\n sage: G1,D1 = designs.difference_family(16,6,2) # needs sage.rings.finite_rings\n sage: G2,D2 = designs.difference_family(36,15,6) # needs sage.rings.finite_rings\n\n sage: G11,D11 = hadamard_difference_set_product(G1,D1,G1,D1) # needs sage.rings.finite_rings\n sage: assert is_difference_family(G11, D11, 256, 120, 56) # needs sage.rings.finite_rings\n sage: assert designs.difference_family(256, 120, 56, existence=True) is True # needs sage.rings.finite_rings\n\n sage: G12,D12 = hadamard_difference_set_product(G1,D1,G2,D2) # needs sage.rings.finite_rings\n sage: assert is_difference_family(G12, D12, 576, 276, 132) # needs sage.rings.finite_rings\n sage: assert designs.difference_family(576, 276, 132, existence=True) is True # needs sage.rings.finite_rings\n '
from sage.categories.cartesian_product import cartesian_product
G = cartesian_product([G1, G2])
D1 = set(D1[0])
D1c = set((s for s in G1 if (s not in D1)))
D2 = set(D2[0])
D2c = set((s for s in G2 if (s not in D2)))
D = set().union((G((s1, s2)) for s1 in D1 for s2 in D2), (G((s1, s2)) for s1 in D1c for s2 in D2c))
return (G, [[s for s in G if (s not in D)]])
|
def turyn_1965_3x3xK(k=4):
'\n Return a difference set in either `C_3 \\times C_3 \\times C_4` or `C_3 \\times\n C_3 \\times C_2 \\times C_2` with parameters `v=36`, `k=15`, `\\lambda=6`.\n\n This example appears in [Tu1965]_.\n\n INPUT:\n\n - ``k`` -- either ``2`` (to get a difference set in `C_3 \\times C_3 \\times\n C_2 \\times C_2`) or ``4`` (to get a difference set in `C_3 \\times C_3\n \\times C_3 \\times C_4`)\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import turyn_1965_3x3xK\n sage: from sage.combinat.designs.difference_family import is_difference_family\n sage: G,D = turyn_1965_3x3xK(4)\n sage: assert is_difference_family(G, D, 36, 15, 6)\n sage: G,D = turyn_1965_3x3xK(2)\n sage: assert is_difference_family(G, D, 36, 15, 6)\n '
from sage.categories.cartesian_product import cartesian_product
from sage.rings.finite_rings.integer_mod_ring import Zmod
if (k == 2):
G = cartesian_product([Zmod(3), Zmod(3), Zmod(2), Zmod(2)])
K = [(0, 0), (0, 1), (1, 0), (1, 1)]
elif (k == 4):
G = cartesian_product([Zmod(3), Zmod(3), Zmod(4)])
K = [(0,), (1,), (2,), (3,)]
else:
raise ValueError('k must be 2 or 4')
L = [[(0, 1), (1, 1), (2, 1), (0, 2), (1, 2), (2, 2)], [(0, 0), (1, 1), (2, 2)], [(0, 0), (1, 2), (2, 1)], [(0, 0), (0, 1), (0, 2)]]
return (G, [[G((v + k)) for (l, k) in zip(L, K) for v in l]])
|
def _is_periodic_sequence(seq, period):
'\n Check if the sequence is periodic with correct period.\n\n The sequence should have length at least twice the period, so that\n periodicity can be checked.\n\n INPUT:\n\n - ``seq`` -- the sequence to be tested (must have length at least twice the period)\n - ``period`` -- integer; the period that the sequence should have\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import _is_periodic_sequence\n sage: _is_periodic_sequence([0, 1, 2, 3, 0, 1, 2, 3], 4)\n True\n sage: _is_periodic_sequence([0, 1, 0, 1, 0, 1, 0, 1], 4)\n False\n sage: _is_periodic_sequence([0, 1, 1, 1, 0, 1, 2, 1], 4)\n False\n '
assert (len(seq) >= (2 * period))
for per in range(1, period):
first = seq[:per]
periodic = True
for j in range(1, (len(seq) // per)):
if (seq[(j * per):((j + 1) * per)] != first):
periodic = False
break
if periodic:
return False
if (seq[:period] != seq[period:(2 * period)]):
return False
return True
|
def _create_m_sequence(q, n, check=True):
'\n Create an m-sequence over GF(q) with period `q^n - 1`.\n\n Given a prime power `q`, the m-sequence is created as described by [Zie1959]_\n from a primitive function over the finite field `GF(q)`.\n\n Given a primitive function `f=c_0+c_1x+...+c_nx^n` over `K = GF(q)` of degree `n`,\n the recurrence is given by: `a_i = -c_0^{-1}(c_1a_{i-1} + ... + c_na{i-n})`.\n The first `n` elements will be `0, 0, ..., 0, 1` and these will give a maximal length recurrence sequence\n as shown in [Mit2008]_.\n\n INPUT:\n\n - ``q`` -- a prime power\n - ``n`` -- a nonnegative number\n - ``check`` -- boolean (default: ``True``); if ``True``, check that the\n result is a sequence with correct period; detting it to ``False`` may\n speed up considerably the computation\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import _create_m_sequence\n sage: _create_m_sequence(3, 2) # random # needs sage.rings.finite_rings\n [1, 0, 1, 2, 2, 0, 2, 1]\n sage: _create_m_sequence(4, 2, check=False) # random # needs sage.rings.finite_rings\n [1, 0, a, a + 1, a, a, 0, a + 1, 1, a + 1, a + 1, 0, 1, a, 1]\n sage: _create_m_sequence(6, 2)\n Traceback (most recent call last):\n ...\n ValueError: q must be a prime power\n\n '
from sage.rings.finite_rings.finite_field_constructor import GF
if (not is_prime_power(q)):
raise ValueError('q must be a prime power')
if (n < 0):
raise ValueError('n cannot be negative')
K = GF(q, 'a')
T = PolynomialRing(K, 'x')
primitive = T.irreducible_element(n, algorithm='random')
while (not primitive.is_primitive()):
primitive = T.irreducible_element(n, algorithm='random')
coeffs = primitive.coefficients()
exps = primitive.exponents()
period = ((q ** n) - 1)
seq_len = ((period * 2) if check else period)
seq = ([1] + ([0] * (n - 1)))
while (len(seq) < seq_len):
nxt = 0
for (i, coeff) in zip(exps[1:], coeffs[1:]):
nxt += (coeff * seq[(- i)])
seq.append(((- coeffs[0].inverse()) * nxt))
if check:
assert _is_periodic_sequence(seq, period)
return seq[:period]
|
def _get_submodule_of_order(G, order):
'\n Construct a submodule of the given order from group ``G``.\n\n This method tries to construct submodules from various elements of `G` until\n a submodule of the correct order is found.\n\n INPUT:\n\n - ``G`` -- an additive abelian group\n - ``order`` -- integer; the order of the desired submodule\n\n TESTS:\n\n sage: # needs sage.modules\n sage: from sage.combinat.designs.difference_family import _get_submodule_of_order\n sage: G = AdditiveAbelianGroup([48])\n sage: _get_submodule_of_order(G, 6).order()\n 6\n sage: G = AdditiveAbelianGroup([13^2 - 1])\n sage: _get_submodule_of_order(G, 12).order()\n 12\n '
for el in G:
H = G.submodule([el])
if (H.order() == order):
return H
return None
|
def relative_difference_set_from_m_sequence(q, N, check=True, return_group=False):
'\n Construct `R((q^N-1)/(q-1), q-1, q^{N-1}, q^{N-2})` where ``q`` is a prime power and `N\\ge 2`.\n\n The relative difference set is constructed over the set of additive integers modulo `q^N-1`,\n as described in Theorem 5.1 of [EB1966]_. Given an m-sequence `(a_i)` of period `q^N-1`, the\n set is: `R=\\{i | 0 \\le i \\le q^{N-1}, a_i=1\\}`.\n\n INPUT:\n\n - ``q`` -- a prime power\n - ``N`` -- a nonnegative number\n - ``check`` -- boolean (default: ``True``); if ``True``, check that the\n result is a relative difference set before returning it\n - ``return_group`` -- boolean (default: ``False``); if ``True``, the function\n will also return the group from which the set is created\n\n OUTPUT:\n\n If ``return_group=False``, the function return only the relative difference\n set. Otherwise, it returns a tuple containing the group and the set.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import relative_difference_set_from_m_sequence\n sage: relative_difference_set_from_m_sequence(2, 4, # random # needs sage.modules sage.rings.finite_rings\n ....: return_group=True)\n (Additive abelian group isomorphic to Z/15,\n [(0), (4), (5), (6), (7), (9), (11), (12)])\n sage: relative_difference_set_from_m_sequence(8, 2, check=False) # random # needs sage.modules sage.rings.finite_rings\n [(0), (6), (30), (40), (41), (44), (56), (61)]\n sage: relative_difference_set_from_m_sequence(6, 2) # needs sage.modules\n Traceback (most recent call last):\n ...\n ValueError: q must be a prime power\n\n TESTS::\n\n sage: from sage.combinat.designs.difference_family import is_relative_difference_set, _get_submodule_of_order\n sage: q, N = 5, 3\n sage: G, D = relative_difference_set_from_m_sequence(q, N, check=False, # needs sage.modules sage.rings.finite_rings\n ....: return_group=True)\n sage: H = _get_submodule_of_order(G, q-1) # needs sage.modules sage.rings.finite_rings\n sage: is_relative_difference_set(D, G, H, # needs sage.modules sage.rings.finite_rings\n ....: ((q^N-1)//(q-1), q-1, q^(N-1), q^(N-2)))\n True\n sage: q, N = 13, 2\n sage: G, D = relative_difference_set_from_m_sequence(q, N, check=False, # needs sage.modules sage.rings.finite_rings\n ....: return_group=True)\n sage: H = _get_submodule_of_order(G, q-1) # needs sage.modules sage.rings.finite_rings\n sage: is_relative_difference_set(D, G, H, # needs sage.modules sage.rings.finite_rings\n ....: ((q^N-1)//(q-1), q-1, q^(N-1), q^(N-2)))\n True\n '
from sage.groups.additive_abelian.additive_abelian_group import AdditiveAbelianGroup
if (not is_prime_power(q)):
raise ValueError('q must be a prime power')
if (N < 2):
raise ValueError('N must be at least 2')
m_seq = _create_m_sequence(q, N, check=False)
period = ((q ** N) - 1)
G = AdditiveAbelianGroup([period])
set1 = [i for i in G if (m_seq[i[0]] == 1)]
if check:
H = _get_submodule_of_order(G, (q - 1))
assert is_relative_difference_set(set1, G, H, ((period // (q - 1)), (q - 1), (q ** (N - 1)), (q ** (N - 2))))
if return_group:
return (G, set1)
return set1
|
def relative_difference_set_from_homomorphism(q, N, d, check=True, return_group=False):
'\n Construct `R((q^N-1)/(q-1), n, q^{N-1}, q^{N-2}d)` where `nd = q-1`.\n\n Given a prime power `q`, a number `N \\ge 2` and integers `d` such that `d | q-1` we create the\n relative difference set using the construction from Corollary 5.1.1 of [EB1966]_.\n\n INPUT:\n\n - ``q`` -- a prime power\n - ``N`` -- an integer greater than 1\n - ``d`` -- an integer which divides `q-1`\n - ``check`` -- boolean (default: ``True``); if ``True``, check that the\n result is a relative difference set before returning it\n - ``return_group`` -- boolean (default: ``False``); if ``True``, the function\n will also return the group from which the set is created\n\n OUTPUT:\n\n If ``return_group=False``, the function return only the relative difference\n set. Otherwise, it returns a tuple containing the group and the set.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import relative_difference_set_from_homomorphism\n sage: relative_difference_set_from_homomorphism(7, 2, 3) # random # needs sage.modules sage.rings.finite_rings\n [(0), (3), (4), (2), (13), (7), (14)]\n sage: relative_difference_set_from_homomorphism(9, 2, 4, # random # needs sage.modules sage.rings.finite_rings\n ....: check=False, return_group=True)\n (Additive abelian group isomorphic to Z/80,\n [(0), (4), (6), (13), (7), (12), (15), (8), (9)])\n sage: relative_difference_set_from_homomorphism(9, 2, 5) # needs sage.modules sage.rings.finite_rings\n Traceback (most recent call last):\n ...\n ValueError: q-1 must be a multiple of d\n\n TESTS::\n\n sage: from sage.combinat.designs.difference_family import is_relative_difference_set, _get_submodule_of_order\n sage: q, N, d = 11, 2, 5\n sage: G, D = relative_difference_set_from_homomorphism(q, N, d, check=False, # needs sage.modules sage.rings.finite_rings\n ....: return_group=True)\n sage: H = _get_submodule_of_order(G, (q-1)//d) # needs sage.modules sage.rings.finite_rings\n sage: is_relative_difference_set(D, G, H, # needs sage.modules sage.rings.finite_rings\n ....: ((q**N-1)//(q-1), (q-1)//d, q**(N-1), q**(N-2)*d))\n True\n sage: q, N, d = 9, 2, 4\n sage: G, D = relative_difference_set_from_homomorphism(q, N, d, check=False, # needs sage.modules sage.rings.finite_rings\n ....: return_group=True)\n sage: H = _get_submodule_of_order(G, (q-1)//d) # needs sage.modules sage.rings.finite_rings\n sage: is_relative_difference_set(D, G, H, # needs sage.modules sage.rings.finite_rings\n ....: ((q**N-1)//(q-1), (q-1)//d, q**(N-1), q**(N-2)*d))\n True\n '
from sage.groups.additive_abelian.additive_abelian_group import AdditiveAbelianGroup
if (not is_prime_power(q)):
raise ValueError('q must be a prime power')
if (N < 2):
raise ValueError('N must be at least 2')
if (((q - 1) % d) != 0):
raise ValueError('q-1 must be a multiple of d')
G = AdditiveAbelianGroup([((q ** N) - 1)])
K = _get_submodule_of_order(G, d)
assert (K is not None), 'Could not find kernel'
G2 = (G / K)
theta = G.hom([G2.gen(0)], G2)
diff_set = relative_difference_set_from_m_sequence(q, N, check=False)
second_diff_set = [theta(x) for x in diff_set]
if check:
H = _get_submodule_of_order(G2, ((q - 1) // d))
assert is_relative_difference_set(second_diff_set, G2, H, ((((q ** N) - 1) // (q - 1)), ((q - 1) // d), (q ** (N - 1)), ((q ** (N - 2)) * d)))
if return_group:
return (G2, second_diff_set)
return second_diff_set
|
def is_relative_difference_set(R, G, H, params, verbose=False):
'\n Check if ``R`` is a difference set of ``G`` relative to ``H``, with the given parameters.\n\n This function checks that `G`, `H` and `R` have the orders specified in the parameters, and\n that `R` satisfies the definition of relative difference set (from [EB1966]_): the collection of\n differences `r-s`, `r,s \\in R`, `r \\neq s` contains only elements of `G` which are not in `H`, and contains\n every such element exactly `d` times.\n\n INPUT:\n\n - ``R`` -- list; the relative diffeence set of length `k`\n - ``G`` -- an additive abelian group of order `mn`\n - ``H`` -- list; a submodule of ``G`` of order `n`\n - ``params`` -- a tuple in the form `(m, n, k, d)`\n - ``verbose`` -- boolean (default: ``False``); if ``True``, the function\n will be verbose when the sequences do not satisfy the contraints\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import _get_submodule_of_order, relative_difference_set_from_m_sequence, is_relative_difference_set\n sage: q, N = 5, 2\n sage: params = ((q^N-1) // (q-1), q - 1, q^(N-1), q^(N-2))\n sage: G, R = relative_difference_set_from_m_sequence(q, N, return_group=True) # needs sage.libs.pari sage.modules\n sage: H = _get_submodule_of_order(G, q - 1) # needs sage.libs.pari sage.modules\n sage: is_relative_difference_set(R, G, H, params) # needs sage.libs.pari sage.modules\n True\n\n If we pass the ``verbose`` argument, the function will explain why it failed::\n\n sage: R2 = [G[1], G[2], G[3], G[5], G[6]] # needs sage.libs.pari sage.modules\n sage: is_relative_difference_set(R2, G, H, params, verbose=True) # needs sage.libs.pari sage.modules\n There is a value in the difference set which is not repeated d times\n False\n '
(m, n, k, d) = params
if (G.order() != (m * n)):
if verbose:
print('Incorrect order of G:', G.order())
return False
if (H.order() != n):
if verbose:
print('Incorect order of H:', H.order())
if (len(R) != k):
if verbose:
print('Length of R not correct:', len(R))
return False
diff_set = {}
for el1 in R:
for el2 in R:
if (el1 != el2):
idx = (el1 - el2)
if (idx not in diff_set):
diff_set[idx] = 0
diff_set[idx] += 1
values = [diff_set[x] for x in diff_set]
if ((max(values) != d) or (min(values) != d)):
if verbose:
print('There is a value in the difference set which is not repeated d times')
return False
for el in G:
if ((el in H) and (el in diff_set)):
if verbose:
print('An element of G is present in both the difference set and in H')
return False
if ((el not in H) and (el not in diff_set)):
if verbose:
print('An element of G is not present in either one of H or the difference set')
return False
return True
|
def is_supplementary_difference_set(Ks, v=None, lmbda=None, G=None, verbose=False):
"\n Check that the sets in ``Ks`` are `n-\\{v; k_1, ..., k_n; \\lambda \\}` supplementary\n difference sets over group ``G`` of order ``v``.\n\n From the definition in [Spe1975]_: let `S_1, S_2, ..., S_n` be `n` subsets of a group `G` of order `v`\n such that `|S_i| = k_i`. If, for each `g \\in G`, `g \\neq 0`, the total number of solutions of `a_i - a'_i = g`, with\n `a_i, a'_i \\in S_i` is `\\lambda`, then `S_1, S_2, ..., S_n` are `n-\\{v; k_1, ..., k_n; \\lambda\\}` supplementary difference sets.\n\n One of the parameters ``v`` or ``G`` must always be specified. If ``G`` is not\n given, the function will use an ``AdditiveAbelianGroup`` of order ``v``.\n\n INPUT:\n\n - ``Ks`` -- a list of sets to be checked\n - ``v`` -- integer; the parameter `v` of the supplementary difference sets\n - ``lmbda`` -- integer; the parameter `\\lambda` of the supplementary difference sets\n - ``G`` -- a group of order `v`\n - ``verbose`` -- boolean (default: ``False``); if ``True``, the function will\n be verbose when the sets do not satisfy the contraints\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import supplementary_difference_set_from_rel_diff_set, is_supplementary_difference_set\n sage: G, [S1, S2, S3, S4] = supplementary_difference_set_from_rel_diff_set(17) # needs sage.modules sage.rings.finite_rings\n sage: is_supplementary_difference_set([S1, S2, S3, S4], lmbda=16, G=G) # needs sage.modules sage.rings.finite_rings\n True\n\n The parameter ``v`` can be given instead of ``G``::\n\n sage: is_supplementary_difference_set([S1, S2, S3, S4], v=16, lmbda=16) # needs sage.modules sage.rings.finite_rings\n True\n sage: is_supplementary_difference_set([S1, S2, S3, S4], v=20, lmbda=16) # needs sage.modules sage.rings.finite_rings\n False\n\n If ``verbose=True``, the function will be verbose::\n\n sage: is_supplementary_difference_set([S1, S2, S3, S4], lmbda=14, G=G, # needs sage.modules sage.rings.finite_rings\n ....: verbose=True)\n Number of pairs with difference (1) is 16, but lambda is 14\n False\n\n TESTS::\n\n sage: # needs sage.modules sage.rings.finite_rings\n sage: is_supplementary_difference_set([[1], [1]], lmbda=0, G=Zmod(3))\n True\n sage: is_supplementary_difference_set([S1, S2, S3, S4], v=17, lmbda=16, G=G)\n False\n sage: is_supplementary_difference_set([S1, S2, S3, S4], G=G)\n True\n sage: is_supplementary_difference_set([S1, S2, S3, S4], lmbda=16)\n Traceback (most recent call last):\n ...\n ValueError: one of G or v must be specified\n\n .. SEEALSO::\n\n :func:`supplementary_difference_set_from_rel_diff_set`\n "
if ((G is None) and (v is None)):
raise ValueError('one of G or v must be specified')
if (G is None):
from sage.groups.additive_abelian.additive_abelian_group import AdditiveAbelianGroup
G = AdditiveAbelianGroup([v])
if ((v is not None) and (G.order() != v)):
if verbose:
print(f'G has order {G.order()}, but it should be {v}')
return False
differences_counter = {el: 0 for el in G}
for K in Ks:
for el1 in K:
for el2 in K:
diff = (G(el1) - G(el2))
differences_counter[diff] += 1
for (key, diff) in differences_counter.items():
if (key == 0):
continue
if (lmbda is None):
lmbda = diff
if (diff != lmbda):
if verbose:
print(f'Number of pairs with difference {key} is {diff}, but lambda is {lmbda}')
return False
return True
|
def supplementary_difference_set_from_rel_diff_set(q, existence=False, check=True):
'\n Construct `4-\\{2v; v, v+1, v, v; 2v\\}` supplementary difference sets where `q=2v+1`.\n\n The sets are created from relative difference sets as detailed in Theorem 3.3 of [Spe1975]_. this construction\n requires that `q` is an odd prime power and that there exists `s \\ge 0` such that `(q-(2^{s+1}+1))/2^{s+1}` is\n an odd prime power.\n\n Note that the construction from [Spe1975]_ states that the resulting sets are `4-\\{2v; v+1, v, v, v; 2v\\}`\n supplementary difference sets. However, the implementation of that construction returns\n `4-\\{2v; v, v+1, v, v; 2v\\}` supplementary difference sets. This is not important, since the supplementary\n difference sets are not ordered.\n\n INPUT:\n\n - ``q`` -- an odd prime power\n - ``existence`` -- boolean (default: ``False``); If ``True``, only check\n whether the supplementary difference sets can be constructed\n - ``check`` -- boolean (default: ``True``); If ``True``, check that the sets\n are supplementary difference sets before returning them\n\n OUTPUT:\n\n If ``existence=False``, the function returns the 4 sets (containing integers),\n or raises an error if ``q`` does not satify the constraints.\n If ``existence=True``, the function returns a boolean representing whether\n supplementary difference sets can be constructed.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import supplementary_difference_set_from_rel_diff_set\n sage: supplementary_difference_set_from_rel_diff_set(17) #random # needs sage.libs.pari\n (Additive abelian group isomorphic to Z/16,\n [[(1), (5), (6), (7), (9), (13), (14), (15)],\n [(0), (2), (3), (5), (6), (10), (11), (13), (14)],\n [(0), (1), (2), (3), (5), (6), (7), (12)],\n [(0), (2), (3), (5), (6), (7), (9), (12)]])\n\n If ``existence=True``, the function returns a boolean::\n\n sage: supplementary_difference_set_from_rel_diff_set(7, existence=True)\n False\n sage: supplementary_difference_set_from_rel_diff_set(17, existence=True)\n True\n\n TESTS::\n\n sage: # needs sage.libs.pari\n sage: from sage.combinat.designs.difference_family import is_supplementary_difference_set\n sage: G, sets = supplementary_difference_set_from_rel_diff_set(17, check=False)\n sage: is_supplementary_difference_set(sets, lmbda=16, G=G)\n True\n sage: G, sets = supplementary_difference_set_from_rel_diff_set(9, check=False)\n sage: is_supplementary_difference_set(sets, lmbda=8, G=G)\n True\n sage: supplementary_difference_set_from_rel_diff_set(7)\n Traceback (most recent call last):\n ...\n ValueError: There is no s for which m-1 is an odd prime power\n sage: supplementary_difference_set_from_rel_diff_set(8)\n Traceback (most recent call last):\n ...\n ValueError: q must be an odd prime power\n sage: supplementary_difference_set_from_rel_diff_set(8, existence=True)\n False\n sage: supplementary_difference_set_from_rel_diff_set(7, existence=True)\n False\n sage: supplementary_difference_set_from_rel_diff_set(1, existence=True)\n False\n\n Check that the function works even when s > 1::\n\n sage: G, sets = supplementary_difference_set_from_rel_diff_set(353, check=False) # long time, needs sage.libs.pari\n sage: is_supplementary_difference_set(sets, lmbda=352, G=G) # long time, needs sage.libs.pari\n True\n\n .. SEEALSO::\n\n :func:`is_supplementary_difference_set`\n '
s = 0
m = (- 1)
while ((q > (2 ** (s + 1))) and (((q - 1) % (2 ** (s + 1))) == 0)):
prime_pow = (((q - 1) // (2 ** (s + 1))) - 1)
if (is_prime_power(prime_pow) and ((prime_pow % 2) == 1)):
m = (((q - ((2 ** (s + 1)) + 1)) // (2 ** (s + 1))) + 1)
break
s += 1
if existence:
return (is_prime_power(q) and ((q % 2) == 1) and (m != (- 1)))
if ((not is_prime_power(q)) or ((q % 2) != 1)):
raise ValueError('q must be an odd prime power')
if (m == (- 1)):
raise ValueError('There is no s for which m-1 is an odd prime power')
set1 = relative_difference_set_from_homomorphism((m - 1), 2, ((m - 2) // 2), check=False)
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
P = PolynomialRing(ZZ, 'x')
hall = 0
for d in set1:
hall += P.monomial(d[0])
def get_T(k):
T = (P.monomial(0) - 1)
for i in range(k):
T += P.monomial(i)
return T
modulo = (P.monomial((2 * m)) - 1)
diff = (get_T((2 * m)) - ((1 + P.monomial(m)) * hall))
diff = diff.mod(modulo)
(exp1, exp2) = diff.exponents()
a = (((exp1 + exp2) - m) // 2)
psi3 = (P.monomial(a) + hall).mod(modulo)
psi4 = (P.monomial((a + m)) + hall).mod(modulo)
for i in range(s):
m_start = ((2 ** i) * m)
(psi3, psi4) = ((psi3(P.monomial(2)) + (P.monomial(1) * psi4(P.monomial(2)))).mod((P.monomial((4 * m_start)) - 1)), (psi3(P.monomial(2)) + (P.monomial(1) * (get_T((2 * m_start))(P.monomial(2)) - psi4(P.monomial(2))))).mod((P.monomial((4 * m_start)) - 1)))
(G2, set2) = relative_difference_set_from_m_sequence(q, 2, check=False, return_group=True)
s3 = get_fixed_relative_difference_set(G2, set2)
phi_exps = []
for i in range(len(s3)):
for j in range((i + 1), len(s3)):
diff = (s3[i] - s3[j])
if (((diff % (q - 1)) == 0) and ((diff % ((q ** 2) - 1)) != 0)):
phi_exps.append(s3[i])
exps1 = [((x + 1) // 2) for x in phi_exps if ((x % 2) == 1)]
exps2 = [(x // 2) for x in phi_exps if ((x % 2) == 0)]
theta1 = 0
for exp in exps1:
theta1 += P.monomial(exp)
theta1 = theta1.mod((P.monomial((q - 1)) - 1))
theta2 = 0
for exp in exps2:
theta2 += P.monomial(exp)
theta2 = theta2.mod((P.monomial((q - 1)) - 1))
psi1 = ((1 + P.monomial(((q - 1) // 2))) * theta1).mod((P.monomial((q - 1)) - 1))
psi2 = (1 + ((1 + P.monomial(((q - 1) // 2))) * theta2)).mod((P.monomial((q - 1)) - 1))
from sage.groups.additive_abelian.additive_abelian_group import AdditiveAbelianGroup
G = AdditiveAbelianGroup([(q - 1)])
K1 = [G[x] for x in psi1.exponents()]
K2 = [G[x] for x in psi2.exponents()]
K3 = [G[x] for x in psi3.exponents()]
K4 = [G[x] for x in psi4.exponents()]
if check:
assert is_supplementary_difference_set([K1, K2, K3, K4], lmbda=(q - 1), G=G)
return (G, [K1, K2, K3, K4])
|
def supplementary_difference_set(q, existence=False, check=True):
'\n Construct `4-\\{2v; v, v+1, v, v; 2v\\}` supplementary difference sets where `q=2v+1`.\n\n This is a deprecated version of :func:`supplementary_difference_set_from_rel_diff_set`,\n please use that instead.\n '
from sage.misc.superseded import deprecation
deprecation(35211, 'This function is deprecated, please use supplementary_difference_set_from_rel_diff_set instead.')
if existence:
return supplementary_difference_set_from_rel_diff_set(q, existence=True)
(_, s) = supplementary_difference_set_from_rel_diff_set(q, check=check)
return s
|
def get_fixed_relative_difference_set(G, rel_diff_set, as_elements=False):
"\n Construct an equivalent relative difference set fixed by the size of the set.\n\n Given a relative difference set `R(q+1, q-1, q, 1)`, it is possible to find a translation\n of this set fixed by `q` (see Section 3 of [Spe1975]_). We say that a set is fixed by `t` if\n `\\{td | d\\in R\\}= R`.\n\n In addition, the set returned by this function will contain the element `0`. This is needed in the\n construction of supplementary difference sets (see :func:`supplementary_difference_set_from_rel_diff_set`).\n\n INPUT:\n\n - ``G`` -- a group, of which ``rel_diff_set`` is a subset\n - ``rel_diff_set`` -- the relative difference set\n - ``as_elements`` -- boolean (default: ``False``); if ``True``, the list\n returned will contain elements of the abelian group (this may slow down\n the computation considerably)\n\n OUTPUT:\n\n By default, this function returns the set as a list of integers. However, if\n ``as_elements=True`` it will return the set as a list containing elements of\n the abelian group.\n If no such set can be found, the function will raise an error.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import relative_difference_set_from_m_sequence, get_fixed_relative_difference_set\n sage: G, s1 = relative_difference_set_from_m_sequence(5, 2, return_group=True) # needs sage.libs.pari sage.modules\n sage: get_fixed_relative_difference_set(G, s1) # random # needs sage.libs.pari sage.modules\n [2, 10, 19, 23, 0]\n\n If ``as_elements=True``, the result will contain elements of the group::\n\n sage: get_fixed_relative_difference_set(G, s1, as_elements=True) # random # needs sage.libs.pari sage.modules\n [(2), (10), (19), (23), (0)]\n\n TESTS::\n\n sage: # needs sage.libs.pari sage.modules\n sage: from sage.combinat.designs.difference_family import is_fixed_relative_difference_set\n sage: G, s1 = relative_difference_set_from_m_sequence(5, 2, return_group=True)\n sage: s2 = get_fixed_relative_difference_set(G, s1, as_elements=True)\n sage: is_fixed_relative_difference_set(s2, len(s2))\n True\n sage: G, s1 = relative_difference_set_from_m_sequence(9, 2, return_group=True)\n sage: s2 = get_fixed_relative_difference_set(G, s1, as_elements=True)\n sage: is_fixed_relative_difference_set(s2, len(s2))\n True\n sage: type(s2[0])\n <class 'sage.groups.additive_abelian.additive_abelian_group.AdditiveAbelianGroup_fixed_gens_with_category.element_class'>\n sage: s2 = get_fixed_relative_difference_set(G, s1)\n sage: type(s2[0])\n <class 'sage.rings.integer.Integer'>\n "
q = len(rel_diff_set)
s2 = None
for el in G:
fixed_set = [(el + x) for x in rel_diff_set]
if is_fixed_relative_difference_set(fixed_set, q):
s2 = fixed_set
break
assert (s2 is not None), 'Cannot find fixed translation of the set'
s3 = None
for i in range(G.order()):
temp = [((((q + 1) * i) + x[0]) % G.order()) for x in s2]
if (0 in temp):
s3 = temp
break
assert (s3 is not None), 'Cannot find fixed set containing 0'
if as_elements:
return [G[x] for x in s3]
return s3
|
def is_fixed_relative_difference_set(R, q):
'\n Check if the relative difference set ``R`` is fixed by ``q``.\n\n A relative difference set `R` is fixed by `q` if `\\{qd | d \\in R\\}= R` (see Section 3 of [Spe1975]_).\n\n INPUT:\n\n - ``R`` -- a list containing elements of an abelian group; the relative\n difference set\n - ``q`` -- an integer\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: from sage.combinat.designs.difference_family import relative_difference_set_from_m_sequence, get_fixed_relative_difference_set, is_fixed_relative_difference_set\n sage: G, s1 = relative_difference_set_from_m_sequence(7, 2, return_group=True) # needs sage.libs.pari\n sage: s2 = get_fixed_relative_difference_set(G, s1, as_elements=True) # needs sage.libs.pari\n sage: is_fixed_relative_difference_set(s2, len(s2)) # needs sage.libs.pari\n True\n sage: G = AdditiveAbelianGroup([15])\n sage: s3 = [G[1], G[2], G[3], G[4]]\n sage: is_fixed_relative_difference_set(s3, len(s3))\n False\n\n If the relative difference set does not contain elements of the group, the method returns false::\n\n sage: G, s1 = relative_difference_set_from_m_sequence(7, 2, return_group=True) # needs sage.libs.pari sage.modules\n sage: s2 = get_fixed_relative_difference_set(G, s1, as_elements=False) # needs sage.libs.pari sage.modules\n sage: is_fixed_relative_difference_set(s2, len(s2)) # needs sage.libs.pari sage.modules\n False\n '
for el in R:
if ((q * el) not in R):
return False
return True
|
def skew_supplementary_difference_set_over_polynomial_ring(n, existence=False, check=True):
'\n Construct skew supplementary difference sets over a polynomial ring of order ``n``.\n\n The skew supplementary difference sets for `n=81, 169` are taken from [Djo1994a]_.\n\n INPUT:\n\n - ``n`` -- integer; the parameter of the supplementary difference sets\n - ``existence`` -- boolean (default: ``False``); if ``True``, only check\n whether the supplementary difference sets can be constructed\n - ``check`` -- boolean (default: ``True``); if ``True``, check that the sets\n are supplementary difference sets with `S_1` skew before returning them;\n setting this parameter to ``False`` may speed up the computation considerably\n\n OUTPUT:\n\n If ``existence=False``, the function returns a Polynomial Ring of order ``n``\n and a list containing 4 sets, or raises an error if data for the given ``n``\n is not available.\n If ``existence=True``, the function returns a boolean representing whether\n skew supplementary difference sets can be constructed.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import skew_supplementary_difference_set_over_polynomial_ring\n sage: G, [S1, S2, S3, S4] = skew_supplementary_difference_set_over_polynomial_ring(81) # needs sage.libs.pari\n\n If ``existence=True``, the function returns a boolean::\n\n sage: skew_supplementary_difference_set_over_polynomial_ring(81, existence=True)\n True\n sage: skew_supplementary_difference_set_over_polynomial_ring(17, existence=True)\n False\n\n TESTS::\n\n sage: skew_supplementary_difference_set_over_polynomial_ring(7)\n Traceback (most recent call last):\n ...\n NotImplementedError: skew SDS of order 7 not yet implemented\n '
data = {81: (3, (lambda x: (((x ** 4) - (x ** 3)) - 1)), 16, 5, [1, 2, 4, 6, 8, 10, 12, 14], [1, 2, 3, 4, 10, 11, 13], [4, 5, 6, 8, 12, 13, 14], [2, 4, 5, 6, 7, 11, 12, 13, 15]), 169: (13, (lambda x: (((x ** 2) - (4 * x)) + 6)), 24, 7, [0, 2, 5, 7, 9, 10, 12, 15, 16, 18, 21, 22], [0, 1, 2, 7, 8, 9, 13, 14, 18, 20, 23], [1, 4, 6, 7, 9, 14, 16, 17, 20, 21, 23], [3, 5, 6, 9, 10, 12, 13, 14, 15, 17, 20])}
if existence:
return (n in data)
if (n not in data):
raise NotImplementedError(f'skew SDS of order {n} not yet implemented')
(mod, poly, exp, order, ind1, ind2, ind3, ind4) = data[n]
from sage.rings.finite_rings.integer_mod_ring import Zmod
Z3 = Zmod(mod)
R = ZZ['x']
x = R.gen()
F = Z3.extension(poly(x))
H = [(F.gen() ** (exp * i)) for i in range(order)]
cosets = []
for i in range(((n - 1) // (2 * order))):
cosets.append([((F.gen() ** i) * el) for el in H])
cosets.append([((- (F.gen() ** i)) * el) for el in H])
def generate_set(index_set, cosets):
return sum((cosets[idx] for idx in index_set), [])
S1 = generate_set(ind1, cosets)
S2 = generate_set(ind2, cosets)
S3 = generate_set(ind3, cosets)
S4 = generate_set(ind4, cosets)
if check:
lmbda = ((((len(S1) + len(S2)) + len(S3)) + len(S4)) - n)
assert is_supplementary_difference_set([S1, S2, S3, S4], lmbda=lmbda, G=F)
assert _is_skew_set(F, S1)
return (F, [S1, S2, S3, S4])
|
def skew_supplementary_difference_set_with_paley_todd(n, existence=False, check=True):
'\n Construct `4-\\{n; n_1, n_2, n_3, n_4; \\lambda\\}` skew supplementary difference sets where `S_1` is the Paley-Todd difference set.\n\n The skew SDS returned have the property that `n_1 + n_2 + n_3 + n_4 = n + \\lambda`.\n\n This construction is described in [DK2016]_. The function contains, for each\n value of `n`, a set `H` containing integers modulo `n`, and four sets `J, K, L`.\n Then, these are used to construct `(n; k_2, k_3, k_4; \\lambda_2)` difference family,\n with `\\lambda_2 = k_2 + k_3 + k_4 + (3n - 1) / 4`. Finally, these sets together\n with the Paley-Todd difference set form a skew supplementary difference set.\n\n INPUT:\n\n - ``n`` -- integer; the parameter of the supplementary difference set\n - ``existence`` -- boolean (default: ``False``); if ``True``, only check\n whether the supplementary difference sets can be constructed\n - ``check`` -- boolean (default: ``True``); if ``True``, check that the sets\n are supplementary difference sets with `S_1` skew before returning them;\n setting this parameter to ``False`` may speed up the computation considerably\n\n OUTPUT:\n\n If ``existence=False``, the function returns the group G of integers modulo\n ``n`` and a list containing 4 sets, or raises an error if data for the given\n ``n`` is not available.\n If ``existence=True``, the function returns a boolean representing whether\n skew supplementary difference sets can be constructed.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import skew_supplementary_difference_set_with_paley_todd\n sage: G, [S1, S2, S3, S4] = skew_supplementary_difference_set_with_paley_todd(239)\n\n If existence is ``True``, the function returns a boolean::\n\n sage: skew_supplementary_difference_set_with_paley_todd(239, existence=True)\n True\n sage: skew_supplementary_difference_set_with_paley_todd(17, existence=True)\n False\n\n TESTS::\n\n sage: skew_supplementary_difference_set_with_paley_todd(7)\n Traceback (most recent call last):\n ...\n NotImplementedError: data for skew SDS of order 7 not yet implemented\n '
H_db = {239: [1, 10, 24, 44, 98, 100, 201]}
indices = {239: [[1, 3, 5, 6, 15, 17, 19, 28, 34, 38, 39, 57, 58, 63, 85, 95, 107], [1, 3, 4, 5, 15, 16, 17, 18, 19, 21, 23, 29, 35, 45, 58, 63], [0, 1, 4, 6, 7, 8, 13, 16, 18, 34, 35, 45, 47, 58, 63, 95]]}
if existence:
return (n in H_db)
if (n not in H_db):
raise NotImplementedError(f'data for skew SDS of order {n} not yet implemented')
G = Zmod(n)
H = {G(el) for el in H_db[n]}
def generate_subset(indices, H):
return list({(el * idx) for el in H for idx in indices})
from sage.arith.misc import quadratic_residues
S1 = [G(el) for el in quadratic_residues(n) if (el != 0)]
S2 = generate_subset(indices[n][0], H)
S3 = generate_subset(indices[n][1], H)
S4 = generate_subset(indices[n][2], H)
if check:
lmbda = ((((len(S1) + len(S2)) + len(S3)) + len(S4)) - n)
assert is_supplementary_difference_set([S1, S2, S3, S4], lmbda=lmbda, G=G)
assert _is_skew_set(G, S1)
return (G, [S1, S2, S3, S4])
|
def skew_supplementary_difference_set(n, existence=False, check=True, return_group=False):
'\n Construct `4-\\{n; n_1, n_2, n_3, n_4; \\lambda\\}` supplementary difference sets,\n where `S_1` is skew and `n_1 + n_2 + n_3 + n_4 = n+\\lambda`.\n\n These sets are constructed from available data, as described in [Djo1994a]_. The set `S_1 \\subset G` is\n always skew, i.e. `S_1 \\cap (-S_1) = \\emptyset` and `S_1 \\cup (-S_1) = G \\setminus \\{0\\}`.\n\n The data is taken from:\n\n * `n = 103, 151`: [Djo1994a]_\n * `n = 67, 113, 127, 157, 163, 181, 241`: [Djo1992a]_\n * `n = 37, 43`: [Djo1992b]_\n * `n = 39, 49, 65, 93, 121, 129, 133, 217, 219, 267`: [Djo1992c]_\n * `n = 97`: [Djo2008a]_\n * `n = 109, 145, 247`: [Djo2008b]_\n * `n = 73`: [Djo2023b]_\n * `n = 213, 631`: [DGK2014]_\n * `n = 331`: [DK2016]_\n\n Additional skew Supplementary difference sets are built using the function\n :func:`skew_supplementary_difference_set_over_polynomial_ring`, and\n :func:`skew_supplementary_difference_set_with_paley_todd`.\n\n INPUT:\n\n - ``n`` -- integer; the parameter of the supplementary difference set\n - ``existence`` -- boolean (default: ``False``); if ``True``, only check\n whether the supplementary difference sets can be constructed\n - ``check`` -- boolean (default: ``True``); if ``True``, check that the sets\n are supplementary difference sets with `S_1` skew before returning them;\n setting this parameter to ``False`` may speed up the computation considerably\n - ``return_group`` -- boolean (default: ``False``); if ``True``, the function\n will also return the group from which the sets are created\n\n OUTPUT:\n\n If ``existence=False``, the function returns a list containing 4 sets,\n or raises an error if data for the given ``n`` is not available. If\n ``return_group=True`` the function will additionally return the group from\n which the sets are created.\n If ``existence=True``, the function returns a boolean representing whether\n skew supplementary difference sets can be constructed.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import skew_supplementary_difference_set\n sage: [S1, S2, S3, S4] = skew_supplementary_difference_set(39)\n\n If ``return_group=True``, the function will also return the group::\n\n sage: G, [S1, S2, S3, S4] = skew_supplementary_difference_set(103, return_group=True)\n\n If ``existence=True``, the function returns a boolean::\n\n sage: skew_supplementary_difference_set(103, existence=True)\n True\n sage: skew_supplementary_difference_set(17, existence=True)\n False\n\n TESTS::\n\n sage: from sage.combinat.designs.difference_family import is_supplementary_difference_set, _is_skew_set\n sage: G, [S1, S2, S3, S4] = skew_supplementary_difference_set(113, check=False, return_group=True)\n sage: is_supplementary_difference_set([S1, S2, S3, S4], lmbda=len(S1)+len(S2)+len(S3)+len(S4)-113, G=G)\n True\n sage: _is_skew_set(G, S1)\n True\n sage: G, [S1, S2, S3, S4] = skew_supplementary_difference_set(67, check=False, return_group=True)\n sage: is_supplementary_difference_set([S1, S2, S3, S4], lmbda=len(S1)+len(S2)+len(S3)+len(S4)-67, G=G)\n True\n sage: _is_skew_set(G, S1)\n True\n sage: skew_supplementary_difference_set(7)\n Traceback (most recent call last):\n ...\n ValueError: Skew SDS of order 7 not yet implemented.\n sage: skew_supplementary_difference_set(7, existence=True)\n False\n sage: skew_supplementary_difference_set(127, existence=True)\n True\n sage: skew_supplementary_difference_set(81, existence=True)\n True\n\n .. NOTE::\n\n The data for `n=247` in [Djo2008b]_ contains a typo: the set `\\alpha_2` should contain `223` instead of `233`.\n This can be verified by checking the resulting sets, which are given explicitly in the paper.\n '
indices = {37: [[0, 3, 5, 7, 9, 10], [0, 5, 6, 7, 8], [1, 2, 6, 7, 9], [2, 6, 8, 9, 10]], 39: [[1, 3, 5, 6, 8, 10, 12], [0, 1, 5, 8, 12, 13], [1, 3, 4, 7, 9, 12, 13], [0, 1, 2, 3, 7, 8]], 43: [[1, 2, 4], [1, 2, 4], [0, 2, 3], [3, 4, (- 1)]], 49: [[1, 2, 5, 7, 8, 10, 13, 14], [4, 5, 6, 7, 10, 11], [0, 1, 2, 4, 6, 7, 12, 14], [1, 2, 3, 5, 6, 10, 12, 13, 14]], 65: [[1, 3, 5, 6, 8, 10, 13, 14, 17, 18, 20, 22], [0, 3, 7, 10, 16, 17, 18, 20, 21], [2, 4, 6, 8, 9, 10, 14, 15, 16, 17, 18, 20], [5, 7, 8, 9, 11, 12, 13, 14, 16, 18, 19, 20, 21]], 67: [[0, 3, 5, 6, 9, 10, 13, 14, 17, 18, 20], [0, 2, 4, 9, 11, 12, 13, 16, 19, 21], [1, 3, 6, 10, 11, 13, 14, 16, 20, 21], [2, 4, 6, 8, 9, 11, 14, 17, 19]], 73: [[4, 6, 8, 14], [8, 10, 12, 14], [4, 6, 10, 12], [(- 1), 0, 2, 10]], 93: [[0, 3, 4, 6, 9, 10, 12, 14, 17, 18], [2, 3, 4, 5, 9, 13, 15, 18, 19], [1, 2, 3, 4, 5, 6, 7, 8, 16], [1, 4, 6, 11, 12, 13, 15, 16, 17, 18]], 97: [[1, 2, 4, 6, 9, 11, 13, 14, 17, 18, 21, 23, 25, 27, 29, 30], [1, 2, 6, 7, 8, 9, 10, 11, 12, 13, 23, 27, 29], [0, 1, 2, 5, 6, 12, 13, 15, 16, 20, 24, 25, 26, 29, 30, 31], [0, 2, 3, 4, 7, 8, 9, 11, 12, 13, 15, 16, 17, 18, 23, 28, 29]], 103: [[1, 3, 4, 6, 8, 11, 12, 14, 17, 18, 20, 22, 25, 27, 28, 30, 32], [2, 9, 10, 12, 13, 14, 15, 16, 20, 21, 22, 23, 24, 26, 28, 29, 30], [0, 1, 2, 3, 4, 11, 12, 13, 16, 17, 19, 20, 21, 24, 25, 26, 28, 30, 31], [0, 1, 2, 3, 4, 5, 6, 13, 15, 18, 19, 20, 23, 24, 25, 26, 27, 28, 29, 31]], 109: [[0, 2, 5, 7, 8, 10, 12, 15, 16, 19, 20, 23, 24, 26, 29, 30, 33, 34], [4, 5, 6, 7, 11, 15, 18, 19, 20, 22, 25, 30, 32, 33, 35], [0, 1, 5, 6, 9, 10, 11, 14, 17, 20, 24, 26, 27, 28, 29, 31, 32], [0, 3, 4, 6, 7, 9, 10, 12, 13, 22, 24, 25, 26, 27, 28, 29, 31, 33, 35]], 113: [[0, 3, 4, 6, 8, 10, 13, 14], [1, 3, 8, 9, 10, 11, 12, 13], [0, 2, 3, 5, 6, 7, 12], [1, 2, 3, 5, 8, 9, 15]], 121: [[0, 2, 4, 7, 8, 11, 13, 14, 16, 19, 20, 22], [0, 1, 4, 5, 8, 9, 10, 15, 17, 20, 23], [1, 2, 3, 7, 9, 16, 18, 19, 20, 21, 22, 23], [0, 2, 9, 10, 11, 12, 13, 14, 15, 17, 18, 21, 22, 23]], 127: [[0, 3, 5, 7, 8, 10, 12, 14, 16], [0, 1, 3, 6, 7, 9, 10, 12, 14, 15], [0, 1, 3, 4, 5, 7, 8, 9, 15, 16], [1, 4, 5, 6, 9, 10, 13, 14, 15, 16]], 129: [[1, 2, 4, 7, 9, 11, 12, 14, 16, 18], [0, 1, 2, 3, 9, 11, 14, 15, 19], [0, 1, 3, 6, 8, 10, 12, 16, 18, 19], [0, 3, 7, 8, 9, 10, 12, 14, 15, 17]], 133: [[1, 2, 5, 6, 9, 11, 12, 14], [1, 4, 7, 9, 10, 12, 13, 15], [0, 5, 6, 8, 11, 12, 13, 15], [0, 1, 2, 5, 7, 8, 9, 13, 14, 15]], 145: [[1, 2, 4, 7, 9, 10, 13, 14, 16, 19, 20, 22], [0, 2, 4, 7, 10, 11, 14, 18, 19, 20, 21, 22], [1, 3, 6, 9, 12, 13, 14, 17, 19, 20, 21, 22, 23], [2, 3, 5, 6, 7, 9, 12, 13, 15, 16, 19, 20, 21, 22, 23]], 151: [[0, 3, 5, 6, 8, 11, 13, 14, 16, 19, 21, 23, 25, 27, 28], [2, 3, 6, 13, 16, 17, 20, 23, 25, 26, 27, 28, 29], [0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 23, 24, 27, 28], [1, 4, 5, 10, 11, 12, 13, 14, 16, 18, 19, 22, 25, 26, 27, 28]], 157: [[0, 2, 5, 7, 8, 11], [0, 4, 5, 6, 9, 11], [6, 7, 8, 9, 10, 11], [0, 5, 6, 7, 8, 10, 11]], 163: [[0, 2, 5, 6, 9, 10, 13, 14, 17], [0, 1, 7, 10, 12, 15, 16, 17], [0, 1, 3, 5, 8, 13, 15, 16, 17], [3, 6, 7, 8, 11, 12, 13, 14, 16, 17]], 181: [[0, 3, 5, 6, 8, 10, 13, 15, 16, 19], [4, 5, 7, 8, 11, 14, 15, 16, 18, 19], [0, 4, 10, 11, 13, 15, 16, 18, 19], [2, 4, 5, 7, 11, 13, 15, 17, 19]], 213: [[1, 2, 5, 6, 9, 11, 12, 14, 16, 19, 20, 23, 24, 26, 29, 30], [3, 6, 8, 12, 13, 14, 15, 17, 20, 22, 23, 25, 26, 27, 28, 31], [2, 3, 5, 7, 9, 13, 16, 17, 19, 21, 23, 24, 27, 28, 29], [0, 5, 6, 9, 11, 13, 14, 17, 20, 22, 23, 26, 29, 31]], 217: [[0, 3, 5, 7, 8, 11, 12, 14], [1, 3, 4, 7, 9, 11, 12, 15], [3, 4, 5, 6, 7, 9, 10, 14, 15], [1, 3, 4, 5, 7, 8, 11, 13, 14]], 219: [[1, 3, 5, 6, 8, 11, 12, 15, 17, 18, 21, 22, 24], [2, 6, 8, 10, 11, 12, 13, 16, 19, 22, 23, 24], [0, 1, 5, 6, 10, 11, 13, 14, 17, 20, 21, 24, 25], [0, 2, 3, 4, 5, 6, 7, 11, 12, 13, 16, 20, 23]], 241: [[0, 2, 4, 6, 8, 11, 12, 14], [1, 3, 4, 6, 7, 13, 14, 15], [6, 8, 9, 10, 12, 13, 14, 15], [3, 4, 5, 9, 10, 13, 14]], 247: [[0, 2, 4, 7, 8, 10, 12, 15, 16, 18, 20, 23, 25, 27, 29], [0, 2, 7, 9, 11, 12, 14, 15, 16, 18, 20, 22, 26], [2, 3, 4, 12, 13, 14, 15, 16, 18, 20, 23, 24, 26, 27, 29], [0, 3, 4, 6, 10, 11, 12, 14, 18, 19, 20, 22, 25, 29]], 267: [[0, 3, 4, 7, 8, 11, 13, 15, 16, 19, 21, 22, 25], [0, 1, 4, 5, 6, 8, 14, 15, 18, 21, 23], [0, 2, 4, 5, 7, 9, 10, 11, 14, 15, 16, 17, 25], [0, 1, 3, 4, 6, 14, 15, 16, 17, 18, 20, 22, 23, 25]], 331: [[1, 2, 4, 7, 9, 10, 12, 15, 16, 18, 21, 22, 24, 26, 28], [(- 1), 0, 2, 6, 9, 11, 12, 14, 15, 17, 20, 21, 24, 25, 28], [(- 1), 0, 1, 5, 6, 7, 8, 9, 10, 12, 15, 18, 23, 28, 29], [(- 1), 0, 3, 7, 8, 10, 11, 12, 14, 16, 19, 20, 21, 26, 29]], 631: [[0, 2, 4, 6, 9, 10, 12, 15, 16, 18, 20, 23, 24, 26, 29, 30, 32, 35, 36, 38, 40], [0, 1, 2, 4, 6, 8, 9, 10, 11, 12, 13, 14, 16, 20, 23, 28, 29, 30, 32, 36, 38, 41], [0, 2, 3, 4, 6, 9, 10, 12, 14, 15, 16, 17, 18, 19, 20, 22, 24, 25, 26, 29, 34, 40], [0, 2, 4, 5, 6, 7, 8, 10, 15, 16, 18, 22, 23, 24, 26, 30, 31, 33, 35, 36, 37, 38]]}
cosets_gens = {37: [1, 2, 3, 5, 6, 9], 39: [1, 2, 3, 4, 6, 8, [13]], 43: [1, 3, 7], 49: [1, 2, 3, 4, 6, 7, 9, 12], 65: [1, 2, 3, 5, 6, 7, 9, 10, 11, [13], 22, [26]], 67: [1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 17], 73: [1, 3, 5, 9, 11, 13, 17, 25], 93: [1, 2, 3, 5, 7, 9, 10, 14, 15, [31]], 97: [1, 2, 3, 4, 5, 6, 7, 9, 10, 12, 13, 15, 18, 20, 23, 26], 103: [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 15, 17, 19, 21, 23, 30], 109: [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 13, 15, 16, 18, 20, 23, 25, 30], 113: [1, 2, 3, 5, 6, 9, 10, 13], 121: [1, 2, 4, 5, 7, 8, 10, 11, 16, 17, 19, 20], 127: [1, 3, 5, 7, 9, 11, 13, 19, 21], 129: [1, 3, 5, 7, 9, 11, 13, 19, 21, [43]], 133: [1, 2, 3, 6, 7, 9, 18, [19, 38, 76]], 145: [1, [2, 17, 32, 72, 77, 127, 137], [3, 43, 48, 98, 108, 118, 133], [6, 51, 71, 86, 91, 96, 121], [7, 52, 82, 107, 112, 117, 132], [11, 21, 31, 46, 61, 101, 106], [14, 19, 69, 79, 89, 104, 119], [22, 42, 57, 62, 67, 92, 122], [5, 35, 80, 100, 115, 120, 125], [10, 15, 55, 70, 85, 95, 105], [29], [58]], 151: [1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 15, 22, 27, 29, 30], 157: [1, 2, 3, 5, 9, 15], 163: [1, 2, 3, 5, 6, 9, 10, 15, 18], 181: [1, 2, 3, 4, 6, 7, 8, 12, 13, 24], 213: [1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 15, 20, 22, 30, 43, 71], 217: [1, 2, 4, 5, 7, 10, 19, [31, 62, 124]], 219: [1, 2, 3, 5, 7, 9, 11, 15, 19, 22, 23, 33, [73]], 241: [1, 2, 4, 5, 7, 13, 19, 35], 247: [1, [2, 18, 31, 32, 41, 110, 122, 162, 223], [3, 27, 48, 165, 170, 183, 185, 211, 243], [5, 28, 45, 58, 80, 158, 187, 201, 226], [6, 54, 83, 93, 96, 119, 123, 175, 239], [7, 20, 63, 73, 112, 138, 163, 180, 232], [10, 56, 69, 90, 116, 127, 155, 160, 205], [11, 47, 99, 102, 111, 115, 150, 176, 177], [13, 52, 65, 78, 91, 117, 143, 208, 221], [14, 29, 40, 79, 113, 126, 146, 217, 224], [17, 25, 43, 49, 140, 142, 153, 194, 225], [19, 57, 171], [33, 34, 37, 50, 59, 86, 98, 141, 203], [35, 66, 68, 74, 100, 118, 159, 172, 196], [38, 95, 114]], 267: [1, 2, 3, 5, 7, 9, 10, 13, 14, 15, 19, 39, [89]], 331: [1, 2, 4, 5, 7, 8, 10, 13, 14, 16, 19, 20, 28, 32, 56], 631: [1, 2, 3, 4, 5, 6, 7, 9, 12, 14, 17, 18, 19, 21, 23, 27, 31, 35, 38, 42, 62]}
H_db = {37: [1, 10, (- 11)], 39: [1, 16, 22], 43: [1, 4, 11, 16, 21, (- 2), (- 8)], 49: [1, 18, 30], 65: [1, 16, 61], 67: [1, 29, 37], 73: [1, 2, 4, 8, 16, 32, 64, 55, 37], 93: [1, 4, 16, 64, 70], 97: [1, 35, 61], 103: [1, 46, 56], 109: [1, 45, 63], 113: [1, 16, 28, 30, 49, 106, 109], 121: [1, 3, 9, 27, 81], 127: [1, 2, 4, 8, 16, 32, 64], 129: [1, 4, 16, 64, 97, 121, 127], 133: [1, 4, 16, 25, 64, 93, 100, 106, 123], 145: [1, 16, 36, 81, 111, 136, 141], 151: [1, 8, 19, 59, 64], 157: [1, 14, 16, 39, 46, 67, 75, 93, 99, 101, 108, 130, 153], 163: [1, 38, 40, 53, 58, 85, 104, 133, 140], 181: [1, 39, 43, 48, 62, 65, 73, 80, 132], 213: [1, 37, 91, 103, 172, 187, 190], 217: [1, 8, 9, 25, 51, 64, 72, 78, 81, 142, 190, 191, 193, 200, 214], 219: [1, 4, 16, 37, 55, 64, 148, 154, 178], 241: [1, 15, 24, 54, 87, 91, 94, 98, 100, 119, 160, 183, 205, 225, 231], 247: [1, 9, 16, 55, 61, 81, 139, 144, 235], 267: [1, 4, 16, 64, 67, 91, 97, 121, 217, 223, 256], 331: [1, 74, 80, 85, 111, 120, 167, 180, 270, 274, 293], 631: [1, 8, 43, 64, 79, 188, 228, 242, 279, 310, 339, 344, 512, 562, 587]}
(G, S1, S2, S3, S4) = (None, [], [], [], [])
if (n in indices):
if existence:
return True
(G, [S1, S2, S3, S4]) = _construction_supplementary_difference_set(n, H_db[n], indices[n], cosets_gens[n], check=False)
elif skew_supplementary_difference_set_over_polynomial_ring(n, existence=True):
if existence:
return True
(G, [S1, S2, S3, S4]) = skew_supplementary_difference_set_over_polynomial_ring(n, check=False)
elif skew_supplementary_difference_set_with_paley_todd(n, existence=True):
if existence:
return True
(G, [S1, S2, S3, S4]) = skew_supplementary_difference_set_with_paley_todd(n, check=False)
if existence:
return False
if (G is None):
raise ValueError(f'Skew SDS of order {n} not yet implemented.')
if check:
lmbda = ((((len(S1) + len(S2)) + len(S3)) + len(S4)) - n)
assert is_supplementary_difference_set([S1, S2, S3, S4], lmbda=lmbda, G=G)
assert _is_skew_set(G, S1)
if return_group:
return (G, [S1, S2, S3, S4])
return [S1, S2, S3, S4]
|
def _construction_supplementary_difference_set(n, H, indices, cosets_gen, check=True):
'\n Construct `4-\\{n; n_1, n_2, n_3, n_4; \\lambda\\}` supplementary difference sets,\n where `n_1 + n_2 + n_3 + n_4 = n+\\lambda`.\n\n This construction is described in [Djo1994a]_.\n\n Let H be a subgroup of Zmod(n) of order `t`. We construct the `2s = n/t` cosets\n `\\alpha_0, .., \\alpha_{2s-1}` by using the elements contained in a sequence `A`:\n `\\alpha_{2i} = a_iH` and `\\alpha_{2i+1} = -\\alpha_{2i}`.\n\n Then, we use four indices sets `J_1, J_2, J_3, J_4` to construct the four\n supplementary difference sets: `S_i = \\bigcup_{j\\in J__i} \\alpha_i`. Note that\n if `J_i` contains the value `-1`, this function will add `0` to the set `S_i`.\n\n To construct a coset `\\alpha_{2i}` by listing it directly, replace the `2i`-th\n element of the list `A` with the desired set.\n\n INPUT:\n\n - ``n`` -- integer; the parameter of the supplementary difference set\n - ``H`` -- list of integers; the set `H` used to construct the cosets\n - ``indices`` -- list containing four lists of integers; the sets\n `J_1, J_2, J_3, J_4` described above\n - ``cosets_gen`` -- list containing integers or list of integers; the set `A`\n described above\n - ``check`` -- boolean (default: ``True``); if ``True``, check that the sets\n are supplementary difference sets; setting this parameter to ``False`` may\n speed up the computation considerably\n\n OUTPUT:\n\n The function returns the ring of integers modulo ``n`` and a list containing\n the 4 sets.\n\n TESTS::\n\n sage: from sage.combinat.designs.difference_family import is_supplementary_difference_set, _construction_supplementary_difference_set\n sage: H = [1, 10, -11]\n sage: cosets_gen = [1, 2, 3, 5, 6, 9]\n sage: indices = [[0, 3, 5, 7, 9, 10], [0, 5, 6, 7, 8], [1, 2, 6, 7, 9], [2, 6, 8, 9, 10]]\n sage: _construction_supplementary_difference_set(37, H, indices, cosets_gen)\n (Ring of integers modulo 37,\n [[32, 1, 33, 35, 34, 7, 9, 10, 12, 14, 16, 17, 18, 22, 24, 26, 29, 31],\n [32, 1, 33, 34, 5, 6, 7, 8, 10, 13, 18, 19, 23, 24, 26],\n [32, 2, 36, 5, 11, 13, 14, 15, 18, 19, 20, 24, 27, 29, 31],\n [2, 5, 6, 8, 9, 12, 13, 14, 15, 16, 19, 20, 23, 29, 31]])\n sage: H = [1, 16, 22]\n sage: cosets_gen = [1, 2, 3, 4, 6, 8, [13]]\n sage: indices = [[1, 3, 5, 6, 8, 10, 12], [0, 1, 5, 8, 12, 13], [1, 3, 4, 7, 9, 12, 13], [0, 1, 2, 3, 7, 8]]\n sage: _construction_supplementary_difference_set(39, H, indices, cosets_gen)\n (Ring of integers modulo 39,\n [[4, 6, 7, 8, 10, 11, 12, 13, 15, 17, 18, 20, 23, 25, 30, 34, 36, 37, 38],\n [1, 36, 38, 6, 12, 13, 15, 16, 17, 18, 22, 23, 26, 30],\n [3, 7, 9, 13, 14, 17, 21, 23, 24, 26, 27, 29, 33, 34, 35, 37, 38],\n [32, 1, 2, 34, 35, 5, 38, 37, 7, 6, 14, 15, 16, 17, 18, 22, 23, 29]])\n sage: H = [1, 4, 11, 16, 21, -2, -8]\n sage: cosets_gen = [1, 3, 7]\n sage: indices = [[1, 2, 4], [1, 2, 4], [0, 2, 3], [3, 4, -1]]\n sage: G, sets = _construction_supplementary_difference_set(43, H, indices, cosets_gen, check=False)\n sage: is_supplementary_difference_set(sets, lmbda=35, G=G)\n True\n\n .. SEEALSO::\n\n :func:`skew_supplementary_difference_set`\n '
def generate_set(index_set, cosets):
S = set()
for idx in index_set:
if (idx == (- 1)):
S.add(Z(0))
else:
S = S.union(cosets[idx])
return list(S)
Z = Zmod(n)
H = set(map(Z, H))
cosets = []
for el in cosets_gen:
if isinstance(el, list):
even_coset = {Z(x) for x in el}
else:
even_coset = {(x * el) for x in H}
odd_coset = {(- x) for x in even_coset}
cosets.append(even_coset)
cosets.append(odd_coset)
S1 = generate_set(indices[0], cosets)
S2 = generate_set(indices[1], cosets)
S3 = generate_set(indices[2], cosets)
S4 = generate_set(indices[3], cosets)
if check:
lmbda = ((((len(S1) + len(S2)) + len(S3)) + len(S4)) - n)
assert is_supplementary_difference_set([S1, S2, S3, S4], lmbda=lmbda, G=Z)
return (Z, [S1, S2, S3, S4])
|
def supplementary_difference_set_hadamard(n, existence=False, check=True):
'\n Construct `4-\\{n; n_1, n_2, n_3, n_4; \\lambda\\}` supplementary difference sets,\n where `n_1 + n_2 + n_3 + n_4 = n+\\lambda`.\n\n These sets are constructed from available data, as described in [Djo1994a]_.\n The data is taken from:\n\n * `n = 191`: [Djo2008c]_\n * `n = 239`: [Djo1994b]_\n * `n = 251`: [DGK2014]_\n\n Additional SDS are constructed using :func:`skew_supplementary_difference_set`.\n\n INPUT:\n\n - ``n`` -- integer; the parameter of the supplementary difference set\n - ``existence`` -- boolean (default: ``False``); if ``True``, only check\n whether the supplementary difference sets can be constructed\n - ``check`` -- boolean (default: ``True``); if ``True``, check that the sets\n are supplementary difference sets before returning them; Setting this\n parameter to ``False`` may speed up the computation considerably\n\n OUTPUT:\n\n If ``existence=False``, the function returns the ring of integers modulo\n ``n`` and a list containing the 4 sets, or raises an error if data for the\n given ``n`` is not available.\n If ``existence=True``, the function returns a boolean representing whether\n skew supplementary difference sets can be constructed.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import supplementary_difference_set_hadamard\n sage: G, [S1, S2, S3, S4] = supplementary_difference_set_hadamard(191)\n\n If ``existence=True``, the function returns a boolean::\n\n sage: supplementary_difference_set_hadamard(191, existence=True)\n True\n sage: supplementary_difference_set_hadamard(17, existence=True)\n False\n\n TESTS::\n\n sage: from sage.combinat.designs.difference_family import is_supplementary_difference_set\n sage: G, [S1, S2, S3, S4] = supplementary_difference_set_hadamard(191, check=False)\n sage: is_supplementary_difference_set([S1, S2, S3, S4], lmbda=len(S1)+len(S2)+len(S3)+len(S4)-191, G=G)\n True\n sage: G, [S1, S2, S3, S4] = supplementary_difference_set_hadamard(37, check=False)\n sage: is_supplementary_difference_set([S1, S2, S3, S4], lmbda=len(S1)+len(S2)+len(S3)+len(S4)-37, G=G)\n True\n sage: supplementary_difference_set_hadamard(7)\n Traceback (most recent call last):\n ...\n ValueError: SDS of order 7 not yet implemented.\n sage: supplementary_difference_set_hadamard(7, existence=True)\n False\n sage: supplementary_difference_set_hadamard(127, existence=True)\n True\n '
indices = {191: [[1, 7, 9, 10, 11, 13, 17, 18, 25, 26, 30, 31, 33, 34, 35, 36, 37], [1, 4, 7, 9, 11, 12, 13, 14, 19, 21, 22, 23, 24, 25, 26, 29, 36, 37], [0, 3, 4, 5, 7, 8, 9, 16, 17, 19, 24, 25, 29, 30, 31, 33, 35, 37], [1, 3, 4, 5, 8, 11, 14, 18, 19, 20, 21, 23, 24, 25, 28, 29, 30, 32, 34, 35]], 239: [[0, 1, 2, 3, 4, 5, 6, 7, 14, 18, 19, 21, 24, 25, 29, 30], [0, 1, 3, 7, 9, 12, 15, 18, 20, 22, 26, 28, 29, 30, 31, 32, 33], [2, 3, 4, 5, 8, 9, 10, 11, 13, 17, 19, 21, 22, 24, 27, 31, 32], [0, 1, 2, 3, 6, 7, 8, 11, 13, 15, 17, 18, 19, 22, 25, 26, 27, 32, 33]], 251: [[2, 6, 8, 10, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 27, 28, 35, 36, 39, 41, 43, 44, 47, 48], [2, 5, 10, 11, 17, 18, 21, 23, 24, 25, 26, 28, 29, 30, 34, 35, 38, 39, 40, 41, 42, 43, 44, 49], [0, 2, 6, 7, 10, 11, 14, 15, 16, 18, 21, 22, 24, 26, 30, 35, 37, 38, 45, 46, 47, 48, 49], [1, 2, 3, 4, 8, 9, 12, 17, 21, 22, 27, 28, 29, 30, 33, 34, 39, 41, 42, 43, 46, 47, 48]]}
cosets_gens = {191: [1, 2, 3, 4, 6, 8, 9, 11, 12, 13, 16, 17, 18, 19, 22, 32, 36, 38, 41], 239: [1, 2, 3, 4, 5, 6, 7, 8, 9, 13, 14, 15, 18, 21, 28, 35, 42], 251: [1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 14, 15, 17, 18, 19, 21, 28, 30, 33, 34, 35, 41, 43, 45, 68]}
H_db = {191: [1, 39, 184, 109, 49], 239: [1, 10, 24, 44, 98, 100, 201], 251: [1, 20, 113, 149, 219]}
if existence:
return ((n in indices) or skew_supplementary_difference_set(n, existence=True))
sets = None
G = None
if (n in indices):
(G, sets) = _construction_supplementary_difference_set(n, H_db[n], indices[n], cosets_gens[n], check=False)
elif skew_supplementary_difference_set(n, existence=True):
(G, sets) = skew_supplementary_difference_set(n, check=False, return_group=True)
if (sets is None):
raise ValueError(f'SDS of order {n} not yet implemented.')
(S1, S2, S3, S4) = sets
if check:
lmbda = ((((len(S1) + len(S2)) + len(S3)) + len(S4)) - n)
assert is_supplementary_difference_set([S1, S2, S3, S4], lmbda=lmbda, G=G)
return (G, [S1, S2, S3, S4])
|
def _is_skew_set(G, S):
'\n Check if ``S`` is a skew set over the group ``G``.\n\n From [Djo1994a]_, a set `S \\subset G` (where `G` is a finite abelian group of order `n`) is of skew\n type if `S_1 \\cap (-S_1) = \\emptyset` and `S_1 \\cup (-S_1) = G\\setminus \\{0\\}`.\n\n INPUT:\n\n - ``G`` -- a group\n - ``S`` -- list containing elements of ``G``; the set to be checked\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import _is_skew_set\n sage: Z5 = Zmod(5)\n sage: _is_skew_set(Z5, [Z5(1), Z5(2)])\n True\n sage: _is_skew_set(Z5, [Z5(1), Z5(2), Z5(3)])\n False\n sage: _is_skew_set(Z5, [Z5(1)])\n False\n '
for el in S:
if ((- el) in S):
return False
for el in G:
if (el == 0):
continue
if ((el not in S) and ((- el) not in S)):
return False
return True
|
def are_complementary_difference_sets(G, A, B, verbose=False):
'\n Check if ``A`` and ``B`` are complementary difference sets over the group ``G``.\n\n According to [Sze1971]_, two sets `A`, `B` of size `m` are complementary\n difference sets over a group `G` of size `2m+1` if:\n\n 1. they are `2-\\{2m+1; m, m; m-1\\}` supplementary difference sets\n 2. `A` is skew, i.e. `a \\in A` implies `-a \\not \\in A`\n\n INPUT:\n\n - ``G`` -- a group of odd order\n - ``A`` -- a set of elements of ``G``\n - ``B`` -- a set of elements of ``G``\n - ``verbose`` -- boolean (default: ``False``); if ``True`` the function will\n be verbose when the sets do not satisfy the contraints\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import are_complementary_difference_sets\n sage: are_complementary_difference_sets(Zmod(7), [1, 2, 4], [1, 2, 4])\n True\n\n If ``verbose=True``, the function will be verbose::\n\n sage: are_complementary_difference_sets(Zmod(7), [1, 2, 5], [1, 2, 4], verbose=True)\n The sets are not supplementary difference sets with lambda = 2\n False\n\n TESTS::\n\n sage: are_complementary_difference_sets(Zmod(16), [1, 2, 4], [1, 2, 4])\n False\n sage: are_complementary_difference_sets(Zmod(7), [1, 2, 4], [1, 2, 3, 4])\n False\n sage: are_complementary_difference_sets(Zmod(19), [1, 4, 5, 6, 7, 9, 11, 16, 17], [1, 4, 5, 6, 7, 9, 11, 16, 17])\n True\n\n .. SEEALSO::\n\n :func:`is_supplementary_difference_set`\n '
n = G.order()
if ((n % 2) != 1):
if verbose:
print('G must have odd order')
return False
m = ((n - 1) // 2)
if ((len(A) != m) or (len(B) != m)):
if verbose:
print(f'A and B must have size {m}')
return False
if (not is_supplementary_difference_set([A, B], lmbda=(m - 1), G=G)):
if verbose:
print(f'The sets are not supplementary difference sets with lambda = {(m - 1)}')
return False
if (not _is_skew_set(G, A)):
if verbose:
print('The set A is not skew')
return False
return True
|
def complementary_difference_setsI(n, check=True):
'\n Construct complementary difference sets in a group of order `n \\cong 3 \\mod 4`, `n` a prime power.\n\n Let `G` be a Galois Field of order `n`, where `n` satisfies the requirements\n above. Let `A` be the set of non-zero quadratic elements in `G`, and `B = A`.\n Then `A` and `B` are complementary difference sets over a group of order `n`.\n This construction is described in [Sze1971]_.\n\n INPUT:\n\n - ``n`` -- integer; the order of the group `G`\n - ``check`` -- boolean (default: ``True``); if ``True``, check that the sets\n are complementary difference sets before returning them\n\n OUTPUT:\n\n The function returns the Galois field of order ``n`` and the two sets, or raises\n an error if ``n`` does not satisfy the requirements of this construction.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import complementary_difference_setsI\n sage: complementary_difference_setsI(19)\n (Finite Field of size 19,\n [1, 4, 5, 6, 7, 9, 11, 16, 17],\n [1, 4, 5, 6, 7, 9, 11, 16, 17])\n\n TESTS::\n\n sage: from sage.combinat.designs.difference_family import are_complementary_difference_sets\n sage: G, A, B = complementary_difference_setsI(23, check=False)\n sage: are_complementary_difference_sets(G, A, B)\n True\n sage: complementary_difference_setsI(17)\n Traceback (most recent call last):\n ...\n ValueError: the parameter 17 is not valid\n sage: complementary_difference_setsI(15) # needs sage.libs.pari\n Traceback (most recent call last):\n ...\n ValueError: the parameter 15 is not valid\n\n .. SEEALSO::\n\n :func:`are_complementary_difference_sets`\n :func:`complementary_difference_sets`\n '
if (not (((n % 4) == 3) and is_prime_power(n))):
raise ValueError(f'the parameter {n} is not valid')
from sage.rings.finite_rings.finite_field_constructor import GF
G = GF(n, 'a')
A = list({(x ** 2) for x in G if ((x ** 2) != 0)})
B = A
if check:
assert are_complementary_difference_sets(G, A, B)
return (G, A, B)
|
def complementary_difference_setsII(n, check=True):
'\n Construct complementary difference sets in a group of order `n = p^t`, where `p \\cong 5 \\mod 8` and `t \\cong 1, 2, 3 \\mod 4`.\n\n Consider a finite field `G` of order `n` and let `\\rho` be the generator of\n the corresponding multiplicative group. Then, there are two different constructions,\n depending on whether `t` is even or odd.\n\n If `t \\cong 2 \\mod 4`, let `C_0` be the set of non-zero octic residues in `G`,\n and let `C_i = \\rho^i C_0` for `1 \\le i \\le 7`.\n Then, `A = C_0 \\cup C_1 \\cup C_2 \\cup C_3` and `B = C_0 \\cup C_1 \\cup C_6 \\cup C_7`.\n\n If `t` is odd, let `C_0` be the set of non-zero fourth powers in `G`, and let\n `C_i = \\rho^i C_0` for `1 \\le i \\le 3`.\n Then, `A = C_0 \\cup C_1` and `B = C_0 \\cup C_3`.\n\n For more details on this construction, see [Sze1971]_.\n\n INPUT:\n\n - ``n`` -- integer; the order of the group `G`\n - ``check`` -- boolean (default: ``True``); if ``True``, check that the sets\n are complementary difference sets before returning them; setting this to\n ``False`` might speed up the computation for large values of ``n``\n\n OUTPUT:\n\n The function returns the Galois field of order ``n`` and the two sets, or raises\n an error if ``n`` does not satisfy the requirements of this construction.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import complementary_difference_setsII\n sage: complementary_difference_setsII(5) # needs sage.libs.pari\n (Finite Field of size 5, [1, 2], [1, 3])\n\n TESTS::\n\n sage: # needs sage.libs.pari\n sage: from sage.combinat.designs.difference_family import are_complementary_difference_sets\n sage: G, A, B = complementary_difference_setsII(25, check=False)\n sage: are_complementary_difference_sets(G, A, B)\n True\n sage: G, A, B = complementary_difference_setsII(13, check=False)\n sage: are_complementary_difference_sets(G, A, B)\n True\n sage: complementary_difference_setsII(49)\n Traceback (most recent call last):\n ...\n ValueError: the parameter 49 is not valid\n sage: complementary_difference_setsII(15)\n Traceback (most recent call last):\n ...\n ValueError: the parameter 15 is not valid\n\n .. SEEALSO::\n\n :func:`are_complementary_difference_sets`\n :func:`complementary_difference_sets`\n '
(p, t) = is_prime_power(n, get_data=True)
if (not (((p % 8) == 5) and (t > 0) and ((t % 4) in [1, 2, 3]))):
raise ValueError(f'the parameter {n} is not valid')
from sage.rings.finite_rings.finite_field_constructor import GF
G = GF(n, 'a')
(A, B) = (None, None)
if ((t % 2) == 0):
rho = G.multiplicative_generator()
C0 = list({(el ** 8) for el in G if (el != 0)})
(C1, C2, C3, C6, C7) = map((lambda i: [((rho ** i) * el) for el in C0]), [1, 2, 3, 6, 7])
A = (((C0 + C1) + C2) + C3)
B = (((C0 + C1) + C6) + C7)
else:
rho = G.multiplicative_generator()
C0 = list({(el ** 4) for el in G if ((el ** 4) != 0)})
C1 = [(rho * el) for el in C0]
C3 = [((rho ** 3) * el) for el in C0]
A = (C0 + C1)
B = (C0 + C3)
if check:
assert are_complementary_difference_sets(G, A, B)
return (G, A, B)
|
def complementary_difference_setsIII(n, check=True):
"\n Construct complementary difference sets in a group of order `n = 2m + 1`, where `4m + 3` is a prime power.\n\n Consider a finite field `G` of order `n` and let `\\rho` be a primite element\n of this group. Now let `Q` be the set of non zero quadratic residues in `G`,\n and let `A = \\{ a | \\rho^{2a} - 1 \\in Q\\}`, `B' = \\{ b | -(\\rho^{2b} + 1) \\in Q\\}`.\n Then `A` and `B = Q \\setminus B'` are complementary difference sets over the ring\n of integers modulo `n`. For more details, see [Sz1969]_.\n\n INPUT:\n\n - ``n`` -- integer; the order of the group over which the sets are constructed\n - ``check`` -- boolean (default: ``True``); if ``True``, check that the sets\n are complementary difference sets before returning them; setting this to\n ``False`` might speed up the computation for large values of ``n``\n\n OUTPUT:\n\n The function returns the Galois field of order ``n`` and the two sets, or raises\n an error if ``n`` does not satisfy the requirements of this construction.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import complementary_difference_setsIII\n sage: complementary_difference_setsIII(11) # needs sage.libs.pari\n (Ring of integers modulo 11, [1, 2, 5, 7, 8], [0, 1, 3, 8, 10])\n\n TESTS::\n\n sage: from sage.combinat.designs.difference_family import are_complementary_difference_sets\n sage: G, A, B = complementary_difference_setsIII(21, check=False) # needs sage.libs.pari\n sage: are_complementary_difference_sets(G, A, B) # needs sage.libs.pari\n True\n sage: G, A, B = complementary_difference_setsIII(65, check=False) # needs sage.libs.pari\n sage: are_complementary_difference_sets(G, A, B) # needs sage.libs.pari\n True\n sage: complementary_difference_setsIII(10)\n Traceback (most recent call last):\n ...\n ValueError: the parameter 10 is not valid\n sage: complementary_difference_setsIII(17) # needs sage.libs.pari\n Traceback (most recent call last):\n ...\n ValueError: the parameter 17 is not valid\n\n .. SEEALSO::\n\n :func:`are_complementary_difference_sets`\n :func:`complementary_difference_sets`\n "
m = ((n - 1) // 2)
q = ((4 * m) + 3)
if (((n % 2) != 1) or (not is_prime_power(q))):
raise ValueError(f'the parameter {n} is not valid')
from sage.rings.finite_rings.finite_field_constructor import GF
G = Zmod(n)
G2 = GF(q)
rho = G2.primitive_element()
Q = [(rho ** (2 * b)) for b in range(1, (n + 1))]
A = [G(a) for a in range(n) if (((rho ** (2 * a)) - 1) in Q)]
B = [G(b) for b in range(n) if (((- (rho ** (2 * b))) - 1) not in Q)]
if check:
assert are_complementary_difference_sets(G, A, B)
return (G, A, B)
|
def complementary_difference_sets(n, existence=False, check=True):
'\n Compute complementary difference sets over a group of order `n = 2m + 1`.\n\n According to [Sze1971]_, two sets `A`, `B` of size `m` are complementary\n difference sets over a group `G` of size `n = 2m + 1` if:\n\n 1. they are `2-\\{2m+1; m, m; m-1\\}` supplementary difference sets\n 2. `A` is skew, i.e. `a \\in A` implies `-a \\not \\in A`\n\n This method tries to call :func:`complementary_difference_setsI`,\n :func:`complementary_difference_setsII` or :func:`complementary_difference_setsIII`\n if the parameter `n` satisfies the requirements of one of these functions.\n\n INPUT:\n\n - ``n`` -- integer; the order of the group over which the sets are constructed\n - ``existence`` -- boolean (default: ``False``); if ``True``, only check\n whether the supplementary difference sets can be constructed\n - ``check`` -- boolean (default: ``True``); if ``True``, check that the sets\n are complementary difference sets before returning them; setting this to\n ``False`` might speed up the computation for large values of ``n``\n\n OUTPUT:\n\n If ``existence=False``, the function returns group ``G`` and two complementary\n difference sets, or raises an error if data for the given ``n`` is not available.\n If ``existence=True``, the function returns a boolean representing whether\n complementary difference sets can be constructed for the given ``n``.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_family import complementary_difference_sets\n sage: complementary_difference_sets(15) # needs sage.libs.pari\n (Ring of integers modulo 15, [1, 2, 4, 6, 7, 10, 12], [0, 1, 2, 6, 9, 13, 14])\n\n If ``existence=True``, the function returns a boolean::\n\n sage: complementary_difference_sets(15, existence=True) # needs sage.libs.pari\n True\n sage: complementary_difference_sets(16, existence=True)\n False\n\n TESTS::\n\n sage: from sage.combinat.designs.difference_family import are_complementary_difference_sets\n sage: G, A, B = complementary_difference_sets(29) # needs sage.libs.pari\n sage: are_complementary_difference_sets(G, A, B) # needs sage.libs.pari\n True\n sage: G, A, B = complementary_difference_sets(65) # needs sage.libs.pari\n sage: are_complementary_difference_sets(G, A, B) # needs sage.libs.pari\n True\n sage: complementary_difference_sets(10)\n Traceback (most recent call last):\n ...\n ValueError: the parameter n must be odd\n sage: complementary_difference_sets(17) # needs sage.libs.pari\n Traceback (most recent call last):\n ...\n NotImplementedError: complementary difference sets of order 17 are not implemented yet\n\n .. SEEALSO::\n\n :func:`are_complementary_difference_sets`\n '
if ((n % 2) == 0):
if existence:
return False
raise ValueError('the parameter n must be odd')
(p, t) = is_prime_power(n, get_data=True)
(G, A, B) = (None, None, None)
if (((n % 4) == 3) and (t > 0)):
if existence:
return True
(G, A, B) = complementary_difference_setsI(n, check=False)
elif (((p % 8) == 5) and (t > 0) and ((t % 4) in [1, 2, 3])):
if existence:
return True
(G, A, B) = complementary_difference_setsII(n, check=False)
elif is_prime_power(((2 * n) + 1)):
if existence:
return True
(G, A, B) = complementary_difference_setsIII(n, check=False)
if existence:
return False
if (G is None):
raise NotImplementedError(f'complementary difference sets of order {n} are not implemented yet')
if check:
assert are_complementary_difference_sets(G, A, B)
return (G, A, B)
|
def difference_family(v, k, l=1, existence=False, explain_construction=False, check=True):
'\n Return a (``k``, ``l``)-difference family on an Abelian group of cardinality ``v``.\n\n Let `G` be a finite Abelian group. For a given subset `D` of `G`, we define\n `\\Delta D` to be the multi-set of differences `\\Delta D = \\{x - y; x \\in D,\n y \\in D, x \\not= y\\}`. A `(G,k,\\lambda)`-*difference family* is a collection\n of `k`-subsets of `G`, `D = \\{D_1, D_2, \\ldots, D_b\\}` such that the union\n of the difference sets `\\Delta D_i` for `i=1,...b`, seen as a multi-set,\n contains each element of `G \\backslash \\{0\\}` exactly `\\lambda`-times.\n\n When there is only one block, i.e. `\\lambda(v - 1) = k(k-1)`, then a\n `(G,k,\\lambda)`-difference family is also called a *difference set*.\n\n See also :wikipedia:`Difference_set`.\n\n If there is no such difference family, an ``EmptySetError`` is raised and if\n there is no construction at the moment ``NotImplementedError`` is raised.\n\n INPUT:\n\n - ``v,k,l`` -- parameters of the difference family. If ``l`` is not provided\n it is assumed to be ``1``\n - ``existence`` -- if ``True``, then return either ``True`` if Sage knows\n how to build such design, ``Unknown`` if it does not and ``False`` if it\n knows that the design does not exist\n - ``explain_construction`` -- instead of returning a difference family,\n returns a string that explains the construction used\n - ``check`` -- boolean (default: ``True``); if ``True``, then the result of\n the computation is checked before being returned. This should not be\n needed but ensures that the output is correct\n\n OUTPUT:\n\n A pair ``(G,D)`` made of a group `G` and a difference family `D` on that\n group. Or, if ``existence=True``` a troolean or if\n ``explain_construction=True`` a string.\n\n EXAMPLES::\n\n sage: G,D = designs.difference_family(73,4) # needs sage.libs.pari\n sage: G # needs sage.libs.pari\n Finite Field of size 73\n sage: D # needs sage.libs.pari\n [[0, 1, 5, 18],\n [0, 3, 15, 54],\n [0, 9, 45, 16],\n [0, 27, 62, 48],\n [0, 8, 40, 71],\n [0, 24, 47, 67]]\n\n sage: print(designs.difference_family(73, 4, explain_construction=True))\n The database contains a (73,4)-evenly distributed set\n\n sage: # needs sage.libs.pari\n sage: G,D = designs.difference_family(15,7,3)\n sage: G\n Ring of integers modulo 15\n sage: D\n [[0, 1, 2, 4, 5, 8, 10]]\n sage: print(designs.difference_family(15,7,3,explain_construction=True))\n Singer difference set\n\n sage: print(designs.difference_family(91,10,1,explain_construction=True)) # needs sage.libs.pari\n Singer difference set\n sage: print(designs.difference_family(64,28,12, explain_construction=True)) # needs sage.libs.pari\n McFarland 1973 construction\n sage: print(designs.difference_family(576, 276, 132, explain_construction=True)) # needs sage.libs.pari\n Hadamard difference set product from N1=2 and N2=3\n\n For `k=6,7` we look at the set of small prime powers for which a\n construction is available::\n\n sage: def prime_power_mod(r,m):\n ....: k = m+r\n ....: while True:\n ....: if is_prime_power(k):\n ....: yield k\n ....: k += m\n\n sage: from itertools import islice\n sage: l6 = {True:[], False: [], Unknown: []}\n sage: for q in islice(prime_power_mod(1,30), int(60)): # needs sage.libs.pari\n ....: l6[designs.difference_family(q,6,existence=True)].append(q)\n sage: l6[True]\n [31, 121, 151, 181, 211, ..., 3061, 3121, 3181]\n sage: l6[Unknown]\n [61]\n sage: l6[False]\n []\n\n sage: l7 = {True: [], False: [], Unknown: []}\n sage: for q in islice(prime_power_mod(1,42), int(60)): # needs sage.libs.pari\n ....: l7[designs.difference_family(q,7,existence=True)].append(q)\n sage: l7[True]\n [169, 337, 379, 421, 463, 547, 631, 673, 757, 841, 883, 967, ..., 4621, 4957, 5167]\n sage: l7[Unknown]\n [43, 127, 211, 2017, 2143, 2269, 2311, 2437, 2521, 2647, ..., 4999, 5041, 5209]\n sage: l7[False]\n []\n\n List available constructions::\n\n sage: for v in range(2,100): # needs sage.libs.pari\n ....: constructions = []\n ....: for k in range(2,10):\n ....: for l in range(1,10):\n ....: ret = designs.difference_family(v,k,l,existence=True)\n ....: if ret is True:\n ....: constructions.append((k,l))\n ....: _ = designs.difference_family(v,k,l)\n ....: if constructions:\n ....: print("%2d: %s"%(v, \', \'.join(\'(%d,%d)\'%(k,l) for k,l in constructions)))\n 3: (2,1)\n 4: (3,2)\n 5: (2,1), (4,3)\n 6: (5,4)\n 7: (2,1), (3,1), (3,2), (4,2), (6,5)\n 8: (7,6)\n 9: (2,1), (4,3), (8,7)\n 10: (9,8)\n 11: (2,1), (4,6), (5,2), (5,4), (6,3)\n 13: (2,1), (3,1), (3,2), (4,1), (4,3), (5,5), (6,5)\n 15: (3,1), (4,6), (5,6), (7,3), (7,6)\n 16: (3,2), (5,4), (6,2)\n 17: (2,1), (4,3), (5,5), (8,7)\n 19: (2,1), (3,1), (3,2), (4,2), (6,5), (9,4), (9,8)\n 21: (3,1), (4,3), (5,1), (6,3), (6,5)\n 22: (4,2), (6,5), (7,4), (8,8)\n 23: (2,1)\n 25: (2,1), (3,1), (3,2), (4,1), (4,3), (6,5), (7,7), (8,7)\n 27: (2,1), (3,1)\n 28: (3,2), (6,5)\n 29: (2,1), (4,3), (7,3), (7,6), (8,4), (8,6)\n 31: (2,1), (3,1), (3,2), (4,2), (5,2), (5,4), (6,1), (6,5)\n 33: (3,1), (5,5), (6,5)\n 34: (4,2)\n 35: (5,2)\n 37: (2,1), (3,1), (3,2), (4,1), (4,3), (6,5), (9,2), (9,8)\n 39: (3,1), (6,5)\n 40: (3,2), (4,1)\n 41: (2,1), (4,3), (5,1), (5,4), (6,3), (8,7)\n 43: (2,1), (3,1), (3,2), (4,2), (6,5), (7,2), (7,3), (7,6), (8,4)\n 45: (3,1), (5,1)\n 46: (4,2), (6,2)\n 47: (2,1)\n 49: (2,1), (3,1), (3,2), (4,1), (4,3), (6,5), (8,7), (9,3)\n 51: (3,1), (5,2), (6,3)\n 52: (4,1)\n 53: (2,1), (4,3)\n 55: (3,1), (9,4)\n 57: (3,1), (7,3), (8,1)\n 59: (2,1)\n 61: (2,1), (3,1), (3,2), (4,1), (4,3), (5,1), (5,4), (6,2), (6,3), (6,5)\n 63: (3,1)\n 64: (3,2), (4,1), (7,2), (7,6), (9,8)\n 65: (5,1)\n 67: (2,1), (3,1), (3,2), (6,5)\n 69: (3,1)\n 71: (2,1), (5,2), (5,4), (7,3), (7,6), (8,4)\n 73: (2,1), (3,1), (3,2), (4,1), (4,3), (6,5), (8,7), (9,1), (9,8)\n 75: (3,1), (5,2)\n 76: (4,1)\n 79: (2,1), (3,1), (3,2), (6,5)\n 81: (2,1), (3,1), (4,3), (5,1), (5,4), (8,7)\n 83: (2,1)\n 85: (4,1), (7,2), (7,3), (8,2)\n 89: (2,1), (4,3), (8,7)\n 91: (6,1), (7,1)\n 97: (2,1), (3,1), (3,2), (4,1), (4,3), (6,5), (8,7), (9,3)\n\n TESTS:\n\n Check more of the Wilson constructions from [Wi72]_::\n\n sage: Q5 = [241, 281,421,601,641, 661, 701, 821,881]\n sage: Q9 = [73, 1153, 1873, 2017]\n sage: Q15 = [76231]\n sage: Q4 = [13, 73, 97, 109, 181, 229, 241, 277, 337, 409, 421, 457]\n sage: Q8 = [1009, 3137, 3697]\n sage: for Q,k in [(Q4,4),(Q5,5),(Q8,8),(Q9,9),(Q15,15)]: # needs sage.libs.pari\n ....: for q in Q:\n ....: assert designs.difference_family(q,k,1,existence=True) is True\n ....: _ = designs.difference_family(q,k,1)\n\n Check Singer difference sets::\n\n sage: sgp = lambda q,d: ((q**(d+1)-1)//(q-1), (q**d-1)//(q-1), (q**(d-1)-1)//(q-1))\n\n sage: for q in range(2,10): # needs sage.libs.pari\n ....: if is_prime_power(q):\n ....: for d in [2,3,4]:\n ....: v,k,l = sgp(q,d)\n ....: assert designs.difference_family(v,k,l,existence=True) is True\n ....: _ = designs.difference_family(v,k,l)\n\n Check twin primes difference sets::\n\n sage: for p in [3,5,7,9,11]: # needs sage.libs.pari\n ....: v = p*(p+2); k = (v-1)/2; lmbda = (k-1)/2\n ....: G,D = designs.difference_family(v,k,lmbda)\n\n Check Complementary difference sets::\n\n sage: for v in [15, 33, 35, 39, 51]: # needs sage.libs.pari\n ....: G, D = designs.difference_family(v, (v-1)//2, (v-1)//2-1)\n\n Check the database::\n\n sage: from sage.combinat.designs.database import DF,EDS\n sage: for v,k,l in DF:\n ....: assert designs.difference_family(v,k,l,existence=True) is True\n ....: df = designs.difference_family(v,k,l,check=True)\n\n sage: for k in EDS: # needs sage.libs.pari\n ....: for v in EDS[k]:\n ....: assert designs.difference_family(v,k,1,existence=True) is True\n ....: df = designs.difference_family(v,k,1,check=True)\n\n Check the known Hadamard parameters::\n\n sage: for N in range(2,21): # needs sage.libs.pari\n ....: v = 4*N^2; k = 2*N^2-N; l = N^2-N\n ....: status = designs.difference_family(v,k,l,existence=True)\n ....: print("{:2} {}".format(N,designs.difference_family(v,k,l,explain_construction=True) if status is True else status))\n 2 McFarland 1973 construction\n 3 Turyn 1965 construction\n 4 McFarland 1973 construction\n 5 False\n 6 Unknown\n 7 False\n 8 McFarland 1973 construction\n 9 Unknown\n 10 Unknown\n 11 False\n 12 Hadamard difference set product from N1=2 and N2=3\n 13 False\n 14 Unknown\n 15 Unknown\n 16 McFarland 1973 construction\n 17 False\n 18 Hadamard difference set product from N1=3 and N2=3\n 19 False\n 20 Unknown\n\n Check a failing construction (:trac:`17528`)::\n\n sage: designs.difference_family(9,3)\n Traceback (most recent call last):\n ...\n NotImplementedError: No construction available for (9,3,1)-difference family\n\n Check that when ``existence=True`` we always obtain ``True``, ``False`` or ``Unknown``,\n and when ``explain_construction=True``, it is a string (see :trac:`24513`)::\n\n sage: designs.difference_family(3, 2, 1, existence=True)\n True\n sage: designs.difference_family(3, 2, 1, explain_construction=True)\n \'Trivial difference family\'\n\n sage: for _ in range(100): # needs sage.libs.pari\n ....: v = randint(1, 30)\n ....: k = randint(2, 30)\n ....: l = randint(1, 30)\n ....: res = designs.difference_family(v, k, l, existence=True)\n ....: assert res is True or res is False or res is Unknown\n ....: if res is True:\n ....: assert isinstance(designs.difference_family(3, 2, 1, explain_construction=True), str)\n\n .. TODO::\n\n Implement recursive constructions from Buratti "Recursive for difference\n matrices and relative difference families" (1998) and Jungnickel\n "Composition theorems for difference families and regular planes" (1978)\n '
from .block_design import are_hyperplanes_in_projective_geometry_parameters
from .database import DF, EDS
v = ZZ(v)
k = ZZ(k)
l = ZZ(l)
if ((v < 0) or (k < 0) or (l < 0)):
if existence:
return False
raise EmptySetError('No difference family eixsts with negative parameters')
if ((v, k, l) in DF):
if existence:
return True
elif explain_construction:
return 'The database contains a ({},{},{})-difference family'.format(v, k, l)
(vv, blocks) = next(iter(DF[(v, k, l)].items()))
from sage.rings.finite_rings.integer_mod_ring import Zmod
if (len(vv) == 1):
G = Zmod(vv[0])
else:
from sage.categories.cartesian_product import cartesian_product
G = cartesian_product([Zmod(i) for i in vv])
df = [[G(i) for i in b] for b in blocks]
if (check and (not is_difference_family(G, df, v=v, k=k, l=l))):
raise RuntimeError('There is an invalid ({},{},{})-difference family in the database... Please contact sage-devel@googlegroups.com'.format(v, k, l))
return (G, df)
elif ((l == 1) and (k in EDS) and (v in EDS[k])):
if existence:
return True
elif explain_construction:
return 'The database contains a ({},{})-evenly distributed set'.format(v, k)
from sage.rings.finite_rings.finite_field_constructor import GF
(poly, B) = EDS[k][v]
if (poly is None):
K = G = GF(v)
else:
K = G = GF(v, 'a', modulus=poly)
B = [K(b) for b in B]
e = ((k * (k - 1)) // 2)
xe = (G.multiplicative_generator() ** e)
df = [[((xe ** j) * b) for b in B] for j in range(((v - 1) // (2 * e)))]
if (check and (not is_difference_family(G, df, v=v, k=k, l=l))):
raise RuntimeError('There is an invalid ({},{})-evenly distributed set in the database... Please contact sage-devel@googlegroups.com'.format(v, k))
return (G, df)
if (k in [0, 1]):
if (v == 1):
if existence:
return True
from sage.rings.finite_rings.integer_mod_ring import Zmod
l = ([0] if (k == 1) else [])
return (Zmod(1), [l])
if existence:
return False
raise EmptySetError('No difference family exists with k=1 and v!=1')
e = (k * (k - 1))
if ((l * (v - 1)) % e):
if existence:
return Unknown
raise NotImplementedError('No construction available for ({},{},{})-difference family'.format(v, k, l))
if ((k == (v - 1)) and (l == (v - 2))):
if existence:
return True
elif explain_construction:
return 'Trivial difference family'
from sage.rings.finite_rings.integer_mod_ring import Zmod
G = Zmod(v)
return (G, [list(range(1, v))])
factorization = arith.factor(v)
if (len(factorization) == 1):
from sage.rings.finite_rings.finite_field_constructor import GF
K = GF(v, 'z')
if are_mcfarland_1973_parameters(v, k, l):
if existence:
return True
elif explain_construction:
return 'McFarland 1973 construction'
else:
(_, (q, s)) = are_mcfarland_1973_parameters(v, k, l, True)
(G, D) = mcfarland_1973_construction(q, s)
elif are_hyperplanes_in_projective_geometry_parameters(v, k, l):
if existence:
return True
elif explain_construction:
return 'Singer difference set'
else:
(_, (q, d)) = are_hyperplanes_in_projective_geometry_parameters(v, k, l, True)
(G, D) = singer_difference_set(q, d)
elif (are_hadamard_difference_set_parameters(v, k, l) and ((k - (2 * l)) == 3)):
if existence:
return True
elif explain_construction:
return 'Turyn 1965 construction'
else:
(G, D) = turyn_1965_3x3xK(4)
elif (are_hadamard_difference_set_parameters(v, k, l) and hadamard_difference_set_product_parameters((k - (2 * l)))):
(N1, N2) = hadamard_difference_set_product_parameters((k - (2 * l)))
if existence:
return True
elif explain_construction:
return 'Hadamard difference set product from N1={} and N2={}'.format(N1, N2)
else:
v1 = ((4 * N1) * N1)
v2 = ((4 * N2) * N2)
k1 = (((2 * N1) * N1) - N1)
k2 = (((2 * N2) * N2) - N2)
l1 = ((N1 * N1) - N1)
l2 = ((N2 * N2) - N2)
(G1, D1) = difference_family(v1, k1, l1)
(G2, D2) = difference_family(v2, k2, l2)
(G, D) = hadamard_difference_set_product(G1, D1, G2, D2)
elif (are_hadamard_difference_set_parameters(v, k, l) and (k - (2 * l)).is_prime()):
if existence:
return False
else:
raise EmptySetError('by McFarland 1989 such difference family does not exist')
elif ((len(factorization) == 1) and (radical_difference_family(K, k, l, existence=True) is True)):
if existence:
return True
elif explain_construction:
return 'Radical difference family on a finite field'
else:
D = radical_difference_family(K, k, l)
G = K
elif ((len(factorization) == 1) and (l == 1) and (k == 6) and (df_q_6_1(K, existence=True) is True)):
if existence:
return True
elif explain_construction:
return 'Wilson 1972 difference family made from the union of two cyclotomic cosets'
else:
D = df_q_6_1(K)
G = K
elif ((k == ((v - 1) // 2)) and (l == ((k - 1) // 2)) and (len(factorization) == 2) and (abs((pow(*factorization[0]) - pow(*factorization[1]))) == 2)):
if existence:
return True
elif explain_construction:
return 'Twin prime powers difference family'
else:
p = pow(*factorization[0])
q = pow(*factorization[1])
if (p > q):
(p, q) = (q, p)
(G, D) = twin_prime_powers_difference_set(p, check=False)
elif ((((v - 1) // 2) == k) and ((((v - 1) // 2) - 1) == l) and complementary_difference_sets(v, existence=True)):
if existence:
return True
elif explain_construction:
return 'Complementary difference sets'
else:
(G, A, B) = complementary_difference_sets(v)
D = [A, B]
else:
if existence:
return Unknown
raise NotImplementedError('No constructions for these parameters')
if (check and (not is_difference_family(G, D, v=v, k=k, l=l, verbose=False))):
raise RuntimeError("There is a problem. Sage built the following difference family on G='{}' with parameters ({},{},{}):\n {}\nwhich seems to not be a difference family... Please contact sage-devel@googlegroups.com".format(G, v, k, l, D))
return (G, D)
|
@cached_function
def find_product_decomposition(g, k, lmbda=1):
'\n Try to find a product decomposition construction for difference matrices.\n\n INPUT:\n\n - ``g,k,lmbda`` -- integers, parameters of the difference matrix\n\n OUTPUT:\n\n A pair of pairs ``(g1,lmbda),(g2,lmbda2)`` if Sage knows how to build\n `(g1,k,lmbda1)` and `(g2,k,lmbda2)` difference matrices and ``False``\n otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_matrices import find_product_decomposition\n sage: find_product_decomposition(77,6)\n ((7, 1), (11, 1))\n sage: find_product_decomposition(616,7)\n ((7, 1), (88, 1))\n sage: find_product_decomposition(24,10)\n False\n '
for lmbda1 in divisors(lmbda):
lmbda2 = (lmbda // lmbda1)
if (lmbda1 == lmbda):
if (lmbda2 == lmbda):
div = divisors(g)[1:(- 1)]
else:
div = divisors(g)[:(- 1)]
elif (lmbda2 == lmbda):
div = divisors(g)[1:]
else:
div = divisors(g)
for g1 in div:
g2 = (g // g1)
if (g1 > g2):
break
if ((difference_matrix(g1, k, lmbda1, existence=True) is True) and (difference_matrix(g2, k, lmbda2, existence=True) is True)):
return ((g1, lmbda1), (g2, lmbda2))
return False
|
def difference_matrix_product(k, M1, G1, lmbda1, M2, G2, lmbda2, check=True):
'\n Return the product of the ``(G1,k,lmbda1)`` and ``(G2,k,lmbda2)`` difference\n matrices ``M1`` and ``M2``.\n\n The result is a `(G1 \\times G2, k, \\lambda_1 \\lambda_2)`-difference matrix.\n\n INPUT:\n\n - ``k,lmbda1,lmbda2`` -- positive integer\n\n - ``G1, G2`` -- groups\n\n - ``M1, M2`` -- ``(G1,k,lmbda1)`` and ``(G,k,lmbda2)`` difference\n matrices\n\n - ``check`` (boolean) -- if ``True`` (default), the output is checked before\n being returned.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.difference_matrices import (\n ....: difference_matrix_product,\n ....: is_difference_matrix)\n sage: G1,M1 = designs.difference_matrix(11,6)\n sage: G2,M2 = designs.difference_matrix(7,6)\n sage: G,M = difference_matrix_product(6,M1,G1,1,M2,G2,1)\n sage: G1\n Finite Field of size 11\n sage: G2\n Finite Field of size 7\n sage: G\n The Cartesian product of (Finite Field of size 11, Finite Field of size 7)\n sage: is_difference_matrix(M,G,6,1)\n True\n '
g1 = G1.cardinality()
g2 = G2.cardinality()
g = (g1 * g2)
lmbda = (lmbda1 * lmbda2)
from sage.categories.cartesian_product import cartesian_product
G = cartesian_product([G1, G2])
M = [[G((M1[j1][i], M2[j2][i])) for i in range(k)] for j1 in range((lmbda1 * g1)) for j2 in range((lmbda2 * g2))]
if (check and (not is_difference_matrix(M, G, k, lmbda, True))):
raise RuntimeError('In the product construction, Sage built something which is not a ({},{},{})-DM!'.format(g, k, lmbda))
return (G, M)
|
def difference_matrix(g, k, lmbda=1, existence=False, check=True):
'\n Return a `(g,k,\\lambda)`-difference matrix\n\n A matrix `M` is a `(g,k,\\lambda)`-difference matrix if it has size `\\lambda\n g\\times k`, its entries belong to the group `G` of cardinality `g`, and\n for any two rows `R,R\'` of `M` and `x\\in G` there are exactly `\\lambda`\n values `i` such that `R_i-R\'_i=x`.\n\n INPUT:\n\n - ``k`` -- (integer) number of columns. If ``k=None`` it is set to the\n largest value available.\n\n - ``g`` -- (integer) cardinality of the group `G`\n\n - ``lmbda`` -- (integer; default: 1) -- number of times each element of `G`\n appears as a difference.\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\n ``True`` by default.\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 .. NOTE::\n\n When ``k=None`` and ``existence=True`` the function returns an\n integer, i.e. the largest `k` such that we can build a\n `(g,k,\\lambda)`-DM.\n\n EXAMPLES::\n\n sage: G,M = designs.difference_matrix(25,10); G\n Finite Field in x of size 5^2\n sage: designs.difference_matrix(993,None,existence=1)\n 32\n\n Here we print for each `g` the maximum possible `k` for which Sage knows\n how to build a `(g,k,1)`-difference matrix::\n\n sage: for g in range(2,30):\n ....: k_max = designs.difference_matrix(g=g,k=None,existence=True)\n ....: print("{:2} {}".format(g, k_max))\n ....: _ = designs.difference_matrix(g,k_max)\n 2 2\n 3 3\n 4 4\n 5 5\n 6 2\n 7 7\n 8 8\n 9 9\n 10 2\n 11 11\n 12 6\n 13 13\n 14 2\n 15 3\n 16 16\n 17 17\n 18 2\n 19 19\n 20 4\n 21 6\n 22 2\n 23 23\n 24 8\n 25 25\n 26 2\n 27 27\n 28 6\n 29 29\n\n TESTS::\n\n sage: designs.difference_matrix(10,12,1,existence=True)\n False\n sage: designs.difference_matrix(10,12,1)\n Traceback (most recent call last):\n ...\n EmptySetError: No (10,12,1)-Difference Matrix exists as k(=12)>g(=10)\n sage: designs.difference_matrix(10,9,1,existence=True)\n Unknown\n sage: designs.difference_matrix(10,9,1)\n Traceback (most recent call last):\n ...\n NotImplementedError: I don\'t know how to build a (10,9,1)-Difference Matrix!\n '
if ((lmbda == 1) and (k is not None) and (k > g)):
if existence:
return False
raise EmptySetError('No ({},{},{})-Difference Matrix exists as k(={})>g(={})'.format(g, k, lmbda, k, g))
elif ((lmbda == 1) and is_prime_power(g)):
if (k is None):
if existence:
return g
else:
k = g
elif existence:
return True
F = FiniteField(g, 'x')
F_set = list(F)
F_k_set = F_set[:k]
G = F
M = [[(x * y) for y in F_k_set] for x in F_set]
elif (k is None):
i = 2
while (difference_matrix(g=g, k=i, lmbda=lmbda, existence=True) is True):
i += 1
return (i - 1)
elif (((g, lmbda) in DM_constructions) and (DM_constructions[(g, lmbda)][0] >= k)):
if existence:
return True
(_, f) = DM_constructions[(g, lmbda)]
(G, M) = f()
M = [R[:k] for R in M]
elif find_product_decomposition(g, k, lmbda):
if existence:
return True
((g1, lmbda1), (g2, lmbda2)) = find_product_decomposition(g, k, lmbda)
(G1, M1) = difference_matrix(g1, k, lmbda1)
(G2, M2) = difference_matrix(g2, k, lmbda2)
(G, M) = difference_matrix_product(k, M1, G1, lmbda1, M2, G2, lmbda2, check=False)
else:
if existence:
return Unknown
raise NotImplementedError("I don't know how to build a ({},{},{})-Difference Matrix!".format(g, k, lmbda))
if (check and (not is_difference_matrix(M, G, k, lmbda, 1))):
raise RuntimeError('Sage built something which is not a ({},{},{})-DM!'.format(g, k, lmbda))
return (G, M)
|
def dump_to_tmpfile(s):
'\n Utility function to dump a string to a temporary file.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs import ext_rep\n sage: file_loc = ext_rep.dump_to_tmpfile("boo")\n sage: os.remove(file_loc)\n '
file_loc = tmp_filename()
f = open(file_loc, 'w')
f.write(v2_b2_k2_icgsa)
f.close()
return file_loc
|
def check_dtrs_protocols(input_name, input_pv):
"\n Check that the XML data is in a valid format. We can currently\n handle version 2.0. For more information see\n http://designtheory.org/library/extrep/\n\n EXAMPLES::\n\n sage: from sage.combinat.designs import ext_rep\n sage: ext_rep.check_dtrs_protocols('source', '2.0')\n sage: ext_rep.check_dtrs_protocols('source', '3.0')\n Traceback (most recent call last):\n ...\n RuntimeError: Incompatible dtrs_protocols: program: 2.0 source: 3.0\n "
program_pv = DTRS_PROTOCOL
(ppv_major, ppv_minor) = program_pv.split('.')
(ipv_major, ipv_minor) = input_pv.split('.')
if ((ppv_major != ipv_major) or (int(ppv_minor) < int(ipv_minor))):
msg = ('Incompatible dtrs_protocols: program: %s %s: %s' % (program_pv, input_name, input_pv))
raise RuntimeError(msg)
|
def open_extrep_file(fname):
'\n Try to guess the compression type from extension\n and open the extrep file.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs import ext_rep\n sage: file_loc = ext_rep.dump_to_tmpfile(ext_rep.v2_b2_k2_icgsa)\n sage: proc = ext_rep.XTreeProcessor()\n sage: f = ext_rep.open_extrep_file(file_loc)\n sage: proc.parse(f)\n sage: f.close()\n sage: os.remove(file_loc)\n '
if (fname == '-'):
f = sys.stdin
else:
(root, ext) = os.path.splitext(fname)
if (ext == '.gz'):
f = gzip.GzipFile(fname)
elif (ext == '.bz2'):
f = bz2.BZ2File(fname)
else:
f = open(fname, 'rb')
return f
|
def open_extrep_url(url):
'\n Try to guess the compression type from extension\n and open the extrep file pointed to by the url. This function\n (unlike open_extrep_file) returns the uncompressed text contained in\n the file.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs import ext_rep\n sage: file_loc = ext_rep.dump_to_tmpfile(ext_rep.v2_b2_k2_icgsa)\n sage: proc = ext_rep.XTreeProcessor()\n sage: s = ext_rep.open_extrep_url("file://" + file_loc)\n sage: proc.parse(s)\n sage: os.remove(file_loc)\n\n sage: from sage.combinat.designs import ext_rep\n sage: s = ext_rep.designs_from_XML_url("http://designtheory.org/database/v-b-k/v3-b6-k2.icgsa.txt.bz2") # optional - internet\n '
f = urlopen(url)
(root, ext) = os.path.splitext(url)
if (ext == '.gz'):
raise NotImplementedError
elif (ext == '.bz2'):
return bz2.decompress(f.read())
else:
return f.read()
|
def _encode_attribute(string):
"\n Convert numbers in attributes into binary format.\n Currently integer and floating point conversions are implemented.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.ext_rep import _encode_attribute\n sage: _encode_attribute('1')\n 1\n sage: _encode_attribute('2')\n 2\n sage: _encode_attribute('12')\n 12\n sage: _encode_attribute('true')\n 'true'\n sage: _encode_attribute('A')\n 'A'\n sage: _encode_attribute('D')\n 'D'\n sage: _encode_attribute('E')\n 'E'\n "
if pattern_integer.match(string):
return int(string)
elif pattern_decimal.match(string):
return float(string)
else:
return string
|
class XTree():
"\n A lazy class to wrap a rooted tree representing an XML document.\n The tree's nodes are tuples of the structure:\n\n (name, {dictionary of attributes}, [list of children])\n\n Methods and services of an XTree object ``t``:\n\n - ``t.attribute`` -- attribute named\n - ``t.child`` -- first child named\n - ``t[i]`` -- i-th child\n - ``for child in t:`` -- iterate over ``t``'s children\n - ``len(t)`` -- number of ``t``'s children\n\n If child is not an empty subtree, return the subtree as an ``XTree``\n object. If child is an empty subtree, return ``_name`` of the subtree.\n Otherwise return the child itself.\n\n The lazy tree idea originated from a utility class of the\n pyRXP 0.9 package by Robin Becker at ReportLab.\n "
def __init__(self, node):
"\n Initialisation method given a node in an XML document.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.ext_rep import *\n sage: xt = XTree(('blocks', {'ordered': 'true'}, [('block', {}, [[0, 1, 2]]), ('block', {}, [[0, 3, 4]]), ('block', {}, [[0, 5, 6]]), ('block', {}, [[0, 7, 8]]), ('block', {}, [[0, 9, 10]]), ('block', {}, [[0, 11, 12]]), ('block', {}, [[1, 3, 5]]), ('block', {}, [[1, 4, 6]]), ('block', {}, [[1, 7, 9]]), ('block', {}, [[1, 8, 11]]), ('block', {}, [[1, 10, 12]]), ('block', {}, [[2, 3, 7]]), ('block', {}, [[2, 4, 8]]), ('block', {}, [[2, 5, 10]]), ('block', {}, [[2, 6, 12]]), ('block', {}, [[2, 9, 11]]), ('block', {}, [[3, 6, 9]]), ('block', {}, [[3, 8, 12]]), ('block', {}, [[3, 10, 11]]), ('block', {}, [[4, 5, 11]]), ('block', {}, [[4, 7, 10]]), ('block', {}, [[4, 9, 12]]), ('block', {}, [[5, 7, 12]]), ('block', {}, [[5, 8, 9]]), ('block', {}, [[6, 7, 11]]), ('block', {}, [[6, 8, 10]])]))\n sage: xt.xt_children\n [('block', {}, [[0, 1, 2]]),\n ('block', {}, [[0, 3, 4]]),\n ('block', {}, [[0, 5, 6]]),\n ('block', {}, [[0, 7, 8]]),\n ('block', {}, [[0, 9, 10]]),\n ('block', {}, [[0, 11, 12]]),\n ('block', {}, [[1, 3, 5]]),\n ('block', {}, [[1, 4, 6]]),\n ('block', {}, [[1, 7, 9]]),\n ('block', {}, [[1, 8, 11]]),\n ('block', {}, [[1, 10, 12]]),\n ('block', {}, [[2, 3, 7]]),\n ('block', {}, [[2, 4, 8]]),\n ('block', {}, [[2, 5, 10]]),\n ('block', {}, [[2, 6, 12]]),\n ('block', {}, [[2, 9, 11]]),\n ('block', {}, [[3, 6, 9]]),\n ('block', {}, [[3, 8, 12]]),\n ('block', {}, [[3, 10, 11]]),\n ('block', {}, [[4, 5, 11]]),\n ('block', {}, [[4, 7, 10]]),\n ('block', {}, [[4, 9, 12]]),\n ('block', {}, [[5, 7, 12]]),\n ('block', {}, [[5, 8, 9]]),\n ('block', {}, [[6, 7, 11]]),\n ('block', {}, [[6, 8, 10]])]\n "
if isinstance(node, str):
node = (node, {}, [])
(name, attributes, children) = node
self.xt_node = node
self.xt_name = name
self.xt_attributes = attributes
self.xt_children = children
def __repr__(self):
"\n String representation of an XTree object.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.ext_rep import *\n sage: xt = XTree(('blocks', {'ordered': 'true'}, [('block', {}, [[0, 1, 2]]), ('block', {}, [[0, 3, 4]]), ('block', {}, [[0, 5, 6]]), ('block', {}, [[0, 7, 8]]), ('block', {}, [[0, 9, 10]]), ('block', {}, [[0, 11, 12]]), ('block', {}, [[1, 3, 5]]), ('block', {}, [[1, 4, 6]]), ('block', {}, [[1, 7, 9]]), ('block', {}, [[1, 8, 11]]), ('block', {}, [[1, 10, 12]]), ('block', {}, [[2, 3, 7]]), ('block', {}, [[2, 4, 8]]), ('block', {}, [[2, 5, 10]]), ('block', {}, [[2, 6, 12]]), ('block', {}, [[2, 9, 11]]), ('block', {}, [[3, 6, 9]]), ('block', {}, [[3, 8, 12]]), ('block', {}, [[3, 10, 11]]), ('block', {}, [[4, 5, 11]]), ('block', {}, [[4, 7, 10]]), ('block', {}, [[4, 9, 12]]), ('block', {}, [[5, 7, 12]]), ('block', {}, [[5, 8, 9]]), ('block', {}, [[6, 7, 11]]), ('block', {}, [[6, 8, 10]])]))\n sage: xt.__repr__()\n 'XTree<blocks>'\n "
return ('XTree<%s>' % self.xt_name)
def __getattr__(self, attr):
"\n Return the data for the first attribute with name attr.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.ext_rep import *\n sage: xt = XTree(('blocks', {'ordered': 'true'}, [('block', {}, [[0, 1, 2]]), ('block', {}, [[0, 3, 4]]), ('block', {}, [[0, 5, 6]]), ('block', {}, [[0, 7, 8]]), ('block', {}, [[0, 9, 10]]), ('block', {}, [[0, 11, 12]]), ('block', {}, [[1, 3, 5]]), ('block', {}, [[1, 4, 6]]), ('block', {}, [[1, 7, 9]]), ('block', {}, [[1, 8, 11]]), ('block', {}, [[1, 10, 12]]), ('block', {}, [[2, 3, 7]]), ('block', {}, [[2, 4, 8]]), ('block', {}, [[2, 5, 10]]), ('block', {}, [[2, 6, 12]]), ('block', {}, [[2, 9, 11]]), ('block', {}, [[3, 6, 9]]), ('block', {}, [[3, 8, 12]]), ('block', {}, [[3, 10, 11]]), ('block', {}, [[4, 5, 11]]), ('block', {}, [[4, 7, 10]]), ('block', {}, [[4, 9, 12]]), ('block', {}, [[5, 7, 12]]), ('block', {}, [[5, 8, 9]]), ('block', {}, [[6, 7, 11]]), ('block', {}, [[6, 8, 10]])]))\n sage: xt.__getattr__('block')\n [0, 1, 2]\n "
if (attr in self.xt_attributes):
return self.xt_attributes[attr]
else:
for child in self.xt_children:
(name, attributes, children) = child
if (name == attr):
if (len(attributes) > 0):
return XTree(child)
else:
if (len(children) == 0):
return XTree(child)
grandchild = children[0]
if isinstance(grandchild, tuple):
if ((len(grandchild[1]) == 0) and (len(grandchild[2]) == 0)):
return grandchild[0]
else:
return XTree(child)
else:
return grandchild
msg = ('"%s" is not found in attributes of %s or its children.' % (attr, self))
raise AttributeError(msg)
def __getitem__(self, i):
"\n Get the ``i``-th item in the current node.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.ext_rep import *\n sage: xt = XTree(('blocks', {'ordered': 'true'}, [('block', {}, [[0, 1, 2]]), ('block', {}, [[0, 3, 4]]), ('block', {}, [[0, 5, 6]]), ('block', {}, [[0, 7, 8]]), ('block', {}, [[0, 9, 10]]), ('block', {}, [[0, 11, 12]]), ('block', {}, [[1, 3, 5]]), ('block', {}, [[1, 4, 6]]), ('block', {}, [[1, 7, 9]]), ('block', {}, [[1, 8, 11]]), ('block', {}, [[1, 10, 12]]), ('block', {}, [[2, 3, 7]]), ('block', {}, [[2, 4, 8]]), ('block', {}, [[2, 5, 10]]), ('block', {}, [[2, 6, 12]]), ('block', {}, [[2, 9, 11]]), ('block', {}, [[3, 6, 9]]), ('block', {}, [[3, 8, 12]]), ('block', {}, [[3, 10, 11]]), ('block', {}, [[4, 5, 11]]), ('block', {}, [[4, 7, 10]]), ('block', {}, [[4, 9, 12]]), ('block', {}, [[5, 7, 12]]), ('block', {}, [[5, 8, 9]]), ('block', {}, [[6, 7, 11]]), ('block', {}, [[6, 8, 10]])]))\n sage: xt.__getitem__(0)\n [0, 1, 2]\n sage: xt.__getitem__(1)\n [0, 3, 4]\n\n TESTS::\n\n sage: xt.__getitem__(119)\n Traceback (most recent call last):\n ...\n IndexError: XTree<blocks> has no index 119\n "
try:
child = self.xt_children[i]
except IndexError:
raise IndexError('{!r} has no index {}'.format(self, i))
if isinstance(child, tuple):
(name, attributes, children) = child
if (len(attributes) > 0):
return XTree(child)
else:
grandchild = children[0]
if isinstance(grandchild, tuple):
if ((len(grandchild[1]) == 0) and (len(grandchild[2]) == 0)):
return grandchild[0]
else:
return XTree(child)
else:
return grandchild
else:
return child
def __len__(self):
"\n Return the length of the current node.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.ext_rep import *\n sage: xt = XTree(('blocks', {'ordered': 'true'}, [('block', {}, [[0, 1, 2]]), ('block', {}, [[0, 3, 4]]), ('block', {}, [[0, 5, 6]]), ('block', {}, [[0, 7, 8]]), ('block', {}, [[0, 9, 10]]), ('block', {}, [[0, 11, 12]]), ('block', {}, [[1, 3, 5]]), ('block', {}, [[1, 4, 6]]), ('block', {}, [[1, 7, 9]]), ('block', {}, [[1, 8, 11]]), ('block', {}, [[1, 10, 12]]), ('block', {}, [[2, 3, 7]]), ('block', {}, [[2, 4, 8]]), ('block', {}, [[2, 5, 10]]), ('block', {}, [[2, 6, 12]]), ('block', {}, [[2, 9, 11]]), ('block', {}, [[3, 6, 9]]), ('block', {}, [[3, 8, 12]]), ('block', {}, [[3, 10, 11]]), ('block', {}, [[4, 5, 11]]), ('block', {}, [[4, 7, 10]]), ('block', {}, [[4, 9, 12]]), ('block', {}, [[5, 7, 12]]), ('block', {}, [[5, 8, 9]]), ('block', {}, [[6, 7, 11]]), ('block', {}, [[6, 8, 10]])]))\n sage: xt.__len__()\n 26\n "
return len(self.xt_children)
|
class XTreeProcessor():
'\n An incremental event-driven parser for ext-rep documents.\n The processing stages:\n\n - ``<list_of_designs ...>`` opening element.\n call-back: ``list_of_designs_proc``\n\n - ``<list_definition>`` subtree.\n call-back: ``list_definition_proc``\n\n - ``<info>`` subtree.\n call-back: ``info_proc``\n\n - iterating over ``<designs>`` processing each ``<block_design>``\n separately.\n call-back: ``block_design_proc``\n\n - finishing with closing ``</designs>`` and ``</list_of_designs>``.\n '
def _init(self):
"\n Internal initialisation for the processor of XTrees.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs import ext_rep\n sage: proc = ext_rep.XTreeProcessor()\n sage: proc._init()\n sage: proc.current_node\n ('root0', {}, [])\n "
self.current_node = ('root0', {}, [])
self.node_stack = [self.current_node]
self.in_item = False
def __init__(self):
"\n Internal initialisation for the processor of XTrees.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.ext_rep import *\n sage: proc = XTreeProcessor()\n sage: proc.current_node\n ('root0', {}, [])\n sage: proc.node_stack\n [('root0', {}, [])]\n sage: proc.in_item\n False\n "
self._init()
self.outf = sys.stdout
self.list_of_designs_start_proc = None
self.list_definition_proc = None
self.info_proc = None
self.designs_start_proc = None
self.block_design_proc = None
self.designs_end_proc = None
self.list_of_designs_end_proc = None
self.save_designs = False
self.list_of_designs = []
def _start_element(self, name, attrs):
'\n Process the start of an element with certain name and\n attributes.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.ext_rep import *\n sage: name = "block_design"\n sage: attrs = {\'b\': \'26\', \'id\': \'t2-v13-b26-r6-k3-L1-0\', \'v\': \'13\'}\n sage: proc = XTreeProcessor()\n sage: proc._start_element(name, attrs)\n sage: proc.current_node\n (\'block_design\', {\'b\': 26, \'id\': \'t2-v13-b26-r6-k3-L1-0\', \'v\': 13}, [])\n '
if ((name == 'block_design') or (name == 'info') or (name == 'list_definition')):
self.in_item = True
elif (name == 'list_of_designs'):
check_dtrs_protocols('source', attrs['dtrs_protocol'])
if self.list_of_designs_start_proc:
self.list_of_designs_start_proc(attrs)
elif (name == 'designs'):
pass
if self.in_item:
for (k, v) in attrs.items():
attrs[k] = _encode_attribute(v)
new_node = (name, attrs, [])
self.node_stack.append(new_node)
self.current_node[2].append(new_node)
self.current_node = new_node
def _end_element(self, name):
'\n Finish processing the element name.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.ext_rep import *\n sage: name = "block_design"\n sage: attrs = {\'b\': \'26\', \'id\': \'t2-v13-b26-r6-k3-L1-0\', \'v\': \'13\'}\n sage: proc = XTreeProcessor()\n sage: proc._start_element(name, attrs)\n sage: proc._end_element(name)\n sage: proc.current_node\n (\'root0\', {}, [])\n '
if self.in_item:
children = self.current_node[2]
if ((len(children) > 0) and isinstance(children[0], tuple)):
if ((children[0][0] == 'z') or (children[0][0] == 'd') or (children[0][0] == 'q')):
if (children[0][0] == 'z'):
convert = int
elif (children[0][0] == 'd'):
convert = float
else:
raise NotImplementedError('rational numbers')
ps = []
for x in children:
ps.append(convert(''.join(x[2])))
del children[:]
if ((name == 'block') or (name == 'permutation') or (name == 'preimage') or (name == 'ksubset') or (name == 'cycle_type') or (name == 'row')):
children.append(ps)
else:
children.append(ps[0])
self.node_stack.pop()
self.current_node = self.node_stack[(- 1)]
if (name == 'block_design'):
if self.block_design_proc:
self.block_design_proc(self.current_node[2][0])
if self.save_designs:
init_bd = XTree(self.current_node[2][0])
self.list_of_designs.append((init_bd.v, [b for b in init_bd.blocks]))
self._init()
elif (name == 'info'):
if self.info_proc:
self.info_proc(self.current_node[2][0])
self._init()
elif (name == 'designs'):
if self.designs_end_proc:
self.designs_end_proc()
def _char_data(self, data):
'\n Internal function to tidy up character data.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.ext_rep import *\n sage: name = "block_design"\n sage: attrs = {\'b\': \'26\', \'id\': \'t2-v13-b26-r6-k3-L1-0\', \'v\': \'13\'}\n\n sage: proc = XTreeProcessor()\n sage: proc._start_element(name, attrs)\n\n sage: proc._char_data(r" [ DESIGN-1.1, GRAPE-4.2, GAPDoc-0.9999, GAP-4.4.3]")\n sage: proc.current_node\n (\'block_design\',\n {\'b\': 26, \'id\': \'t2-v13-b26-r6-k3-L1-0\', \'v\': 13},\n [\'[ DESIGN-1.1, GRAPE-4.2, GAPDoc-0.9999, GAP-4.4.3]\'])\n '
if self.in_item:
data = data.strip()
if data:
self.current_node[2].append(data)
def parse(self, xml_source):
'\n The main parsing function. Given an XML source (either a file\n handle or a string), parse the entire XML source.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs import ext_rep\n sage: file_loc = ext_rep.dump_to_tmpfile(ext_rep.v2_b2_k2_icgsa)\n sage: proc = ext_rep.XTreeProcessor()\n sage: proc.save_designs = True\n sage: f = ext_rep.open_extrep_file(file_loc)\n sage: proc.parse(f)\n sage: f.close()\n sage: os.remove(file_loc)\n sage: proc.list_of_designs[0]\n (2, [[0, 1], [0, 1]])\n '
p = xml.parsers.expat.ParserCreate()
p.StartElementHandler = self._start_element
p.EndElementHandler = self._end_element
p.CharacterDataHandler = self._char_data
if isinstance(xml_source, (str, bytes)):
p.Parse(xml_source)
else:
p.ParseFile(xml_source)
|
def designs_from_XML(fname):
'\n Return a list of designs contained in an XML file fname. The list\n contains tuples of the form (v, bs) where v is the number of points of\n the design and bs is the list of blocks.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs import ext_rep\n sage: file_loc = ext_rep.dump_to_tmpfile(ext_rep.v2_b2_k2_icgsa)\n sage: ext_rep.designs_from_XML(file_loc)[0]\n (2, [[0, 1], [0, 1]])\n sage: os.remove(file_loc)\n\n sage: from sage.combinat.designs import ext_rep\n sage: from sage.combinat.designs.block_design import BlockDesign\n sage: file_loc = ext_rep.dump_to_tmpfile(ext_rep.v2_b2_k2_icgsa)\n sage: v, blocks = ext_rep.designs_from_XML(file_loc)[0]\n sage: d = BlockDesign(v, blocks)\n sage: d.blocks()\n [[0, 1], [0, 1]]\n sage: d.is_t_design(t=2)\n True\n sage: d.is_t_design(return_parameters=True)\n (True, (2, 2, 2, 2))\n '
proc = XTreeProcessor()
proc.save_designs = True
f = open_extrep_file(fname)
proc.parse(f)
f.close()
return proc.list_of_designs
|
def designs_from_XML_url(url):
'\n Return a list of designs contained in an XML file named by a URL.\n The list contains tuples of the form (v, bs) where v is the number\n of points of the design and bs is the list of blocks.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs import ext_rep\n sage: file_loc = ext_rep.dump_to_tmpfile(ext_rep.v2_b2_k2_icgsa)\n sage: ext_rep.designs_from_XML_url("file://" + file_loc)[0]\n (2, [[0, 1], [0, 1]])\n sage: os.remove(file_loc)\n\n sage: from sage.combinat.designs import ext_rep\n sage: ext_rep.designs_from_XML_url("http://designtheory.org/database/v-b-k/v3-b6-k2.icgsa.txt.bz2") # optional - internet\n [(3, [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 2]]),\n (3, [[0, 1], [0, 1], [0, 1], [0, 1], [0, 2], [0, 2]]),\n (3, [[0, 1], [0, 1], [0, 1], [0, 1], [0, 2], [1, 2]]),\n (3, [[0, 1], [0, 1], [0, 1], [0, 2], [0, 2], [0, 2]]),\n (3, [[0, 1], [0, 1], [0, 1], [0, 2], [0, 2], [1, 2]]),\n (3, [[0, 1], [0, 1], [0, 2], [0, 2], [1, 2], [1, 2]])]\n '
proc = XTreeProcessor()
proc.save_designs = True
s = open_extrep_url(url)
proc.parse(s)
return proc.list_of_designs
|
def group_divisible_design(v, K, G, existence=False, check=False):
'\n Return a `(v,K,G)`-Group Divisible Design.\n\n A `(v,K,G)`-GDD is a pair `(\\mathcal G, \\mathcal B)` where:\n\n - `\\mathcal G` is a partition of `X=\\bigcup \\mathcal G` where `|X|=v`\n\n - `\\forall S\\in \\mathcal G, |S| \\in G`\n\n - `\\forall S\\in \\mathcal B, |S| \\in K`\n\n - `\\mathcal G\\cup \\mathcal B` is a `(v,K\\cup G)`-PBD\n\n For more information, see the documentation of\n :class:`~sage.combinat.designs.incidence_structures.GroupDivisibleDesign` or\n :class:`~sage.combinat.designs.bibd.PairwiseBalancedDesign`.\n\n INPUT:\n\n - ``v`` (integer)\n\n - ``K,G`` (sets of 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 - ``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 .. NOTE::\n\n The GDD returned by this function are defined on ``range(v)``, and its\n groups are sets of consecutive integers.\n\n EXAMPLES::\n\n sage: designs.group_divisible_design(14,{4},{2})\n Group Divisible Design on 14 points of type 2^7\n '
G = list(set(G))
K = list(set(K))
blocks = None
if ((len(G) == 1 == len(K)) and ((G[0] + 1) in K)):
from .bibd import balanced_incomplete_block_design
k = K[0]
if existence:
return balanced_incomplete_block_design((v + 1), k, existence=True)
BIBD = balanced_incomplete_block_design((v + 1), k)
groups = [[x for x in S if (x != v)] for S in BIBD if (v in S)]
d = {p: i for (i, p) in enumerate(sum(groups, []))}
d[v] = v
BIBD.relabel(d)
groups = [list(range(((k - 1) * i), ((k - 1) * (i + 1)))) for i in range((v // (k - 1)))]
blocks = [S for S in BIBD if (v not in S)]
elif (((v % 2) == 0) and (K == [4]) and (G == [2]) and GDD_4_2((v // 2), existence=True)):
if existence:
return True
return GDD_4_2((v // 2), check=check)
elif ((len(G) == 1 == len(K)) and ((K[0] * G[0]) == v)):
from .orthogonal_arrays import transversal_design
return transversal_design(k=K[0], n=G[0], existence=existence)
if blocks:
return GroupDivisibleDesign(v, groups=groups, blocks=blocks, G=G, K=K, check=check, copy=True)
if existence:
return Unknown
raise NotImplementedError
|
def GDD_4_2(q, existence=False, check=True):
'\n Return a `(2q,\\{4\\},\\{2\\})`-GDD for `q` a prime power with `q\\equiv 1\\pmod{6}`.\n\n This method implements Lemma VII.5.17 from [BJL99] (p.495).\n\n INPUT:\n\n - ``q`` (integer)\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 - ``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.group_divisible_designs import GDD_4_2\n sage: GDD_4_2(7,existence=True)\n True\n sage: GDD_4_2(7)\n Group Divisible Design on 14 points of type 2^7\n sage: GDD_4_2(8,existence=True)\n Unknown\n sage: GDD_4_2(8)\n Traceback (most recent call last):\n ...\n NotImplementedError\n '
if ((q <= 1) or ((q % 6) != 1) or (not is_prime_power(q))):
if existence:
return Unknown
raise NotImplementedError
if existence:
return True
from sage.rings.finite_rings.finite_field_constructor import FiniteField
G = FiniteField(q, 'x')
w = G.primitive_element()
e = (w ** ((q - 1) // 3))
first_class = [[(0, 0), (1, (w ** i)), (1, (e * (w ** i))), (1, ((e * e) * (w ** i)))] for i in range(((q - 1) // 6))]
label = {p: i for (i, p) in enumerate(G)}
classes = [[[((2 * label[(x[1] + g)]) + ((x[0] + j) % 2)) for x in S] for S in first_class] for g in G for j in range(2)]
return GroupDivisibleDesign((2 * q), groups=[[i, (i + 1)] for i in range(0, (2 * q), 2)], blocks=sum(classes, []), K=[4], G=[2], check=check, copy=False)
|
class GroupDivisibleDesign(IncidenceStructure):
"\n Group Divisible Design (GDD)\n\n Let `K` and `G` be sets of positive integers and let `\\lambda` be a positive\n integer. A Group Divisible Design of index `\\lambda` and order `v` is a\n triple `(V,\\mathcal G,\\mathcal B)` where:\n\n - `V` is a set of cardinality `v`\n\n - `\\mathcal G` is a partition of `V` into groups whose size belongs to `G`\n\n - `\\mathcal B` is a family of subsets of `V` whose size belongs to `K` such\n that any two points `p_1,p_2\\in V` from different groups appear\n simultaneously in exactly `\\lambda` elements of `\\mathcal B`. Besides, a\n group and a block intersect on at most one point.\n\n If `K=\\{k_1,...,k_l\\}` and `G` has exactly `m_i` groups of cardinality `k_i`\n then `G` is said to have type `k_1^{m_1}...k_l^{m_l}`.\n\n INPUT:\n\n - ``points`` -- the underlying set. If ``points`` is an integer `v`, then\n the set is considered to be `\\{0, ..., v-1\\}`.\n\n - ``groups`` -- the groups of the design. Set to ``None`` for an automatic\n guess (this triggers ``check=True`` and can thus cost some time).\n\n - ``blocks`` -- collection of blocks\n\n - ``G`` -- list of integers of which the sizes of the groups must be\n elements. Set to ``None`` (automatic guess) by default.\n\n - ``K`` -- list of integers of which the sizes of the blocks must be\n elements. Set to ``None`` (automatic guess) by default.\n\n - ``lambd`` (integer) -- value of `\\lambda`, set to `1` by default.\n\n - ``check`` (boolean) -- whether to check that the design is indeed a `GDD`\n with the right parameters. Set to ``True`` by default.\n\n - ``copy`` -- (use with caution) if set to ``False`` then ``blocks`` must be\n a list of lists of integers. The list will not be copied but will be\n modified in place (each block is sorted, and the whole list is\n sorted). Your ``blocks`` object will become the instance's internal data.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.group_divisible_designs import GroupDivisibleDesign\n sage: TD = designs.transversal_design(4,10)\n sage: groups = [list(range(i*10,(i+1)*10)) for i in range(4)]\n sage: GDD = GroupDivisibleDesign(40,groups,TD); GDD\n Group Divisible Design on 40 points of type 10^4\n\n With unspecified groups::\n\n sage: # needs sage.schemes\n sage: D = designs.transversal_design(4,3).relabel(list('abcdefghiklm'),inplace=False).blocks()\n sage: GDD = GroupDivisibleDesign('abcdefghiklm',None,D)\n sage: sorted(GDD.groups())\n [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['k', 'l', 'm']]\n "
def __init__(self, points, groups, blocks, G=None, K=None, lambd=1, check=True, copy=True, **kwds):
'\n Constructor function\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.group_divisible_designs import GroupDivisibleDesign\n sage: TD = designs.transversal_design(4,10)\n sage: groups = [list(range(i*10,(i+1)*10)) for i in range(4)]\n sage: GDD = GroupDivisibleDesign(40,groups,TD); GDD\n Group Divisible Design on 40 points of type 10^4\n '
from .designs_pyx import is_group_divisible_design
self._lambd = lambd
IncidenceStructure.__init__(self, points, blocks, copy=copy, check=False, **kwds)
if ((groups is None) or ((copy is False) and (self._point_to_index is None))):
self._groups = groups
elif (self._point_to_index is None):
self._groups = [g[:] for g in groups]
else:
self._groups = [[self._point_to_index[x] for x in g] for g in groups]
if (check or (groups is None)):
is_gdd = is_group_divisible_design(self._groups, self._blocks, self.num_points(), G, K, lambd, verbose=1)
assert is_gdd
if (groups is None):
self._groups = is_gdd[1]
def groups(self):
"\n Return the groups of the Group-Divisible Design.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.group_divisible_designs import GroupDivisibleDesign\n sage: TD = designs.transversal_design(4,10)\n sage: groups = [list(range(i*10,(i+1)*10)) for i in range(4)]\n sage: GDD = GroupDivisibleDesign(40,groups,TD); GDD\n Group Divisible Design on 40 points of type 10^4\n sage: GDD.groups()\n [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],\n [30, 31, 32, 33, 34, 35, 36, 37, 38, 39]]\n\n TESTS:\n\n Non-integer ground set::\n\n sage: # needs sage.schemes\n sage: TD = designs.transversal_design(5,5)\n sage: TD.relabel({i: chr(97+i) for i in range(25)})\n sage: TD.groups()\n [['a', 'b', 'c', 'd', 'e'],\n ['f', 'g', 'h', 'i', 'j'],\n ['k', 'l', 'm', 'n', 'o'],\n ['p', 'q', 'r', 's', 't'],\n ['u', 'v', 'w', 'x', 'y']]\n "
if (self._point_to_index is None):
return [list(g) for g in self._groups]
else:
return [[self._points[i] for i in g] for g in self._groups]
def __repr__(self):
'\n Return a string that describes ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.group_divisible_designs import GroupDivisibleDesign\n sage: TD = designs.transversal_design(4,10)\n sage: groups = [list(range(i*10,(i+1)*10)) for i in range(4)]\n sage: GDD = GroupDivisibleDesign(40,groups,TD); GDD\n Group Divisible Design on 40 points of type 10^4\n '
group_sizes = [len(g) for g in self._groups]
gdd_type = ('{}^{}'.format(s, group_sizes.count(s)) for s in sorted(set(group_sizes)))
gdd_type = '.'.join(gdd_type)
if (not gdd_type):
gdd_type = '1^0'
v = self.num_points()
return 'Group Divisible Design on {} points of type {}'.format(v, gdd_type)
|
class IncidenceStructure():
'\n A base class for incidence structures (i.e. hypergraphs, i.e. set systems)\n\n An incidence structure (i.e. hypergraph, i.e. set system) can be defined\n from a collection of blocks (i.e. sets, i.e. edges), optionally with an\n explicit ground set (i.e. point set, i.e. vertex set). Alternatively they\n can be defined from a binary incidence matrix.\n\n INPUT:\n\n - ``points`` -- (i.e. ground set, i.e. vertex set) the underlying set. If\n ``points`` is an integer `v`, then the set is considered to be `\\{0, ...,\n v-1\\}`.\n\n .. NOTE::\n\n The following syntax, where ``points`` is omitted, automatically\n defines the ground set as the union of the blocks::\n\n sage: H = IncidenceStructure([[\'a\',\'b\',\'c\'],[\'c\',\'d\',\'e\']])\n sage: sorted(H.ground_set())\n [\'a\', \'b\', \'c\', \'d\', \'e\']\n\n - ``blocks`` -- (i.e. edges, i.e. sets) the blocks defining the incidence\n structure. Can be any iterable.\n\n - ``incidence_matrix`` -- a binary incidence matrix. Each column represents\n a set.\n\n - ``name`` (a string, such as "Fano plane").\n\n - ``check`` -- whether to check the input\n\n - ``copy`` -- (use with caution) if set to ``False`` then ``blocks`` must be\n a list of lists of integers. The list will not be copied but will be\n modified in place (each block is sorted, and the whole list is\n sorted). Your ``blocks`` object will become the\n :class:`IncidenceStructure` instance\'s internal data.\n\n EXAMPLES:\n\n An incidence structure can be constructed by giving the number of points and\n the list of blocks::\n\n sage: IncidenceStructure(7, [[0,1,2],[0,3,4],[0,5,6],[1,3,5],[1,4,6],[2,3,6],[2,4,5]])\n Incidence structure with 7 points and 7 blocks\n\n Only providing the set of blocks is sufficient. In this case, the ground set\n is defined as the union of the blocks::\n\n sage: IncidenceStructure([[1,2,3],[2,3,4]])\n Incidence structure with 4 points and 2 blocks\n\n Or by its adjacency matrix (a `\\{0,1\\}`-matrix in which rows are indexed by\n points and columns by blocks)::\n\n sage: m = matrix([[0,1,0],[0,0,1],[1,0,1],[1,1,1]]) # needs sage.modules\n sage: IncidenceStructure(m) # needs sage.modules\n Incidence structure with 4 points and 3 blocks\n\n The points can be any (hashable) object::\n\n sage: V = [(0,\'a\'),(0,\'b\'),(1,\'a\'),(1,\'b\')]\n sage: B = [(V[0],V[1],V[2]), (V[1],V[2]), (V[0],V[2])]\n sage: I = IncidenceStructure(V, B)\n sage: I.ground_set()\n [(0, \'a\'), (0, \'b\'), (1, \'a\'), (1, \'b\')]\n sage: I.blocks()\n [[(0, \'a\'), (0, \'b\'), (1, \'a\')], [(0, \'a\'), (1, \'a\')], [(0, \'b\'), (1, \'a\')]]\n\n The order of the points and blocks does not matter as they are sorted on\n input (see :trac:`11333`)::\n\n sage: A = IncidenceStructure([0,1,2], [[0],[0,2]])\n sage: B = IncidenceStructure([1,0,2], [[0],[2,0]])\n sage: B == A\n True\n\n sage: C = BlockDesign(2, [[0], [1,0]])\n sage: D = BlockDesign(2, [[0,1], [0]])\n sage: C == D\n True\n\n If you care for speed, you can set ``copy`` to ``False``, but in that\n case, your input must be a list of lists and the ground set must be `{0,\n ..., v-1}`::\n\n sage: blocks = [[0,1],[2,0],[1,2]] # a list of lists of integers\n sage: I = IncidenceStructure(3, blocks, copy=False)\n sage: I._blocks is blocks\n True\n '
def __init__(self, points=None, blocks=None, incidence_matrix=None, name=None, check=True, copy=True):
"\n TESTS::\n\n sage: IncidenceStructure(3, [[4]])\n Traceback (most recent call last):\n ...\n ValueError: Block [4] is not contained in the point set\n\n sage: IncidenceStructure(3, [[0,1],[0,2]], check=True)\n Incidence structure with 3 points and 2 blocks\n\n sage: IncidenceStructure(2, [[0,1,2,3,4,5]], check=False)\n Incidence structure with 2 points and 1 blocks\n\n We avoid to convert to integers when the points are not (but compare\n equal to integers because of coercion)::\n\n sage: # needs sage.rings.finite_rings\n sage: V = GF(5)\n sage: e0,e1,e2,e3,e4 = V\n sage: [e0,e1,e2,e3,e4] == list(range(5)) # coercion makes them equal\n True\n sage: blocks = [[e0,e1,e2],[e0,e1],[e2,e4]]\n sage: I = IncidenceStructure(V, blocks)\n sage: type(I.ground_set()[0])\n <class 'sage.rings.finite_rings.integer_mod.IntegerMod_int'>\n sage: type(I.blocks()[0][0])\n <class 'sage.rings.finite_rings.integer_mod.IntegerMod_int'>\n\n TESTS::\n\n sage: IncidenceStructure([])\n Incidence structure with 0 points and 0 blocks\n "
from sage.structure.element import Matrix
if isinstance(points, Matrix):
assert (incidence_matrix is None), "'incidence_matrix' cannot be defined when 'points' is a matrix"
assert (blocks is None), "'blocks' cannot be defined when 'points' is a matrix"
incidence_matrix = points
points = blocks = None
elif ((points is not None) and (blocks is None)):
blocks = points
points = set().union(*blocks)
if points:
assert (incidence_matrix is None), "'incidence_matrix' cannot be defined when 'points' is defined"
if incidence_matrix:
from sage.matrix.constructor import matrix
M = matrix(incidence_matrix)
v = M.nrows()
self._points = list(range(v))
self._point_to_index = None
self._blocks = sorted((M.nonzero_positions_in_column(i) for i in range(M.ncols())))
else:
if isinstance(points, (int, Integer)):
self._points = list(range(points))
self._point_to_index = None
else:
self._points = list(points)
if ((self._points == list(range(len(points)))) and all((isinstance(x, (int, Integer)) for x in self._points))):
self._point_to_index = None
else:
self._point_to_index = {e: i for (i, e) in enumerate(self._points)}
if check:
for block in blocks:
if any(((x not in self._points) for x in block)):
raise ValueError('Block {} is not contained in the point set'.format(block))
if (len(block) != len(set(block))):
raise ValueError('Repeated element in block {}'.format(block))
if self._point_to_index:
blocks = [sorted((self._point_to_index[e] for e in block)) for block in blocks]
elif copy:
blocks = [sorted(block) for block in blocks]
else:
for b in blocks:
b.sort()
blocks.sort()
self._blocks = blocks
self._name = (str(name) if (name is not None) else 'IncidenceStructure')
self._classes = None
self._canonical_label = None
def __iter__(self):
"\n Iterator over the blocks.\n\n EXAMPLES::\n\n sage: sts = designs.steiner_triple_system(9)\n sage: list(sts)\n [[0, 1, 5], [0, 2, 4], [0, 3, 6], [0, 7, 8], [1, 2, 3], [1, 4, 7],\n [1, 6, 8], [2, 5, 8], [2, 6, 7], [3, 4, 8], [3, 5, 7], [4, 5, 6]]\n\n sage: b = IncidenceStructure('ab', ['a','ab'])\n sage: it = iter(b)\n sage: next(it)\n ['a']\n sage: next(it)\n ['a', 'b']\n "
if (self._point_to_index is None):
for b in self._blocks:
(yield b[:])
else:
for b in self._blocks:
(yield [self._points[i] for i in b])
def __repr__(self):
'\n A print method.\n\n EXAMPLES::\n\n sage: BD = IncidenceStructure(7,[[0,1,2],[0,3,4],[0,5,6],[1,3,5],[1,4,6],[2,3,6],[2,4,5]])\n sage: BD\n Incidence structure with 7 points and 7 blocks\n '
return 'Incidence structure with {} points and {} blocks'.format(self.num_points(), self.num_blocks())
__str__ = __repr__
def __eq__(self, other):
'\n Test whether the two incidence structures are equal.\n\n TESTS::\n\n sage: blocks = [[0,1,2],[0,3,4],[0,5,6],[1,3,5],[1,4,6],[2,3,6],[2,4,5]]\n sage: BD1 = IncidenceStructure(7, blocks)\n sage: M = BD1.incidence_matrix() # needs sage.modules\n sage: BD2 = IncidenceStructure(incidence_matrix=M) # needs sage.modules\n sage: BD1 == BD2 # needs sage.modules\n True\n\n sage: e1 = frozenset([0,1])\n sage: e2 = frozenset([2])\n sage: sorted([e1,e2]) == [e1,e2]\n True\n sage: sorted([e2,e1]) == [e2,e1]\n True\n sage: I1 = IncidenceStructure([e1,e2], [[e1],[e1,e2]])\n sage: I2 = IncidenceStructure([e1,e2], [[e2,e1],[e1]])\n sage: I3 = IncidenceStructure([e2,e1], [[e1,e2],[e1]])\n sage: I1 == I2 and I2 == I1 and I1 == I3 and I3 == I1 and I2 == I3 and I3 == I2\n True\n '
if (not isinstance(other, IncidenceStructure)):
return False
if (self._points == other._points):
return (self._blocks == other._blocks)
if ((self.num_points() != other.num_points()) or (self.num_blocks() != other.num_blocks())):
return False
p_to_i = (self._point_to_index if self._point_to_index else list(range(self.num_points())))
if any(((p not in p_to_i) for p in other.ground_set())):
return False
other_blocks = sorted((sorted((p_to_i[p] for p in b)) for b in other.blocks()))
return (self._blocks == other_blocks)
def __ne__(self, other):
'\n Difference test.\n\n EXAMPLES::\n\n sage: BD1 = IncidenceStructure(7, [[0,1,2],[0,3,4],[0,5,6],[1,3,5],[1,4,6],[2,3,6],[2,4,5]])\n sage: M = BD1.incidence_matrix() # needs sage.modules\n sage: BD2 = IncidenceStructure(incidence_matrix=M) # needs sage.modules\n sage: BD1 != BD2 # needs sage.modules\n False\n '
return (not (self == other))
def __contains__(self, block):
'\n Tests if a block belongs to the incidence structure\n\n INPUT:\n\n - ``block`` -- a block.\n\n EXAMPLES::\n\n sage: [1,2,3,4] in IncidenceStructure([[1,2,3,4]])\n True\n sage: [1,2,4,3] in IncidenceStructure([[1,2,3,4]])\n True\n sage: [1,2,"3",4] in IncidenceStructure([[1,2,3,4]])\n False\n sage: [1,2,"3",4] in IncidenceStructure([[1,2,"3",4]])\n True\n\n More complicated examples::\n\n sage: str="I had a dream of a time when a 3-lines patch does not kill one hour"\n sage: sets = Subsets(str.split(), 4)\n sage: IS = IncidenceStructure(sets) # a complete 4-uniform hypergraph\n sage: ["I", "dream", "of", "one"] in IS\n True\n sage: ["does", "patch", "kill", "dream"] in IS\n True\n sage: ["Am", "I", "finally", "done ?"] in IS\n False\n sage: IS = designs.ProjectiveGeometryDesign(3, 1, GF(2), # needs sage.combinat\n ....: point_coordinates=False)\n sage: [3,8,7] in IS # needs sage.combinat\n True\n sage: [3,8,9] in IS # needs sage.combinat\n False\n '
try:
iter(block)
except TypeError:
return False
if (self._point_to_index is not None):
try:
block = [self._point_to_index[x] for x in block]
except KeyError:
return False
return (sorted(block) in self._blocks)
def canonical_label(self):
'\n Return a canonical label for the incidence structure.\n\n A canonical label is relabeling of the points into integers\n `\\{0,...,n-1\\}` such that isomorphic incidence structures are\n relabelled to equal objects.\n\n EXAMPLES::\n\n sage: # needs sage.schemes\n sage: fano1 = designs.balanced_incomplete_block_design(7,3)\n sage: fano2 = designs.projective_plane(2)\n sage: fano1 == fano2\n False\n sage: fano1.relabel(fano1.canonical_label())\n sage: fano2.relabel(fano2.canonical_label())\n sage: fano1 == fano2\n True\n '
if (self._canonical_label is None):
from sage.graphs.graph import Graph
g = Graph()
n = self.num_points()
g.add_edges((((i + n), x) for (i, b) in enumerate(self._blocks) for x in b))
canonical_label = g.canonical_label([list(range(n)), list(range(n, (n + self.num_blocks())))], certificate=True)[1]
canonical_label = [canonical_label[x] for x in range(n)]
self._canonical_label = canonical_label
return dict(zip(self._points, self._canonical_label))
def is_isomorphic(self, other, certificate=False):
'\n Return whether the two incidence structures are isomorphic.\n\n INPUT:\n\n - ``other`` -- an incidence structure.\n\n - ``certificate`` (boolean) -- whether to return an\n isomorphism from ``self`` to ``other`` instead of a boolean\n answer.\n\n EXAMPLES::\n\n sage: # needs sage.schemes\n sage: fano1 = designs.balanced_incomplete_block_design(7,3)\n sage: fano2 = designs.projective_plane(2)\n sage: fano1.is_isomorphic(fano2)\n True\n sage: fano1.is_isomorphic(fano2,certificate=True)\n {0: 0, 1: 1, 2: 2, 3: 6, 4: 4, 5: 3, 6: 5}\n\n TESTS::\n\n sage: # needs sage.symbolic\n sage: IS = IncidenceStructure([["A",5,pi],["A",5,"Wouhou"],\n ....: ["A","Wouhou",(9,9)],[pi,12]])\n sage: IS2 = IS.copy()\n sage: IS2.relabel(IS2.canonical_label())\n sage: IS.is_isomorphic(IS2)\n True\n sage: canon = IS.is_isomorphic(IS2, certificate=True)\n sage: IS.relabel(canon)\n sage: IS==IS2\n True\n\n sage: IS2 = IncidenceStructure([[1,2]])\n sage: IS2.is_isomorphic(IS) # needs sage.symbolic\n False\n sage: IS2.is_isomorphic(IS, certificate=True) # needs sage.symbolic\n {}\n\n Checking whether two :class:`IncidenceStructure` are isomorphic\n incidentally computes their canonical label (if necessary). Thus,\n subsequent calls to :meth:`is_isomorphic` will be faster::\n\n sage: # needs sage.schemes\n sage: IS1 = designs.projective_plane(3)\n sage: IS2 = IS1.relabel(Permutations(IS1.ground_set()).random_element(),\n ....: inplace=False)\n sage: IS2 = IncidenceStructure(IS2.blocks())\n sage: IS1._canonical_label is None and IS2._canonical_label is None\n True\n sage: IS1.is_isomorphic(IS2)\n True\n sage: IS1._canonical_label is None or IS2._canonical_label is None\n False\n\n '
if ((self.num_points() != other.num_points()) or (self.num_blocks() != other.num_blocks()) or (sorted(self.block_sizes()) != sorted(other.block_sizes()))):
return ({} if certificate else False)
A_canon = self.canonical_label()
B_canon = other.canonical_label()
A = self.relabel(A_canon, inplace=False)
B = other.relabel(B_canon, inplace=False)
if (A == B):
if certificate:
B_canon_rev = {y: x for (x, y) in B_canon.items()}
return {x: B_canon_rev[xint] for (x, xint) in A_canon.items()}
else:
return True
else:
return ({} if certificate else False)
def isomorphic_substructures_iterator(self, H2, induced=False):
"\n Iterates over all copies of ``H2`` contained in ``self``.\n\n A hypergraph `H_1` contains an isomorphic copy of a hypergraph `H_2` if\n there exists an injection `f:V(H_2)\\mapsto V(H_1)` such that for any set\n `S_2\\in E(H_2)` the set `S_1=f(S2)` belongs to `E(H_1)`.\n\n It is an *induced* copy if no other set of `E(H_1)` is contained in\n `f(V(H_2))`, i.e. `|E(H_2)|=\\{S:S\\in E(H_1)\\text{ and }f(V(H_2))\\}`.\n\n This function lists all such injections. In particular, the number of\n copies of `H` in itself is equal to *the size of its automorphism\n group*.\n\n See :mod:`~sage.combinat.designs.subhypergraph_search` for more information.\n\n INPUT:\n\n - ``H2`` an :class:`IncidenceStructure` object.\n\n - ``induced`` (boolean) -- whether to require the copies to be\n induced. Set to ``False`` by default.\n\n EXAMPLES:\n\n How many distinct `C_5` in Petersen's graph ? ::\n\n sage: P = graphs.PetersenGraph()\n sage: C = graphs.CycleGraph(5)\n sage: IP = IncidenceStructure(P.edges(sort=True, labels=False))\n sage: IC = IncidenceStructure(C.edges(sort=True, labels=False))\n sage: sum(1 for _ in IP.isomorphic_substructures_iterator(IC))\n 120\n\n As the automorphism group of `C_5` has size 10, the number of distinct\n unlabelled copies is 12. Let us check that all functions returned\n correspond to an actual `C_5` subgraph::\n\n sage: for f in IP.isomorphic_substructures_iterator(IC):\n ....: assert all(P.has_edge(f[x],f[y]) for x,y in C.edges(sort=True, labels=False))\n\n The number of induced copies, in this case, is the same::\n\n sage: sum(1 for _ in IP.isomorphic_substructures_iterator(IC,induced=True))\n 120\n\n They begin to differ if we make one vertex universal::\n\n sage: P.add_edges([(0,x) for x in P], loops=False)\n sage: IP = IncidenceStructure(P.edges(sort=True, labels=False))\n sage: IC = IncidenceStructure(C.edges(sort=True, labels=False))\n sage: sum(1 for _ in IP.isomorphic_substructures_iterator(IC))\n 420\n sage: sum(1 for _ in IP.isomorphic_substructures_iterator(IC,induced=True))\n 60\n\n The number of copies of `H` in itself is the size of its automorphism\n group::\n\n sage: H = designs.projective_plane(3) # needs sage.schemes\n sage: sum(1 for _ in H.isomorphic_substructures_iterator(H)) # needs sage.schemes\n 5616\n sage: H.automorphism_group().cardinality() # needs sage.groups sage.schemes\n 5616\n "
from sage.combinat.designs.subhypergraph_search import SubHypergraphSearch
return SubHypergraphSearch(self, H2, induced=induced)
def copy(self):
'\n Return a copy of the incidence structure.\n\n EXAMPLES::\n\n sage: IS = IncidenceStructure([[1,2,3,"e"]],name="Test")\n sage: IS\n Incidence structure with 4 points and 1 blocks\n sage: copy(IS)\n Incidence structure with 4 points and 1 blocks\n sage: [1, 2, 3, \'e\'] in copy(IS)\n True\n sage: copy(IS)._name\n \'Test\'\n '
IS = IncidenceStructure(self._blocks, name=self._name, check=False)
IS.relabel(dict(zip(range(self.num_points()), self._points)))
IS._canonical_label = (None if (self._canonical_label is None) else self._canonical_label[:])
return IS
__copy__ = copy
def induced_substructure(self, points):
'\n Return the substructure induced by a set of points.\n\n The substructure induced in `\\mathcal H` by a set `X\\subseteq V(\\mathcal\n H)` of points is the incidence structure `\\mathcal H_X` defined on `X`\n whose sets are all `S\\in \\mathcal H` such that `S\\subseteq X`.\n\n INPUT:\n\n - ``points`` -- a set of points.\n\n .. NOTE::\n\n This method goes over all sets of ``self`` before building a new\n :class:`IncidenceStructure` (which involves some relabelling and\n sorting). It probably should not be called in a performance-critical\n code.\n\n EXAMPLES:\n\n A Fano plane with one point removed::\n\n sage: F = designs.steiner_triple_system(7)\n sage: F.induced_substructure([0..5])\n Incidence structure with 6 points and 4 blocks\n\n TESTS::\n\n sage: F.induced_substructure([0..50])\n Traceback (most recent call last):\n ...\n ValueError: 7 is not a point of the incidence structure\n sage: F.relabel(dict(enumerate("abcdefg")))\n sage: F.induced_substructure("abc")\n Incidence structure with 3 points and ...\n sage: F.induced_substructure("Y")\n Traceback (most recent call last):\n ...\n ValueError: \'Y\' is not a point of the incidence structure\n '
if (self._point_to_index is None):
n = self.num_points()
for x in points:
x = int(x)
if ((x < 0) or (x >= n)):
raise ValueError('{} is not a point of the incidence structure'.format(x))
int_points = points
else:
try:
int_points = [self._point_to_index[x] for x in points]
except KeyError as bad_pt:
raise ValueError('{} is not a point of the incidence structure'.format(bad_pt))
int_points = set(int_points)
return IncidenceStructure(points, [[self._points[x] for x in S] for S in self._blocks if int_points.issuperset(S)])
def trace(self, points, min_size=1, multiset=True):
'\n Return the trace of a set of points.\n\n Given an hypergraph `\\mathcal H`, the *trace* of a set `X` of points in\n `\\mathcal H` is the hypergraph whose blocks are all non-empty `S \\cap X`\n where `S \\in \\mathcal H`.\n\n INPUT:\n\n - ``points`` -- a set of points.\n\n - ``min_size`` (integer; default 1) -- minimum size of the sets to\n keep. By default all empty sets are discarded, i.e. ``min_size=1``.\n\n - ``multiset`` (boolean; default ``True``) -- whether to keep multiple\n copies of the same set.\n\n .. NOTE::\n\n This method goes over all sets of ``self`` before building a new\n :class:`IncidenceStructure` (which involves some relabelling and\n sorting). It probably should not be called in a performance-critical\n code.\n\n EXAMPLES:\n\n A Baer subplane of order 2 (i.e. a Fano plane) in a projective plane of order 4::\n\n sage: # needs sage.schemes\n sage: P4 = designs.projective_plane(4)\n sage: F = designs.projective_plane(2)\n sage: for x in Subsets(P4.ground_set(),7):\n ....: if P4.trace(x,min_size=2).is_isomorphic(F):\n ....: break\n sage: subplane = P4.trace(x,min_size=2); subplane\n Incidence structure with 7 points and 7 blocks\n sage: subplane.is_isomorphic(F)\n True\n\n TESTS::\n\n sage: # needs sage.schemes\n sage: F.trace([0..50])\n Traceback (most recent call last):\n ...\n ValueError: 7 is not a point of the incidence structure\n sage: F.relabel(dict(enumerate("abcdefg")))\n sage: F.trace("abc")\n Incidence structure with 3 points and ...\n sage: F.trace("Y")\n Traceback (most recent call last):\n ...\n ValueError: \'Y\' is not a point of the incidence structure\n '
if (self._point_to_index is None):
n = self.num_points()
int_points = frozenset((int(x) for x in points))
for x in int_points:
if ((x < 0) or (x >= n)):
raise ValueError('{} is not a point of the incidence structure'.format(x))
else:
try:
int_points = frozenset((self._point_to_index[x] for x in points))
except KeyError as bad_pt:
raise ValueError('{} is not a point of the incidence structure'.format(bad_pt))
blocks = [int_points.intersection(S) for S in self._blocks]
if min_size:
blocks = [S for S in blocks if (len(S) >= min_size)]
if (not multiset):
blocks = set(blocks)
IS = IncidenceStructure(blocks)
IS.relabel({i: self._points[i] for i in int_points})
return IS
def ground_set(self):
'\n Return the ground set (i.e the list of points).\n\n EXAMPLES::\n\n sage: IncidenceStructure(3, [[0,1],[0,2]]).ground_set()\n [0, 1, 2]\n '
return self._points[:]
def num_points(self):
'\n Return the size of the ground set.\n\n EXAMPLES::\n\n sage: designs.DesarguesianProjectivePlaneDesign(2).num_points()\n 7\n sage: B = IncidenceStructure(4, [[0,1],[0,2],[0,3],[1,2], [1,2,3]])\n sage: B.num_points()\n 4\n '
return len(self._points)
def num_blocks(self):
'\n Return the number of blocks.\n\n EXAMPLES::\n\n sage: designs.DesarguesianProjectivePlaneDesign(2).num_blocks()\n 7\n sage: B = IncidenceStructure(4, [[0,1],[0,2],[0,3],[1,2], [1,2,3]])\n sage: B.num_blocks()\n 5\n '
return len(self._blocks)
def blocks(self):
'\n Return the list of blocks.\n\n EXAMPLES::\n\n sage: BD = IncidenceStructure(7,[[0,1,2],[0,3,4],[0,5,6],[1,3,5],[1,4,6],[2,3,6],[2,4,5]])\n sage: BD.blocks()\n [[0, 1, 2], [0, 3, 4], [0, 5, 6], [1, 3, 5], [1, 4, 6], [2, 3, 6], [2, 4, 5]]\n\n '
if (self._point_to_index is None):
return [b[:] for b in self._blocks]
else:
return [[self._points[i] for i in b] for b in self._blocks]
def block_sizes(self):
'\n Return the set of block sizes.\n\n EXAMPLES::\n\n sage: BD = IncidenceStructure(8, [[0,1,3],[1,4,5,6],[1,2],[5,6,7]])\n sage: BD.block_sizes()\n [3, 2, 4, 3]\n sage: BD = IncidenceStructure(7,[[0,1,2],[0,3,4],[0,5,6],[1,3,5],[1,4,6],[2,3,6],[2,4,5]])\n sage: BD.block_sizes()\n [3, 3, 3, 3, 3, 3, 3]\n '
return [len(b) for b in self._blocks]
def degree(self, p=None, subset=False):
'\n Return the degree of a point ``p`` (or a set of points).\n\n The degree of a point (or set of points) is the number of blocks that\n contain it.\n\n INPUT:\n\n - ``p`` -- a point (or a set of points) of the incidence structure.\n\n - ``subset`` (boolean) -- whether to interpret the argument as a set of\n point (``subset=True``) or as a point (``subset=False``, default).\n\n EXAMPLES::\n\n sage: designs.steiner_triple_system(9).degree(3)\n 4\n sage: designs.steiner_triple_system(9).degree({1,2},subset=True)\n 1\n\n TESTS::\n\n sage: designs.steiner_triple_system(9).degree(subset=True)\n Traceback (most recent call last):\n ...\n ValueError: subset must be False when p is None\n '
if (p is None):
if (subset is True):
raise ValueError('subset must be False when p is None')
if (not subset):
if self._point_to_index:
p = self._point_to_index.get(p, (- 1))
else:
p = (p if ((p >= 0) and (p < len(self._points))) else (- 1))
return (sum(((p in b) for b in self._blocks)) if (p != (- 1)) else 0)
else:
if self._point_to_index:
p = set((self._point_to_index.get(x, (- 1)) for x in p))
else:
p = (set(p) if all((((x >= 0) and (x < len(self._points))) for x in p)) else set([(- 1)]))
return (sum((p.issubset(b) for b in self._blocks)) if ((- 1) not in p) else 0)
def degrees(self, size=None):
'\n Return the degree of all sets of given size, or the degree of all points.\n\n The degree of a point (or set of point) is the number of blocks that\n contain it.\n\n INPUT:\n\n - ``size`` (integer) -- return the degree of all subsets of points of\n cardinality ``size``. When ``size=None``, the function outputs the\n degree of all points.\n\n .. NOTE::\n\n When ``size=None`` the output is indexed by the points. When\n ``size=1`` it is indexed by tuples of size 1. This is the same\n information, stored slightly differently.\n\n OUTPUT:\n\n A dictionary whose values are degrees and keys are either:\n\n - the points of the incidence structure if ``size=None`` (default)\n\n - the subsets of size ``size`` of the points stored as tuples\n\n EXAMPLES::\n\n sage: IncidenceStructure([[1,2,3],[1,4]]).degrees(2)\n {(1, 2): 1, (1, 3): 1, (1, 4): 1, (2, 3): 1, (2, 4): 0, (3, 4): 0}\n\n In a Steiner triple system, all pairs have degree 1::\n\n sage: S13 = designs.steiner_triple_system(13)\n sage: all(v == 1 for v in S13.degrees(2).values())\n True\n '
if (size is None):
d = ([0] * self.num_points())
for b in self._blocks:
for x in b:
d[x] += 1
return {p: d[i] for (i, p) in enumerate(self._points)}
else:
from itertools import combinations
d = {t: 0 for t in combinations(range(self.num_points()), size)}
for b in self._blocks:
for s in combinations(b, size):
d[s] += 1
if self._point_to_index:
return {tuple([self._points[x] for x in s]): v for (s, v) in d.items()}
else:
return d
def rank(self):
'\n Return the rank of the hypergraph (the maximum size of a block).\n\n EXAMPLES::\n\n sage: h = Hypergraph(8, [[0,1,3],[1,4,5,6],[1,2]])\n sage: h.rank()\n 4\n '
return max((len(b) for b in self._blocks))
def is_regular(self, r=None) -> (bool | int):
'\n Test whether the incidence structure is `r`-regular.\n\n An incidence structure is said to be `r`-regular if all its points are\n incident with exactly `r` blocks.\n\n INPUT:\n\n - ``r`` (integer)\n\n OUTPUT:\n\n If ``r`` is defined, a boolean is returned. If ``r`` is set to ``None``\n (default), the method returns either ``False`` or the integer ``r`` such\n that the incidence structure is `r`-regular.\n\n .. WARNING::\n\n In case of `0`-regular incidence structure, beware that ``if not\n H.is_regular()`` is a satisfied condition.\n\n EXAMPLES::\n\n sage: designs.balanced_incomplete_block_design(7,3).is_regular() # needs sage.schemes\n 3\n sage: designs.balanced_incomplete_block_design(7,3).is_regular(r=3) # needs sage.schemes\n True\n sage: designs.balanced_incomplete_block_design(7,3).is_regular(r=4) # needs sage.schemes\n False\n\n TESTS::\n\n sage: IncidenceStructure([]).is_regular()\n Traceback (most recent call last):\n ...\n ValueError: This incidence structure has no points.\n '
if (self.num_points() == 0):
raise ValueError('This incidence structure has no points.')
count = ([0] * self.num_points())
for b in self._blocks:
for x in b:
count[x] += 1
scount = set(count)
if (len(scount) != 1):
return False
if (r is None):
return scount.pop()
return (scount.pop() == r)
def is_uniform(self, k=None) -> (bool | int):
'\n Test whether the incidence structure is `k`-uniform\n\n An incidence structure is said to be `k`-uniform if all its blocks have\n size `k`.\n\n INPUT:\n\n - ``k`` (integer)\n\n OUTPUT:\n\n If ``k`` is defined, a boolean is returned. If ``k`` is set to ``None``\n (default), the method returns either ``False`` or the integer ``k`` such\n that the incidence structure is `k`-uniform.\n\n .. WARNING::\n\n In case of `0`-uniform incidence structure, beware that ``if not\n H.is_uniform()`` is a satisfied condition.\n\n EXAMPLES::\n\n sage: designs.balanced_incomplete_block_design(7,3).is_uniform() # needs sage.schemes\n 3\n sage: designs.balanced_incomplete_block_design(7,3).is_uniform(k=3) # needs sage.schemes\n True\n sage: designs.balanced_incomplete_block_design(7,3).is_uniform(k=4) # needs sage.schemes\n False\n\n TESTS::\n\n sage: IncidenceStructure([]).is_uniform()\n Traceback (most recent call last):\n ...\n ValueError: This incidence structure has no blocks.\n '
if (self.num_blocks() == 0):
raise ValueError('This incidence structure has no blocks.')
sizes = set(self.block_sizes())
if (len(sizes) != 1):
return False
if (k is None):
return sizes.pop()
return (sizes.pop() == k)
def is_connected(self) -> bool:
'\n Test whether the design is connected.\n\n EXAMPLES::\n\n sage: IncidenceStructure(3, [[0,1],[0,2]]).is_connected()\n True\n sage: IncidenceStructure(4, [[0,1],[2,3]]).is_connected()\n False\n '
from sage.sets.disjoint_set import DisjointSet
D = DisjointSet(self.num_points())
for B in self._blocks:
x = B[0]
for i in range(1, len(B)):
D.union(x, B[i])
return (D.number_of_subsets() == 1)
def is_simple(self) -> bool:
"\n Test whether this design is simple (i.e. no repeated block).\n\n EXAMPLES::\n\n sage: IncidenceStructure(3, [[0,1],[1,2],[0,2]]).is_simple()\n True\n sage: IncidenceStructure(3, [[0],[0]]).is_simple()\n False\n\n sage: V = [(0,'a'),(0,'b'),(1,'a'),(1,'b')]\n sage: B = [[V[0],V[1]], [V[1],V[2]]]\n sage: I = IncidenceStructure(V, B)\n sage: I.is_simple()\n True\n sage: I2 = IncidenceStructure(V, B*2)\n sage: I2.is_simple()\n False\n "
B = self._blocks
return all(((B[i] != B[(i + 1)]) for i in range((len(B) - 1))))
def _gap_(self):
"\n Return the GAP string describing the design.\n\n EXAMPLES::\n\n sage: BD = IncidenceStructure(7,[[0,1,2],[0,3,4],[0,5,6],[1,3,5],[1,4,6],[2,3,6],[2,4,5]])\n sage: BD._gap_()\n 'BlockDesign(7,[[1, 2, 3], [1, 4, 5], [1, 6, 7], [2, 4, 6], [2, 5, 7], [3, 4, 7], [3, 5, 6]])'\n "
v = self.num_points()
gB = [[(x + 1) for x in b] for b in self._blocks]
return 'BlockDesign({},{})'.format(v, gB)
def _libgap_(self):
'\n Return the design as a GAP record.\n\n EXAMPLES::\n\n sage: D = IncidenceStructure(4, [[0,2],[1,2,3],[2,3]])\n sage: D._libgap_() # optional - gap_package_design\n rec( blocks := [ [ 1, 3 ], [ 2, 3, 4 ], [ 3, 4 ] ],\n isBlockDesign := true, v := 4 )\n '
libgap.load_package('design')
v = self.num_points()
gB = [[(x + 1) for x in b] for b in self._blocks]
return libgap.BlockDesign(v, gB)
def intersection_graph(self, sizes=None):
'\n Return the intersection graph of the incidence structure.\n\n The vertices of this graph are the :meth:`blocks` of the incidence\n structure. Two of them are adjacent if the size of their intersection\n belongs to the set ``sizes``.\n\n INPUT:\n\n - ``sizes`` -- a list/set of integers. For convenience, setting\n ``sizes`` to ``5`` has the same effect as ``sizes=[5]``. When set to\n ``None`` (default), behaves as ``sizes=PositiveIntegers()``.\n\n EXAMPLES:\n\n The intersection graph of a\n :func:`~sage.combinat.designs.bibd.balanced_incomplete_block_design` is\n a :meth:`strongly regular graph <Graph.is_strongly_regular>` (when it is\n not trivial)::\n\n sage: BIBD = designs.balanced_incomplete_block_design(19,3)\n sage: G = BIBD.intersection_graph(1)\n sage: G.is_strongly_regular(parameters=True)\n (57, 24, 11, 9)\n '
from sage.sets.positive_integers import PositiveIntegers
from sage.graphs.graph import Graph
from sage.sets.set import Set
if (sizes is None):
sizes = PositiveIntegers()
elif (sizes in PositiveIntegers()):
sizes = (sizes,)
V = [Set(v) for v in self]
return Graph([V, (lambda x, y: (len((x & y)) in sizes))], loops=False)
def incidence_matrix(self):
"\n Return the incidence matrix `A` of the design. A is a `(v \\times b)`\n matrix defined by: ``A[i,j] = 1`` if ``i`` is in block ``B_j`` and 0\n otherwise.\n\n EXAMPLES::\n\n sage: BD = IncidenceStructure(7, [[0,1,2],[0,3,4],[0,5,6],[1,3,5],\n ....: [1,4,6],[2,3,6],[2,4,5]])\n sage: BD.block_sizes()\n [3, 3, 3, 3, 3, 3, 3]\n sage: BD.incidence_matrix() # needs sage.modules\n [1 1 1 0 0 0 0]\n [1 0 0 1 1 0 0]\n [1 0 0 0 0 1 1]\n [0 1 0 1 0 1 0]\n [0 1 0 0 1 0 1]\n [0 0 1 1 0 0 1]\n [0 0 1 0 1 1 0]\n\n sage: I = IncidenceStructure('abc', ('ab','abc','ac','c'))\n sage: I.incidence_matrix() # needs sage.modules\n [1 1 1 0]\n [1 1 0 0]\n [0 1 1 1]\n "
from sage.matrix.constructor import Matrix
from sage.rings.integer_ring import ZZ
A = Matrix(ZZ, self.num_points(), self.num_blocks(), sparse=True)
for (j, b) in enumerate(self._blocks):
for i in b:
A[(i, j)] = 1
return A
def incidence_graph(self, labels=False):
'\n Return the incidence graph of the incidence structure\n\n A point and a block are adjacent in this graph whenever they are\n incident.\n\n INPUT:\n\n - ``labels`` (boolean) -- whether to return a graph whose vertices are\n integers, or labelled elements.\n\n - ``labels is False`` (default) -- in this case the first vertices\n of the graphs are the elements of :meth:`ground_set`, and appear\n in the same order. Similarly, the following vertices represent the\n elements of :meth:`blocks`, and appear in the same order.\n\n - ``labels is True``, the points keep their original labels, and the\n blocks are :func:`Set <Set>` objects.\n\n Note that the labelled incidence graph can be incorrect when\n blocks are repeated, and on some (rare) occasions when the\n elements of :meth:`ground_set` mix :func:`Set` and non-:func:`Set\n <Set>` objects.\n\n EXAMPLES::\n\n sage: BD = IncidenceStructure(7, [[0,1,2],[0,3,4],[0,5,6],[1,3,5],\n ....: [1,4,6],[2,3,6],[2,4,5]])\n sage: BD.incidence_graph() # needs sage.modules\n Bipartite graph on 14 vertices\n sage: A = BD.incidence_matrix() # needs sage.modules\n sage: Graph(block_matrix([[A*0, A], # needs sage.modules\n ....: [A.transpose(),A*0]])) == BD.incidence_graph()\n True\n\n TESTS:\n\n With ``labels = True``::\n\n sage: BD.incidence_graph(labels=True).has_edge(0,Set([0,1,2]))\n True\n '
if labels:
from sage.graphs.graph import Graph
from sage.sets.set import Set
G = Graph()
G.add_vertices(self.ground_set())
for b in self.blocks():
b = Set(b)
G.add_vertex(b)
G.add_edges(((b, x) for x in b))
return G
else:
from sage.graphs.bipartite_graph import BipartiteGraph
A = self.incidence_matrix()
return BipartiteGraph(A)
def is_berge_cyclic(self):
'\n Check whether ``self`` is a Berge-Cyclic uniform hypergraph.\n\n A `k`-uniform Berge cycle (named after Claude Berge) of length `\\ell`\n is a cyclic list of distinct `k`-sets `F_1,\\ldots,F_\\ell`, `\\ell>1`,\n and distinct vertices `C = \\{v_1,\\ldots,v_\\ell\\}` such that for each\n `1\\le i\\le \\ell`, `F_i` contains `v_i` and `v_{i+1}` (where `v_{l+1} =\n v_1`).\n\n A uniform hypergraph is Berge-cyclic if its incidence graph is cyclic.\n It is called "Berge-acyclic" otherwise.\n\n For more information, see [Fag1983]_ and :wikipedia:`Hypergraph`.\n\n EXAMPLES::\n\n sage: Hypergraph(5, [[1, 2, 3], [2, 3, 4]]).is_berge_cyclic() # needs sage.modules\n True\n sage: Hypergraph(6, [[1, 2, 3], [3, 4, 5]]).is_berge_cyclic() # needs sage.modules\n False\n\n TESTS::\n\n sage: Hypergraph(5, [[1, 2, 3], [2, 3]]).is_berge_cyclic()\n Traceback (most recent call last):\n ...\n TypeError: Berge cycles are defined for uniform hypergraphs only\n '
if (not self.is_uniform()):
raise TypeError('Berge cycles are defined for uniform hypergraphs only')
return (not self.incidence_graph().is_forest())
def complement(self, uniform=False):
'\n Return the complement of the incidence structure.\n\n Two different definitions of "complement" are made available, according\n to the value of ``uniform``.\n\n INPUT:\n\n - ``uniform`` (boolean) --\n\n - if set to ``False`` (default), returns the incidence structure whose\n blocks are the complements of all blocks of the incidence structure.\n\n - If set to ``True`` and the incidence structure is `k`-uniform,\n returns the incidence structure whose blocks are all `k`-sets of the\n ground set that do not appear in ``self``.\n\n EXAMPLES:\n\n The complement of a\n :class:`~sage.combinat.designs.bibd.BalancedIncompleteBlockDesign` is\n also a `2`-design::\n\n sage: bibd = designs.balanced_incomplete_block_design(13,4) # needs sage.schemes\n sage: bibd.is_t_design(return_parameters=True) # needs sage.schemes\n (True, (2, 13, 4, 1))\n sage: bibd.complement().is_t_design(return_parameters=True) # needs sage.schemes\n (True, (2, 13, 9, 6))\n\n The "uniform" complement of a graph is a graph::\n\n sage: g = graphs.PetersenGraph()\n sage: G = IncidenceStructure(g.edges(sort=True, labels=False))\n sage: H = G.complement(uniform=True)\n sage: h = Graph(H.blocks())\n sage: g == h\n False\n sage: g == h.complement()\n True\n\n TESTS::\n\n sage: bibd.relabel({i:str(i) for i in bibd.ground_set()}) # needs sage.schemes\n sage: bibd.complement().ground_set() # needs sage.schemes\n [\'0\', \'1\', \'2\', \'3\', \'4\', \'5\', \'6\', \'7\', \'8\', \'9\', \'10\', \'11\', \'12\']\n\n sage: I = IncidenceStructure(\'abc\', [\'ab\',\'ac\',\'bc\'])\n sage: I.is_t_design(return_parameters=True)\n (True, (2, 3, 2, 1))\n '
if uniform:
k = self.is_uniform()
if (k is False):
raise ValueError('The incidence structure is not uniform.')
blocks = []
num_blocks = self.num_blocks()
i = 0
from itertools import combinations
for B in combinations(range(self.num_points()), k):
B = list(B)
while ((i < num_blocks) and (self._blocks[i] < B)):
i += 1
if ((i < num_blocks) and (self._blocks[i] == B)):
i += 1
continue
blocks.append(B)
I = IncidenceStructure(blocks, copy=False)
else:
X = set(range(self.num_points()))
I = IncidenceStructure([X.difference(B) for B in self._blocks])
I.relabel({i: self._points[i] for i in range(self.num_points())})
return I
def relabel(self, perm=None, inplace=True):
"\n Relabel the ground set\n\n INPUT:\n\n - ``perm`` -- can be one of\n\n - a dictionary -- then each point ``p`` (which should be a key of\n ``d``) is relabeled to ``d[p]``\n\n - a list or a tuple of length ``n`` -- the first point returned by\n :meth:`ground_set` is relabeled to ``l[0]``, the second to\n ``l[1]``, ...\n\n - ``None`` -- the incidence structure is relabeled to be on\n `\\{0,1,...,n-1\\}` in the ordering given by :meth:`ground_set`.\n\n - ``inplace`` -- If ``True`` then return a relabeled graph and does not\n touch ``self`` (default is ``False``).\n\n\n EXAMPLES::\n\n sage: # needs sage.schemes\n sage: TD = designs.transversal_design(5,5)\n sage: TD.relabel({i: chr(97+i) for i in range(25)})\n sage: TD.ground_set()\n ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',\n 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y']\n sage: TD.blocks()[:3]\n [['a', 'f', 'k', 'p', 'u'], ['a', 'g', 'm', 's', 'y'], ['a', 'h', 'o', 'q', 'x']]\n\n Relabel to integer points::\n\n sage: TD.relabel() # needs sage.schemes\n sage: TD.blocks()[:3] # needs sage.schemes\n [[0, 5, 10, 15, 20], [0, 6, 12, 18, 24], [0, 7, 14, 16, 23]]\n\n TESTS:\n\n Check that the relabel is consistent on a fixed incidence structure::\n\n sage: I = IncidenceStructure([0,1,2,3,4],\n ....: [[0,1,3],[0,2,4],[2,3,4],[0,1]])\n sage: I.relabel()\n sage: from itertools import permutations\n sage: for p in permutations([0,1,2,3,4]):\n ....: J = I.relabel(p,inplace=False)\n ....: if I == J: print(p)\n (0, 1, 2, 3, 4)\n (0, 1, 4, 3, 2)\n\n And one can also verify that we have exactly two automorphisms::\n\n sage: I.automorphism_group() # needs sage.groups\n Permutation Group with generators [(2,4)]\n "
if (not inplace):
from copy import copy
G = copy(self)
G.relabel(perm=perm, inplace=True)
return G
if (perm is None):
self._points = list(range(self.num_points()))
self._point_to_index = None
return
if isinstance(perm, (list, tuple)):
perm = dict(zip(self._points, perm))
if (not isinstance(perm, dict)):
raise ValueError('perm argument must be None, a list or a dictionary')
if (len(set(perm.values())) != len(perm)):
raise ValueError('two points are getting relabelled with the same name')
self._points = [perm[x] for x in self._points]
if (self._points == list(range(self.num_points()))):
self._point_to_index = None
else:
self._point_to_index = {v: i for (i, v) in enumerate(self._points)}
def packing(self, solver=None, verbose=0, *, integrality_tolerance=0.001):
'\n Return a maximum packing\n\n A maximum packing in a hypergraph is collection of disjoint sets/blocks\n of maximal cardinality. This problem is NP-complete in general, and in\n particular on 3-uniform hypergraphs. It is solved here with an Integer\n Linear Program.\n\n For more information, see the :wikipedia:`Packing_in_a_hypergraph`.\n\n INPUT:\n\n - ``solver`` -- (default: ``None``) Specify a Mixed Integer Linear\n Programming (MILP) solver to be used. If set to ``None``, the default\n one is used. For more information on LP solvers and which default\n solver is used, see the method :meth:`solve\n <sage.numerical.mip.MixedIntegerLinearProgram.solve>` of the class\n :class:`MixedIntegerLinearProgram\n <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``verbose`` -- integer (default: ``0``). Sets the level of\n verbosity. Set to 0 by default, which means quiet.\n\n - ``integrality_tolerance`` -- parameter for use with MILP solvers over\n an inexact base ring; see\n :meth:`MixedIntegerLinearProgram.get_values`.\n\n EXAMPLES::\n\n sage: P = IncidenceStructure([[1,2],[3,4],[2,3]]).packing() # needs sage.numerical.mip\n sage: sorted(sorted(b) for b in P) # needs sage.numerical.mip\n [[1, 2], [3, 4]]\n sage: len(designs.steiner_triple_system(9).packing()) # needs sage.numerical.mip\n 3\n '
from sage.numerical.mip import MixedIntegerLinearProgram
d = [[] for _ in self._points]
for (i, B) in enumerate(self._blocks):
for x in B:
d[x].append(i)
p = MixedIntegerLinearProgram(solver=solver)
b = p.new_variable(binary=True)
for (x, L) in enumerate(d):
p.add_constraint((p.sum([b[i] for i in L]) <= 1))
p.set_objective(p.sum([b[i] for i in range(self.num_blocks())]))
p.solve(log=verbose)
values = p.get_values(b, convert=bool, tolerance=integrality_tolerance)
return [[self._points[x] for x in self._blocks[i]] for (i, v) in values.items() if v]
def is_t_design(self, t=None, v=None, k=None, l=None, return_parameters=False):
'\n Test whether ``self`` is a `t-(v,k,l)` design.\n\n A `t-(v,k,\\lambda)` (sometimes called `t`-design for short) is a block\n design in which:\n\n - the underlying set has cardinality `v`\n - the blocks have size `k`\n - each `t`-subset of points is covered by `\\lambda` blocks\n\n INPUT:\n\n - ``t,v,k,l`` (integers) -- their value is set to ``None`` by\n default. The function tests whether the design is a ``t-(v,k,l)``\n design using the provided values and guesses the others. Note that\n `l`` cannot be specified if ``t`` is not.\n\n - ``return_parameters`` (boolean)-- whether to return the parameters of\n the `t`-design. If set to ``True``, the function returns a pair\n ``(boolean_answer,(t,v,k,l))``.\n\n EXAMPLES::\n\n sage: fano_blocks = [[0,1,2],[0,3,4],[0,5,6],[1,3,5],[1,4,6],[2,3,6],[2,4,5]]\n sage: BD = IncidenceStructure(7, fano_blocks)\n sage: BD.is_t_design()\n True\n sage: BD.is_t_design(return_parameters=True)\n (True, (2, 7, 3, 1))\n sage: BD.is_t_design(2, 7, 3, 1)\n True\n sage: BD.is_t_design(1, 7, 3, 3)\n True\n sage: BD.is_t_design(0, 7, 3, 7)\n True\n\n sage: BD.is_t_design(0,6,3,7) or BD.is_t_design(0,7,4,7) or BD.is_t_design(0,7,3,8)\n False\n\n sage: BD = designs.AffineGeometryDesign(3, 1, GF(2)) # needs sage.combinat\n sage: BD.is_t_design(1) # needs sage.combinat\n True\n sage: BD.is_t_design(2) # needs sage.combinat\n True\n\n Steiner triple and quadruple systems are other names for `2-(v,3,1)` and\n `3-(v,4,1)` designs::\n\n sage: S3_9 = designs.steiner_triple_system(9)\n sage: S3_9.is_t_design(2,9,3,1)\n True\n\n sage: blocks = designs.steiner_quadruple_system(8)\n sage: S4_8 = IncidenceStructure(8, blocks)\n sage: S4_8.is_t_design(3,8,4,1)\n True\n\n sage: blocks = designs.steiner_quadruple_system(14)\n sage: S4_14 = IncidenceStructure(14, blocks)\n sage: S4_14.is_t_design(3,14,4,1)\n True\n\n Some examples of Witt designs that need the gap database::\n\n sage: # optional - gap_package_design\n sage: BD = designs.WittDesign(9)\n sage: BD.is_t_design(2,9,3,1)\n True\n sage: W12 = designs.WittDesign(12)\n sage: W12.is_t_design(5,12,6,1)\n True\n sage: W12.is_t_design(4)\n True\n\n Further examples::\n\n sage: D = IncidenceStructure(4,[[],[]])\n sage: D.is_t_design(return_parameters=True)\n (True, (0, 4, 0, 2))\n\n sage: D = IncidenceStructure(4, [[0,1],[0,2],[0,3]])\n sage: D.is_t_design(return_parameters=True)\n (True, (0, 4, 2, 3))\n\n sage: D = IncidenceStructure(4, [[0],[1],[2],[3]])\n sage: D.is_t_design(return_parameters=True)\n (True, (1, 4, 1, 1))\n\n sage: D = IncidenceStructure(4,[[0,1],[2,3]])\n sage: D.is_t_design(return_parameters=True)\n (True, (1, 4, 2, 1))\n\n sage: D = IncidenceStructure(4, [list(range(4))])\n sage: D.is_t_design(return_parameters=True)\n (True, (4, 4, 4, 1))\n\n TESTS::\n\n sage: blocks = designs.steiner_quadruple_system(8)\n sage: S4_8 = IncidenceStructure(8, blocks)\n sage: R = list(range(15))\n sage: [(v,k,l) for v in R for k in R for l in R if S4_8.is_t_design(3,v,k,l)]\n [(8, 4, 1)]\n sage: [(v,k,l) for v in R for k in R for l in R if S4_8.is_t_design(2,v,k,l)]\n [(8, 4, 3)]\n sage: [(v,k,l) for v in R for k in R for l in R if S4_8.is_t_design(1,v,k,l)]\n [(8, 4, 7)]\n sage: [(v,k,l) for v in R for k in R for l in R if S4_8.is_t_design(0,v,k,l)]\n [(8, 4, 14)]\n\n sage: # needs sage.rings.finite_rings\n sage: A = designs.AffineGeometryDesign(3, 1, GF(2))\n sage: A.is_t_design(return_parameters=True)\n (True, (2, 8, 2, 1))\n sage: A = designs.AffineGeometryDesign(4, 2, GF(2))\n sage: A.is_t_design(return_parameters=True)\n (True, (3, 16, 4, 1))\n\n sage: I = IncidenceStructure(2, [])\n sage: I.is_t_design(return_parameters=True)\n (True, (0, 2, 0, 0))\n sage: I = IncidenceStructure(2, [[0],[0,1]])\n sage: I.is_t_design(return_parameters=True)\n (False, (0, 0, 0, 0))\n '
from sage.arith.misc import binomial
if (v is None):
v = self.num_points()
if (k is None):
k = (len(self._blocks[0]) if self._blocks else 0)
if ((l is not None) and (t is None)):
raise ValueError('t must be set when l=None')
b = self.num_blocks()
if (any(((len(block) != k) for block in self._blocks)) or (v != self.num_points())):
return ((False, (0, 0, 0, 0)) if return_parameters else False)
if ((t is not None) and (t > k)):
if ((l is None) or (l == 0)):
return ((True, (t, v, k, 0)) if return_parameters else True)
else:
return ((False, (0, 0, 0, 0)) if return_parameters else False)
if (k == 0):
if ((l is None) or (l == 0)):
return ((True, (0, v, k, b)) if return_parameters else True)
else:
return ((False, (0, 0, 0, 0)) if return_parameters else False)
if (k == v):
if (t is None):
t = v
if ((l is None) or (b == l)):
return ((True, (t, v, k, b)) if return_parameters else True)
else:
return ((True, (0, 0, 0, 0)) if return_parameters else False)
from itertools import combinations
for tt in (range(1, (k + 1)) if (t is None) else [t]):
if (((b * binomial(k, tt)) % binomial(v, tt)) != 0):
tt -= 1
break
s = {}
for block in self._blocks:
for i in combinations(block, tt):
s[i] = (s.get(i, 0) + 1)
if (len(set(s.values())) != 1):
tt -= 1
break
ll = ((b * binomial(k, tt)) // binomial(v, tt))
if (((t is not None) and (t != tt)) or ((l is not None) and (l != ll))):
return ((False, (0, 0, 0, 0)) if return_parameters else False)
else:
if (tt == 0):
ll = b
return ((True, (tt, v, k, ll)) if return_parameters else True)
def is_generalized_quadrangle(self, verbose=False, parameters=False):
"\n Test if the incidence structure is a generalized quadrangle.\n\n An incidence structure is a generalized quadrangle iff (see [BH2012]_,\n section 9.6):\n\n - two blocks intersect on at most one point.\n\n - For every point `p` not in a block `B`, there is a unique block `B'`\n intersecting both `\\{p\\}` and `B`\n\n It is a *regular* generalized quadrangle if furthermore:\n\n - it is `s+1`-:meth:`uniform <is_uniform>` for some positive integer `s`.\n\n - it is `t+1`-:meth:`regular <is_regular>` for some positive integer `t`.\n\n For more information, see the :wikipedia:`Generalized_quadrangle`.\n\n .. NOTE::\n\n Some references (e.g. [PT2009]_ or\n :wikipedia:`Generalized_quadrangle`) only allow *regular*\n generalized quadrangles. To use such a definition, see the\n ``parameters`` optional argument described below, or the methods\n :meth:`is_regular` and :meth:`is_uniform`.\n\n INPUT:\n\n - ``verbose`` (boolean) -- whether to print an explanation when the\n instance is not a generalized quadrangle.\n\n - ``parameters`` (boolean; ``False``) -- if set to ``True``, the\n function returns a pair ``(s,t)`` instead of ``True`` answers. In this\n case, `s` and `t` are the integers defined above if they exist (each\n can be set to ``False`` otherwise).\n\n EXAMPLES::\n\n sage: h = designs.CremonaRichmondConfiguration() # needs networkx\n sage: h.is_generalized_quadrangle() # needs networkx\n True\n\n This is actually a *regular* generalized quadrangle::\n\n sage: h.is_generalized_quadrangle(parameters=True) # needs networkx\n (2, 2)\n\n TESTS::\n\n sage: H = IncidenceStructure((2*graphs.CompleteGraph(3)).edges(sort=True, labels=False))\n sage: H.is_generalized_quadrangle(verbose=True) # needs sage.modules\n Some point is at distance >3 from some block.\n False\n\n sage: G = graphs.CycleGraph(5)\n sage: B = list(G.subgraph_search_iterator(graphs.PathGraph(3), # needs sage.modules\n ....: return_graphs=False))\n sage: H = IncidenceStructure(B) # needs sage.modules\n sage: H.is_generalized_quadrangle(verbose=True) # needs sage.modules\n Two blocks intersect on >1 points.\n False\n\n sage: hypergraphs.CompleteUniform(4,2).is_generalized_quadrangle(verbose=1) # needs sage.modules\n Some point has two projections on some line.\n False\n "
g = self.incidence_graph()
if (g.diameter() > 4):
if verbose:
print('Some point is at distance >3 from some block.')
return False
girth = g.girth()
if (girth == 4):
if verbose:
print('Two blocks intersect on >1 points.')
return False
elif (girth == 6):
if verbose:
print('Some point has two projections on some line.')
return False
if parameters:
s = self.is_uniform()
t = self.is_regular()
s = ((s - 1) if ((s is not False) and (s >= 2)) else False)
t = ((t - 1) if ((t is not False) and (t >= 2)) else False)
return (s, t)
else:
return True
def dual(self, algorithm=None):
'\n Return the dual of the incidence structure.\n\n INPUT:\n\n - ``algorithm`` -- whether to use Sage\'s implementation\n (``algorithm=None``, default) or use GAP\'s (``algorithm="gap"``).\n\n .. NOTE::\n\n The ``algorithm="gap"`` option requires GAP\'s Design package\n (included in the ``gap_packages`` Sage spkg).\n\n EXAMPLES:\n\n The dual of a projective plane is a projective plane::\n\n sage: PP = designs.DesarguesianProjectivePlaneDesign(4) # needs sage.rings.finite_rings\n sage: PP.dual().is_t_design(return_parameters=True) # needs sage.modules sage.rings.finite_rings\n (True, (2, 21, 5, 1))\n\n TESTS::\n\n sage: D = IncidenceStructure(4, [[0,2],[1,2,3],[2,3]]); D\n Incidence structure with 4 points and 3 blocks\n sage: D.dual() # needs sage.modules\n Incidence structure with 3 points and 4 blocks\n sage: print(D.dual(algorithm="gap")) # optional - gap_package_design\n Incidence structure with 3 points and 4 blocks\n sage: blocks = [[0,1,2],[0,3,4],[0,5,6],[1,3,5],[1,4,6],[2,3,6],[2,4,5]]\n sage: BD = IncidenceStructure(7, blocks, name="FanoPlane"); BD\n Incidence structure with 7 points and 7 blocks\n sage: print(BD.dual(algorithm="gap")) # optional - gap_package_design\n Incidence structure with 7 points and 7 blocks\n sage: BD.dual() # needs sage.modules\n Incidence structure with 7 points and 7 blocks\n\n REFERENCE:\n\n - Soicher, Leonard, Design package manual, available at\n https://www.gap-system.org/Manuals/pkg/design/htm/CHAP003.htm\n '
if (algorithm == 'gap'):
libgap.load_package('design')
DD = libgap(self).DualBlockDesign()
v = DD['v'].sage()
gB = [[(x - 1) for x in b] for b in DD['blocks'].sage()]
return IncidenceStructure(list(range(v)), gB, name=None, check=False)
else:
return IncidenceStructure(incidence_matrix=self.incidence_matrix().transpose(), check=False)
def automorphism_group(self):
"\n Return the subgroup of the automorphism group of the incidence graph\n which respects the P B partition. It is (isomorphic to) the automorphism\n group of the block design, although the degrees differ.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.rings.finite_rings\n sage: P = designs.DesarguesianProjectivePlaneDesign(2); P\n (7,3,1)-Balanced Incomplete Block Design\n sage: G = P.automorphism_group()\n sage: G.is_isomorphic(PGL(3,2))\n True\n sage: G\n Permutation Group with generators [...]\n sage: G.cardinality()\n 168\n\n A non self-dual example::\n\n sage: IS = IncidenceStructure(list(range(4)), [[0,1,2,3],[1,2,3]])\n sage: IS.automorphism_group().cardinality() # needs sage.groups\n 6\n sage: IS.dual().automorphism_group().cardinality() # needs sage.groups sage.modules\n 1\n\n Examples with non-integer points::\n\n sage: I = IncidenceStructure('abc', ('ab','ac','bc'))\n sage: I.automorphism_group() # needs sage.groups\n Permutation Group with generators [('b','c'), ('a','b')]\n sage: IncidenceStructure([[(1,2),(3,4)]]).automorphism_group() # needs sage.groups\n Permutation Group with generators [((1,2),(3,4))]\n "
from sage.graphs.graph import Graph
from sage.groups.perm_gps.permgroup import PermutationGroup
g = Graph()
n = self.num_points()
g.add_edges((((i + n), x) for (i, b) in enumerate(self._blocks) for x in b))
ag = g.automorphism_group(partition=[list(range(n)), list(range(n, (n + self.num_blocks())))])
if self._point_to_index:
gens = [[tuple([self._points[i] for i in cycle if ((not cycle) or (cycle[0] < n))]) for cycle in g.cycle_tuples()] for g in ag.gens()]
else:
gens = [[tuple(cycle) for cycle in g.cycle_tuples() if ((not cycle) or (cycle[0] < n))] for g in ag.gens()]
return PermutationGroup(gens, domain=self._points)
def is_resolvable(self, certificate=False, solver=None, verbose=0, check=True, *, integrality_tolerance=0.001):
'\n Test whether the hypergraph is resolvable\n\n A hypergraph is said to be resolvable if its sets can be partitionned\n into classes, each of which is a partition of the ground set.\n\n .. NOTE::\n\n This problem is solved using an Integer Linear Program, and GLPK\n (the default LP solver) has been reported to be very slow on some\n instances. If you hit this wall, consider installing a more powerful\n MILP solver (CPLEX, Gurobi, ...).\n\n INPUT:\n\n - ``certificate`` (boolean) -- whether to return the classes along with\n the binary answer (see examples below).\n\n - ``solver`` -- (default: ``None``) Specify a Mixed Integer Linear\n Programming (MILP) solver to be used. If set to ``None``, the default\n one is used. For more information on MILP solvers and which default\n solver is used, see the method :meth:`solve\n <sage.numerical.mip.MixedIntegerLinearProgram.solve>` of the class\n :class:`MixedIntegerLinearProgram\n <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``verbose`` -- integer (default: ``0``). Sets the level of\n verbosity. Set to 0 by default, which means quiet.\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\n ``True`` by default.\n\n - ``integrality_tolerance`` -- parameter for use with MILP solvers over\n an inexact base ring; see\n :meth:`MixedIntegerLinearProgram.get_values`.\n\n EXAMPLES:\n\n Some resolvable designs::\n\n sage: TD = designs.transversal_design(2,2,resolvable=True)\n sage: TD.is_resolvable()\n True\n\n sage: AG = designs.AffineGeometryDesign(3,1,GF(2)) # needs sage.combinat\n sage: AG.is_resolvable() # needs sage.combinat\n True\n\n Their classes::\n\n sage: b, cls = TD.is_resolvable(True)\n sage: b\n True\n sage: cls # random\n [[[0, 3], [1, 2]], [[1, 3], [0, 2]]]\n\n sage: # needs sage.combinat\n sage: b, cls = AG.is_resolvable(True)\n sage: b\n True\n sage: cls # random\n [[[6, 7], [4, 5], [0, 1], [2, 3]],\n [[5, 7], [0, 4], [3, 6], [1, 2]],\n [[0, 2], [4, 7], [1, 3], [5, 6]],\n [[3, 4], [0, 7], [1, 5], [2, 6]],\n [[3, 7], [1, 6], [0, 5], [2, 4]],\n [[0, 6], [2, 7], [1, 4], [3, 5]],\n [[4, 6], [0, 3], [2, 5], [1, 7]]]\n\n A non-resolvable design::\n\n sage: Fano = designs.balanced_incomplete_block_design(7,3) # needs sage.schemes\n sage: Fano.is_resolvable() # needs sage.schemes\n False\n sage: Fano.is_resolvable(True) # needs sage.schemes\n (False, [])\n\n TESTS::\n\n sage: # needs sage.combinat\n sage: _, cls1 = AG.is_resolvable(certificate=True)\n sage: _, cls2 = AG.is_resolvable(certificate=True)\n sage: cls1 is cls2\n False\n '
if (self._classes is None):
degrees = set(self.degrees().values())
if (len(degrees) != 1):
self._classes = False
else:
from sage.numerical.mip import MixedIntegerLinearProgram
from sage.numerical.mip import MIPSolverException
n_classes = degrees.pop()
p = MixedIntegerLinearProgram(solver=solver)
b = p.new_variable(binary=True)
domain = list(range(self.num_points()))
dual = [[] for _ in domain]
for (i, B) in enumerate(self._blocks):
for x in B:
dual[x].append(i)
for t in range(n_classes):
for x in domain:
p.add_constraint((p.sum((b[(t, i)] for i in dual[x])) == 1))
for i in range(len(self._blocks)):
p.add_constraint((p.sum((b[(t, i)] for t in range(n_classes))) == 1))
try:
p.solve(log=verbose)
except MIPSolverException:
self._classes = False
else:
self._classes = [[] for _ in range(n_classes)]
for ((t, i), v) in p.get_values(b, convert=bool, tolerance=integrality_tolerance).items():
if v:
self._classes[t].append(self._blocks[i])
if (check and (self._classes is not False)):
assert (sorted((id(c) for cls in self._classes for c in cls)) == sorted((id(b) for b in self._blocks))), 'some set does not appear exactly once'
domain = list(range(self.num_points()))
for (i, c) in enumerate(self._classes):
assert (sorted(sum(c, [])) == domain), 'class {} is not a partition'.format(i)
if (self._classes is False):
return ((False, []) if certificate else False)
if certificate:
if (self._point_to_index is None):
classes = [[block[:] for block in classs] for classs in self._classes]
else:
classes = [[[self._points[i] for i in block] for block in classs] for classs in self._classes]
return (True, classes)
else:
return True
def coloring(self, k=None, solver=None, verbose=0, *, integrality_tolerance=0.001):
'\n Compute a (weak) `k`-coloring of the hypergraph\n\n A weak coloring of a hypergraph `\\mathcal H` is an assignment of colors\n to its vertices such that no set is monochromatic.\n\n INPUT:\n\n - ``k`` (integer) -- compute a coloring with `k` colors if an integer is\n provided, otherwise returns an optimal coloring (i.e. with the minimum\n possible number of colors).\n\n - ``solver`` -- (default: ``None``) Specify a Mixed Integer Linear\n Programming (MILP) solver to be used. If set to ``None``, the default\n one is used. For more information on MILP solvers and which default\n solver is used, see the method :meth:`solve\n <sage.numerical.mip.MixedIntegerLinearProgram.solve>` of the class\n :class:`MixedIntegerLinearProgram\n <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``verbose`` -- non-negative integer (default: ``0``). Set the level\n of verbosity you want from the linear program solver. Since the\n problem is `NP`-complete, its solving may take some time depending on\n the graph. A value of 0 means that there will be no message printed by\n the solver.\n\n - ``integrality_tolerance`` -- parameter for use with MILP solvers over\n an inexact base ring; see\n :meth:`MixedIntegerLinearProgram.get_values`.\n\n EXAMPLES:\n\n The Fano plane has chromatic number 3::\n\n sage: len(designs.steiner_triple_system(7).coloring()) # needs sage.numerical.mip\n 3\n\n One admissible 3-coloring::\n\n sage: designs.steiner_triple_system(7).coloring() # not tested # needs sage.numerical.mip\n [[0, 2, 5, 1], [4, 3], [6]]\n\n The chromatic number of a graph is equal to the chromatic number of its\n 2-uniform corresponding hypergraph::\n\n sage: g = graphs.PetersenGraph()\n sage: H = IncidenceStructure(g.edges(sort=True, labels=False))\n sage: len(g.coloring())\n 3\n sage: len(H.coloring()) # needs sage.numerical.mip\n 3\n '
if (k is None):
for k in range((self.num_points() + 1)):
try:
return self.coloring(k)
except ValueError:
pass
if (k == 0):
if self.num_points():
raise ValueError('Only empty hypergraphs are 0-chromatic')
return []
elif any(((len(x) == 1) for x in self._blocks)):
raise RuntimeError('No coloring can be defined when there is a set of size 1')
elif (k == 1):
if any(self._blocks):
raise ValueError('This hypergraph contains a set. It is not 1-chromatic')
return [self.ground_set()]
from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException
p = MixedIntegerLinearProgram(solver=solver)
b = p.new_variable(binary=True)
for x in range(self.num_points()):
p.add_constraint((p.sum((b[(x, i)] for i in range(k))) == 1))
for s in self._blocks:
for i in range(k):
p.add_constraint((p.sum((b[(x, i)] for x in s)) <= (len(s) - 1)))
try:
p.solve(log=verbose)
except MIPSolverException:
raise ValueError('This hypergraph is not {}-colorable'.format(k))
col = [[] for _ in range(k)]
for ((x, i), v) in p.get_values(b, convert=bool, tolerance=integrality_tolerance).items():
if v:
col[i].append(self._points[x])
return col
def edge_coloring(self):
'\n Compute a proper edge-coloring.\n\n A proper edge-coloring is an assignment of colors to the sets of the\n incidence structure such that two sets with non-empty intersection\n receive different colors. The coloring returned minimizes the number of\n colors.\n\n OUTPUT:\n\n A partition of the sets into color classes.\n\n EXAMPLES::\n\n sage: H = Hypergraph([{1,2,3},{2,3,4},{3,4,5},{4,5,6}]); H\n Incidence structure with 6 points and 4 blocks\n sage: C = H.edge_coloring()\n sage: C # random\n [[[3, 4, 5]], [[2, 3, 4]], [[4, 5, 6], [1, 2, 3]]]\n sage: Set(map(Set,sum(C,[]))) == Set(map(Set,H.blocks()))\n True\n '
from sage.graphs.graph import Graph
blocks = self.blocks()
blocks_sets = [frozenset(b) for b in blocks]
g = Graph([list(range(self.num_blocks())), (lambda x, y: len((blocks_sets[x] & blocks_sets[y])))], loops=False)
return [[blocks[i] for i in C] for C in g.coloring(algorithm='MILP')]
def _spring_layout(self):
'\n Return a spring layout for the points.\n\n The layout is computed by creating a graph `G` on the points *and* sets\n of the incidence structure. Each set is then made adjacent in `G` with\n all points it contains before a spring layout is computed for this\n graph. The position of the points in the graph gives the position of the\n points in the final drawing.\n\n .. NOTE::\n\n This method also returns the position of the "fake" points,\n i.e. those representing the sets.\n\n EXAMPLES::\n\n sage: # needs sage.plot\n sage: H = Hypergraph([{1,2,3},{2,3,4},{3,4,5},{4,5,6}]); H\n Incidence structure with 6 points and 4 blocks\n sage: L = H._spring_layout()\n sage: L # random\n {1: (0.238, -0.926),\n 2: (0.672, -0.518),\n 3: (0.449, -0.225),\n 4: (0.782, 0.225),\n 5: (0.558, 0.518),\n 6: (0.992, 0.926),\n {3, 4, 5}: (0.504, 0.173),\n {2, 3, 4}: (0.727, -0.173),\n {4, 5, 6}: (0.838, 0.617),\n {1, 2, 3}: (0.393, -0.617)}\n sage: all(v in L for v in H.ground_set())\n True\n sage: all(v in L for v in map(Set, H.blocks()))\n True\n '
from sage.graphs.graph import Graph
g = Graph()
for s in map(Set, self.blocks()):
for x in s:
g.add_edge((0, s), (1, x))
_ = g.plot(iterations=50000, save_pos=True)
return {k[1]: (round(x, 3), round(y, 3)) for (k, (x, y)) in g.get_pos().items()}
def _latex_(self):
'\n Return a TikZ representation of the incidence structure\n\n EXAMPLES::\n\n sage: H = Hypergraph([{1,2,3},{2,3,4},{3,4,5},{4,5,6}]); H\n Incidence structure with 6 points and 4 blocks\n sage: view(H) # not tested\n\n With sets of size 4::\n\n sage: g = graphs.Grid2dGraph(5,5)\n sage: C4 = graphs.CycleGraph(4)\n sage: sets = Set(map(Set, g.subgraph_search_iterator(C4, # needs sage.modules\n ....: return_graphs=False)))\n sage: H = Hypergraph(sets) # needs sage.modules\n sage: view(H) # not tested # needs sage.modules sage.plot\n\n TESTS::\n\n # verify that :trac:`30976` is fixed\n sage: IS = IncidenceStructure([1,2,3], [[1,2], [2,3]])\n sage: if latex.has_file("tikz.sty"): # optional - latex\n ....: IS._latex_()\n ...UserWarning:\n The hypergraph is drawn as a set of closed curves...\n \\begin{tikzpicture}...\n \\draw... -- ...;\n \\draw... -- ...;\n \\draw node...;\n \\draw node...;\n \\draw node...;\n \\end{tikzpicture}\n\n '
from sage.functions.trig import arctan2
from warnings import warn
warn('\nThe hypergraph is drawn as a set of closed curves. The curve representing a set S goes **THROUGH** the points contained in S.\n A point which is encircled by a curve but is not located on its boundary is **NOT** included in the corresponding set.\n\nThe colors are picked for readability and have no other meaning.')
latex.add_package_to_preamble_if_available('tikz')
if (not latex.has_file('tikz.sty')):
raise RuntimeError('You must have TikZ installed in order to draw a hypergraph.')
domain = self.ground_set()
pos = self._spring_layout()
tex = '\\begin{tikzpicture}[scale=3]\n'
colors = ['black', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'pink', 'brown']
colored_sets = [(s, i) for (i, S) in enumerate(self.edge_coloring()) for s in S]
for (s, i) in colored_sets:
current_color = colors[(i % len(colors))]
if (len(s) == 2):
s = list(s)
tex += ((((((('\\draw[color=' + str(current_color)) + ',') + 'line width=.1cm,opacity = .6] ') + str(pos[s[0]])) + ' -- ') + str(pos[s[1]])) + ';\n')
continue
tex += (('\\draw[color=' + str(current_color)) + ',line width=.1cm,opacity = .6,line cap=round,line join=round]plot [smooth cycle,tension=1] coordinates {')
(cx, cy) = pos[Set(s)]
s = [pos[_] for _ in s]
s = sorted(s, key=(lambda x_y: arctan2((x_y[0] - cx), (x_y[1] - cy))))
for x in s:
tex += (str(x) + ' ')
tex += '};\n'
for v in domain:
tex += (((('\\draw node[fill,circle,scale=.5,label={90:$' + latex(v)) + '$}] at ') + str(pos[v])) + ' {};\n')
tex += '\\end{tikzpicture}'
return tex
def is_spread(self, spread):
"\n Check whether the input is a spread for ``self``.\n\n A spread of an incidence structure `(P, B)` is a subset of `B` which\n forms a partition of `P`.\n\n INPUT:\n\n - ``spread`` -- iterable; defines the spread\n\n EXAMPLES::\n\n sage: E = IncidenceStructure([[1, 2, 3], [4, 5, 6], [1, 5, 6]])\n sage: E.is_spread([[1, 2, 3], [4, 5, 6]])\n True\n sage: E.is_spread([1, 2, 3, 4, 5, 6])\n Traceback (most recent call last):\n ...\n TypeError: 'sage.rings.integer.Integer' object is not iterable\n sage: E.is_spread([[1, 2, 3, 4], [5, 6]])\n False\n\n Order of blocks or of points within each block doesn't matter::\n\n sage: E = IncidenceStructure([[1, 2, 3], [4, 5, 6], [1, 5, 6]])\n sage: E.is_spread([[5, 6, 4], [3, 1, 2]])\n True\n\n TESTS::\n\n sage: E = IncidenceStructure([])\n sage: E.is_spread([])\n True\n sage: E = IncidenceStructure([[1]])\n sage: E.is_spread([])\n False\n sage: E.is_spread([[1]])\n True\n sage: E = IncidenceStructure([[1], [1]])\n sage: E.is_spread([[1]])\n True\n "
points = set(self.ground_set())
allBlocks = set(map(frozenset, self.blocks()))
for block in spread:
sblock = set(block)
if (sblock not in allBlocks):
return False
if (not points.issuperset(sblock)):
return False
points.difference_update(sblock)
if points:
return False
return True
|
def are_mutually_orthogonal_latin_squares(l, verbose=False):
'\n Check whether the list of matrices in ``l`` form mutually orthogonal latin\n squares.\n\n INPUT:\n\n - ``verbose`` - if ``True`` then print why the list of matrices provided are\n not mutually orthogonal latin squares\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.latin_squares import are_mutually_orthogonal_latin_squares\n sage: m1 = matrix([[0,1,2],[2,0,1],[1,2,0]])\n sage: m2 = matrix([[0,1,2],[1,2,0],[2,0,1]])\n sage: m3 = matrix([[0,1,2],[2,0,1],[1,2,0]])\n sage: are_mutually_orthogonal_latin_squares([m1,m2])\n True\n sage: are_mutually_orthogonal_latin_squares([m1,m3])\n False\n sage: are_mutually_orthogonal_latin_squares([m2,m3])\n True\n sage: are_mutually_orthogonal_latin_squares([m1,m2,m3], verbose=True)\n Squares 0 and 2 are not orthogonal\n False\n\n sage: m = designs.mutually_orthogonal_latin_squares(7,8) # needs sage.schemes\n sage: are_mutually_orthogonal_latin_squares(m) # needs sage.schemes\n True\n\n TESTS:\n\n Not a latin square::\n\n sage: m1 = matrix([[0,1,0],[2,0,1],[1,2,0]])\n sage: m2 = matrix([[0,1,2],[1,2,0],[2,0,1]])\n sage: are_mutually_orthogonal_latin_squares([m1,m2], verbose=True)\n Matrix 0 is not row latin\n False\n sage: m1 = matrix([[0,1,2],[1,0,2],[1,2,0]])\n sage: are_mutually_orthogonal_latin_squares([m1,m2], verbose=True)\n Matrix 0 is not column latin\n False\n sage: m1 = matrix([[0,0,0],[1,1,1],[2,2,2]])\n sage: m2 = matrix([[0,1,2],[0,1,2],[0,1,2]])\n sage: are_mutually_orthogonal_latin_squares([m1,m2])\n False\n '
if (not l):
raise ValueError('the list must be non empty')
n = l[0].ncols()
k = len(l)
if any((((M.ncols() != n) or (M.nrows() != n)) for M in l)):
if verbose:
print('Not all matrices are square matrices of the same dimensions')
return False
for (i, M) in enumerate(l):
if any(((len(set(R)) != n) for R in M)):
if verbose:
print('Matrix {} is not row latin'.format(i))
return False
if any(((len(set(R)) != n) for R in zip(*M))):
if verbose:
print('Matrix {} is not column latin'.format(i))
return False
from .designs_pyx import is_orthogonal_array
return is_orthogonal_array(list(zip(*[[x for R in M for x in R] for M in l])), k, n, verbose=verbose, terminology='MOLS')
|
def mutually_orthogonal_latin_squares(k, n, partitions=False, check=True):
"\n Return `k` Mutually Orthogonal `n\\times n` Latin Squares (MOLS).\n\n For more information on Mutually Orthogonal Latin Squares, see\n :mod:`~sage.combinat.designs.latin_squares`.\n\n INPUT:\n\n - ``k`` (integer) -- number of MOLS. If ``k=None`` it is set to the largest\n value available.\n\n - ``n`` (integer) -- size of the latin square.\n\n - ``partitions`` (boolean) -- a Latin Square can be seen as 3 partitions of\n the `n^2` cells of the array into `n` sets of size `n`, respectively:\n\n * The partition of rows\n * The partition of columns\n * The partition of number (cells numbered with 0, cells numbered with 1,\n ...)\n\n These partitions have the additional property that any two sets from\n different partitions intersect on exactly one element.\n\n When ``partitions`` is set to ``True``, this function returns a list of `k+2`\n partitions satisfying this intersection property instead of the `k+2` MOLS\n (though the data is exactly the same in both cases).\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\n ``True`` by default.\n\n EXAMPLES::\n\n sage: designs.mutually_orthogonal_latin_squares(4,5) # needs sage.schemes\n [\n [0 2 4 1 3] [0 3 1 4 2] [0 4 3 2 1] [0 1 2 3 4]\n [4 1 3 0 2] [3 1 4 2 0] [2 1 0 4 3] [4 0 1 2 3]\n [3 0 2 4 1] [1 4 2 0 3] [4 3 2 1 0] [3 4 0 1 2]\n [2 4 1 3 0] [4 2 0 3 1] [1 0 4 3 2] [2 3 4 0 1]\n [1 3 0 2 4], [2 0 3 1 4], [3 2 1 0 4], [1 2 3 4 0]\n ]\n\n sage: designs.mutually_orthogonal_latin_squares(3,7) # needs sage.schemes\n [\n [0 2 4 6 1 3 5] [0 3 6 2 5 1 4] [0 4 1 5 2 6 3]\n [6 1 3 5 0 2 4] [5 1 4 0 3 6 2] [4 1 5 2 6 3 0]\n [5 0 2 4 6 1 3] [3 6 2 5 1 4 0] [1 5 2 6 3 0 4]\n [4 6 1 3 5 0 2] [1 4 0 3 6 2 5] [5 2 6 3 0 4 1]\n [3 5 0 2 4 6 1] [6 2 5 1 4 0 3] [2 6 3 0 4 1 5]\n [2 4 6 1 3 5 0] [4 0 3 6 2 5 1] [6 3 0 4 1 5 2]\n [1 3 5 0 2 4 6], [2 5 1 4 0 3 6], [3 0 4 1 5 2 6]\n ]\n\n sage: designs.mutually_orthogonal_latin_squares(2,5,partitions=True) # needs sage.schemes\n [[[0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24]],\n [[0, 5, 10, 15, 20],\n [1, 6, 11, 16, 21],\n [2, 7, 12, 17, 22],\n [3, 8, 13, 18, 23],\n [4, 9, 14, 19, 24]],\n [[0, 8, 11, 19, 22],\n [3, 6, 14, 17, 20],\n [1, 9, 12, 15, 23],\n [4, 7, 10, 18, 21],\n [2, 5, 13, 16, 24]],\n [[0, 9, 13, 17, 21],\n [2, 6, 10, 19, 23],\n [4, 8, 12, 16, 20],\n [1, 5, 14, 18, 22],\n [3, 7, 11, 15, 24]]]\n\n What is the maximum number of MOLS of size 8 that Sage knows how to build?::\n\n sage: designs.orthogonal_arrays.largest_available_k(8)-2 # needs sage.schemes\n 7\n\n If you only want to know if Sage is able to build a given set of\n MOLS, query the ``orthogonal_arrays.*`` functions::\n\n sage: designs.orthogonal_arrays.is_available(5+2, 5) # 5 MOLS of order 5\n False\n sage: designs.orthogonal_arrays.is_available(4+2,6) # 4 MOLS of order 6 # needs sage.schemes\n False\n\n Sage, however, is not able to prove that the second MOLS do not exist::\n\n sage: designs.orthogonal_arrays.exists(4+2,6) # 4 MOLS of order 6 # needs sage.schemes\n Unknown\n\n If you ask for such a MOLS then you will respectively get an informative\n ``EmptySetError`` or ``NotImplementedError``::\n\n sage: designs.mutually_orthogonal_latin_squares(5, 5)\n Traceback (most recent call last):\n ...\n EmptySetError: there exist at most n-1 MOLS of size n if n>=2\n sage: designs.mutually_orthogonal_latin_squares(4,6) # needs sage.schemes\n Traceback (most recent call last):\n ...\n NotImplementedError: I don't know how to build 4 MOLS of order 6\n\n TESTS:\n\n The special case `n=1`::\n\n sage: designs.mutually_orthogonal_latin_squares(3, 1)\n [[0], [0], [0]]\n\n Wrong input for `k`::\n\n sage: designs.mutually_orthogonal_latin_squares(None, 1)\n Traceback (most recent call last):\n ...\n TypeError: k must be a positive integer\n\n sage: designs.mutually_orthogonal_latin_squares(-1, 1)\n Traceback (most recent call last):\n ...\n ValueError: k must be positive\n\n sage: designs.mutually_orthogonal_latin_squares(2,10)\n [\n [1 8 9 0 2 4 6 3 5 7] [1 7 6 5 0 9 8 2 3 4]\n [7 2 8 9 0 3 5 4 6 1] [8 2 1 7 6 0 9 3 4 5]\n [6 1 3 8 9 0 4 5 7 2] [9 8 3 2 1 7 0 4 5 6]\n [5 7 2 4 8 9 0 6 1 3] [0 9 8 4 3 2 1 5 6 7]\n [0 6 1 3 5 8 9 7 2 4] [2 0 9 8 5 4 3 6 7 1]\n [9 0 7 2 4 6 8 1 3 5] [4 3 0 9 8 6 5 7 1 2]\n [8 9 0 1 3 5 7 2 4 6] [6 5 4 0 9 8 7 1 2 3]\n [2 3 4 5 6 7 1 8 9 0] [3 4 5 6 7 1 2 8 0 9]\n [3 4 5 6 7 1 2 0 8 9] [5 6 7 1 2 3 4 0 9 8]\n [4 5 6 7 1 2 3 9 0 8], [7 1 2 3 4 5 6 9 8 0]\n ]\n "
from sage.combinat.designs.orthogonal_arrays import orthogonal_array
from sage.matrix.constructor import Matrix
from .database import MOLS_constructions
if (k is None):
raise TypeError('k must be a positive integer')
try:
Integer(k)
except TypeError:
raise
if (k < 0):
raise ValueError('k must be positive')
if (n == 1):
matrices = ([Matrix([[0]])] * k)
elif (k >= n):
raise EmptySetError('there exist at most n-1 MOLS of size n if n>=2')
elif ((n in MOLS_constructions) and (k <= MOLS_constructions[n][0])):
(_, construction) = MOLS_constructions[n]
matrices = construction()[:k]
elif (orthogonal_array((k + 2), n, existence=True) is not Unknown):
if orthogonal_array((k + 2), n, existence=True):
pass
else:
raise EmptySetError('there does not exist {} MOLS of order {}!'.format(k, n))
OA = sorted(orthogonal_array((k + 2), n, check=False))
matrices = [[] for _ in repeat(None, k)]
for L in OA:
for i in range(2, (k + 2)):
matrices[(i - 2)].append(L[i])
matrices = [[M[(i * n):((i + 1) * n)] for i in range(n)] for M in matrices]
matrices = [Matrix(M) for M in matrices]
else:
raise NotImplementedError("I don't know how to build {} MOLS of order {}".format(k, n))
if check:
assert are_mutually_orthogonal_latin_squares(matrices)
if (partitions is True):
partitions = [[[((i * n) + j) for j in range(n)] for i in range(n)], [[((j * n) + i) for j in range(n)] for i in range(n)]]
for m in matrices:
partition = [[] for _ in repeat(None, n)]
for i in range(n):
for j in range(n):
partition[m[(i, j)]].append(((i * n) + j))
partitions.append(partition)
if partitions:
return partitions
else:
return matrices
|
def latin_square_product(M, N, *others):
"\n Return the product of two (or more) latin squares.\n\n Given two Latin Squares `M,N` of respective sizes `m,n`, the direct product\n `M\\times N` of size `mn` is defined by `(M\\times\n N)((i_1,i_2),(j_1,j_2))=(M(i_1,j_1),N(i_2,j_2))` where `i_1,j_1\\in [m],\n i_2,j_2\\in [n]`\n\n Each pair of values `(i,j)\\in [m]\\times [n]` is then relabeled to `in+j`.\n\n This is Lemma 6.25 of [Stinson2004]_.\n\n INPUT:\n\n An arbitrary number of latin squares (greater than 2).\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.latin_squares import latin_square_product\n sage: m=designs.mutually_orthogonal_latin_squares(3,4)[0] # needs sage.schemes\n sage: latin_square_product(m,m,m) # needs sage.schemes\n 64 x 64 sparse matrix over Integer Ring (use the '.str()' method to see the entries)\n "
from sage.matrix.constructor import Matrix
m = M.nrows()
n = N.nrows()
D = {((i, j), (ii, jj)): (M[(i, ii)], N[(j, jj)]) for i in range(m) for ii in range(m) for j in range(n) for jj in range(n)}
L = (lambda i_j: ((i_j[0] * n) + i_j[1]))
D = {(L(c[0]), L(c[1])): L(v) for (c, v) in D.items()}
P = Matrix(D)
if others:
return latin_square_product(P, others[0], *others[1:])
else:
return P
|
def MOLS_table(start, stop=None, compare=False, width=None):
'\n Prints the MOLS table that Sage can produce.\n\n INPUT:\n\n - ``start,stop`` (integers) -- print the table of MOLS for value of `n` such\n that ``start<=n<stop``. If only one integer is given as input, it is\n interpreted as the value of ``stop`` with ``start=0`` (same behaviour as\n ``range``).\n\n - ``compare`` (boolean) -- if sets to ``True`` the MOLS displays\n with `+` and `-` entries its difference with the table from the\n Handbook of Combinatorial Designs (2ed).\n\n - ``width`` (integer) -- the width of each column of the table. By default,\n it is computed from range of values determined by the parameters ``start``\n and ``stop``.\n\n EXAMPLES::\n\n sage: # needs sage.schemes\n sage: from sage.combinat.designs.latin_squares import MOLS_table\n sage: MOLS_table(100)\n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19\n ________________________________________________________________________________\n 0| +oo +oo 1 2 3 4 1 6 7 8 2 10 5 12 4 4 15 16 5 18\n 20| 4 5 3 22 7 24 4 26 5 28 4 30 31 5 4 5 8 36 4 5\n 40| 7 40 5 42 5 6 4 46 8 48 6 5 5 52 5 6 7 7 5 58\n 60| 5 60 5 6 63 7 5 66 5 6 6 70 7 72 5 7 6 6 6 78\n 80| 9 80 8 82 6 6 6 6 7 88 6 7 6 6 6 6 7 96 6 8\n sage: MOLS_table(100, width=4)\n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19\n ____________________________________________________________________________________________________\n 0| +oo +oo 1 2 3 4 1 6 7 8 2 10 5 12 4 4 15 16 5 18\n 20| 4 5 3 22 7 24 4 26 5 28 4 30 31 5 4 5 8 36 4 5\n 40| 7 40 5 42 5 6 4 46 8 48 6 5 5 52 5 6 7 7 5 58\n 60| 5 60 5 6 63 7 5 66 5 6 6 70 7 72 5 7 6 6 6 78\n 80| 9 80 8 82 6 6 6 6 7 88 6 7 6 6 6 6 7 96 6 8\n sage: MOLS_table(100, compare=True)\n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19\n ________________________________________________________________________________\n 0| + +\n 20|\n 40|\n 60| +\n 80|\n sage: MOLS_table(50, 100, compare=True)\n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19\n ________________________________________________________________________________\n 40|\n 60| +\n 80|\n '
from .orthogonal_arrays import largest_available_k
if (stop is None):
(start, stop) = (0, start)
start = (start - (start % 20))
stop = (stop - 1)
stop = (stop + (20 - (stop % 20)))
assert (((start % 20) == 0) and ((stop % 20) == 0))
if (stop <= start):
return
if compare:
handbook_file = open('{}/MOLS_table.txt'.format(COMBINATORIAL_DESIGN_DATA_DIR), 'r')
hb = [int(_) for _ in handbook_file.readlines()[9].split(',')]
handbook_file.close()
if (width is None):
width = max(3, Integer((stop - 1)).ndigits(10))
print(((' ' * (width + 2)) + ' '.join(('{i:>{width}}'.format(i=i, width=width) for i in range(20)))))
print(((' ' * (width + 1)) + ('_' * ((width + 1) * 20))), end='')
for i in range(start, stop):
if ((i % 20) == 0):
print('\n{:>{width}}|'.format(i, width=width), end='')
k = (largest_available_k(i) - 2)
if compare:
if ((i < 2) or (hb[i] == k)):
c = ''
elif (hb[i] < k):
c = '+'
else:
c = '-'
elif (i < 2):
c = '+oo'
else:
c = k
print(' {:>{width}}'.format(c, width=width), end='')
|
def transversal_design(k, n, resolvable=False, check=True, existence=False):
'\n Return a transversal design of parameters `k,n`.\n\n A transversal design of parameters `k, n` is a collection `\\mathcal{S}` of\n subsets of `V = V_1 \\cup \\cdots \\cup V_k` (where the *groups* `V_i` are\n disjoint and have cardinality `n`) such that:\n\n * Any `S \\in \\mathcal{S}` has cardinality `k` and intersects each group on\n exactly one element.\n\n * Any two elements from distincts groups are contained in exactly one\n element of `\\mathcal{S}`.\n\n More general definitions sometimes involve a `\\lambda` parameter, and we\n assume here that `\\lambda=1`.\n\n For more information on transversal designs, see\n `<http://mathworld.wolfram.com/TransversalDesign.html>`_.\n\n INPUT:\n\n - `n,k` -- integers. If ``k is None`` it is set to the largest value\n available.\n\n - ``resolvable`` (boolean) -- set to ``True`` if you want the design to be\n resolvable (see\n :meth:`sage.combinat.designs.incidence_structures.IncidenceStructure.is_resolvable`). The\n `n` classes of the resolvable design are obtained as the first `n` blocks,\n then the next `n` blocks, etc ... Set to ``False`` by default.\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\n ``True`` by default.\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 .. NOTE::\n\n When ``k=None`` and ``existence=True`` the function returns an\n integer, i.e. the largest `k` such that we can build a `TD(k,n)`.\n\n OUTPUT:\n\n The kind of output depends on the input:\n\n - if ``existence=False`` (the default) then the output is a list of lists\n that represent a `TD(k,n)` with\n `V_1=\\{0,\\dots,n-1\\},\\dots,V_k=\\{(k-1)n,\\dots,kn-1\\}`\n\n - if ``existence=True`` and ``k`` is an integer, then the function returns a\n troolean: either ``True``, ``Unknown`` or ``False``\n\n - if ``existence=True`` and ``k=None`` then the output is the largest value\n of ``k`` for which Sage knows how to compute a `TD(k,n)`.\n\n .. SEEALSO::\n\n :func:`orthogonal_array` -- a transversal design `TD(k,n)` is equivalent to an\n orthogonal array `OA(k,n,2)`.\n\n EXAMPLES::\n\n sage: TD = designs.transversal_design(5,5); TD\n Transversal Design TD(5,5)\n sage: TD.blocks()\n [[0, 5, 10, 15, 20], [0, 6, 12, 18, 24], [0, 7, 14, 16, 23],\n [0, 8, 11, 19, 22], [0, 9, 13, 17, 21], [1, 5, 14, 18, 22],\n [1, 6, 11, 16, 21], [1, 7, 13, 19, 20], [1, 8, 10, 17, 24],\n [1, 9, 12, 15, 23], [2, 5, 13, 16, 24], [2, 6, 10, 19, 23],\n [2, 7, 12, 17, 22], [2, 8, 14, 15, 21], [2, 9, 11, 18, 20],\n [3, 5, 12, 19, 21], [3, 6, 14, 17, 20], [3, 7, 11, 15, 24],\n [3, 8, 13, 18, 23], [3, 9, 10, 16, 22], [4, 5, 11, 17, 23],\n [4, 6, 13, 15, 22], [4, 7, 10, 18, 21], [4, 8, 12, 16, 20],\n [4, 9, 14, 19, 24]]\n\n Some examples of the maximal number of transversal Sage is able to build::\n\n sage: TD_4_10 = designs.transversal_design(4,10)\n sage: designs.transversal_design(5,10,existence=True)\n Unknown\n\n For prime powers, there is an explicit construction which gives a\n `TD(n+1,n)`::\n\n sage: designs.transversal_design(4, 3, existence=True)\n True\n sage: designs.transversal_design(674, 673, existence=True)\n True\n\n For other values of ``n`` it depends::\n\n sage: designs.transversal_design(7, 6, existence=True)\n False\n sage: designs.transversal_design(4, 6, existence=True)\n Unknown\n sage: designs.transversal_design(3, 6, existence=True)\n True\n\n sage: designs.transversal_design(11, 10, existence=True)\n False\n sage: designs.transversal_design(4, 10, existence=True)\n True\n sage: designs.transversal_design(5, 10, existence=True)\n Unknown\n\n sage: designs.transversal_design(7, 20, existence=True)\n Unknown\n sage: designs.transversal_design(6, 12, existence=True)\n True\n sage: designs.transversal_design(7, 12, existence=True)\n True\n sage: designs.transversal_design(8, 12, existence=True)\n Unknown\n\n sage: designs.transversal_design(6, 20, existence = True)\n True\n sage: designs.transversal_design(7, 20, existence = True)\n Unknown\n\n If you ask for a transversal design that Sage is not able to build then an\n ``EmptySetError`` or a ``NotImplementedError`` is raised::\n\n sage: designs.transversal_design(47, 100)\n Traceback (most recent call last):\n ...\n NotImplementedError: I don\'t know how to build a TD(47,100)!\n sage: designs.transversal_design(55, 54)\n Traceback (most recent call last):\n ...\n EmptySetError: There exists no TD(55,54)!\n\n Those two errors correspond respectively to the cases where Sage answer\n ``Unknown`` or ``False`` when the parameter ``existence`` is set to\n ``True``::\n\n sage: designs.transversal_design(47, 100, existence=True)\n Unknown\n sage: designs.transversal_design(55, 54, existence=True)\n False\n\n If for a given `n` you want to know the largest `k` for which Sage is able\n to build a `TD(k,n)` just call the function with `k` set to ``None`` and\n ``existence`` set to ``True`` as follows::\n\n sage: designs.transversal_design(None, 6, existence=True)\n 3\n sage: designs.transversal_design(None, 20, existence=True)\n 6\n sage: designs.transversal_design(None, 30, existence=True)\n 6\n sage: designs.transversal_design(None, 120, existence=True)\n 9\n\n TESTS:\n\n The case when `n=1`::\n\n sage: designs.transversal_design(5,1).blocks()\n [[0, 1, 2, 3, 4]]\n\n Obtained through Wilson\'s decomposition::\n\n sage: _ = designs.transversal_design(4,38)\n\n Obtained through product decomposition::\n\n sage: _ = designs.transversal_design(6,60)\n sage: _ = designs.transversal_design(5,60) # checks some tricky divisibility error\n\n For small values of the parameter ``n`` we check the coherence of the\n function :func:`transversal_design`::\n\n sage: for n in range(2,25): # long time -- 15 secs\n ....: i = 2\n ....: while designs.transversal_design(i, n, existence=True) is True:\n ....: i += 1\n ....: _ = designs.transversal_design(i-1, n)\n ....: assert designs.transversal_design(None, n, existence=True) == i - 1\n ....: j = i\n ....: while designs.transversal_design(j, n, existence=True) is Unknown:\n ....: try:\n ....: _ = designs.transversal_design(j, n)\n ....: raise AssertionError("no NotImplementedError")\n ....: except NotImplementedError:\n ....: pass\n ....: j += 1\n ....: k = j\n ....: while k < n+4:\n ....: assert designs.transversal_design(k, n, existence=True) is False\n ....: try:\n ....: _ = designs.transversal_design(k, n)\n ....: raise AssertionError("no EmptySetError")\n ....: except EmptySetError:\n ....: pass\n ....: k += 1\n ....: print("%2d: (%2d, %2d)"%(n,i,j))\n 2: ( 4, 4)\n 3: ( 5, 5)\n 4: ( 6, 6)\n 5: ( 7, 7)\n 6: ( 4, 7)\n 7: ( 9, 9)\n 8: (10, 10)\n 9: (11, 11)\n 10: ( 5, 11)\n 11: (13, 13)\n 12: ( 8, 14)\n 13: (15, 15)\n 14: ( 7, 15)\n 15: ( 7, 17)\n 16: (18, 18)\n 17: (19, 19)\n 18: ( 8, 20)\n 19: (21, 21)\n 20: ( 7, 22)\n 21: ( 8, 22)\n 22: ( 6, 23)\n 23: (25, 25)\n 24: (10, 26)\n\n The special case `n=1`::\n\n sage: designs.transversal_design(3, 1).blocks()\n [[0, 1, 2]]\n sage: designs.transversal_design(None, 1, existence=True)\n +Infinity\n sage: designs.transversal_design(None, 1)\n Traceback (most recent call last):\n ...\n ValueError: there is no upper bound on k when 0<=n<=1\n\n Resolvable TD::\n\n sage: k,n = 5,15\n sage: TD = designs.transversal_design(k,n,resolvable=True)\n sage: TD.is_resolvable()\n True\n sage: r = designs.transversal_design(None,n,resolvable=True,existence=True)\n sage: non_r = designs.transversal_design(None,n,existence=True)\n sage: r + 1 == non_r\n True\n '
if resolvable:
if existence:
return orthogonal_array(k, n, resolvable=True, existence=True)
else:
OA = orthogonal_array(k, n, resolvable=True, check=False)
blocks = [[((i * n) + c) for (i, c) in enumerate(B)] for B in OA]
classes = [blocks[i:(i + n)] for i in range(0, (n * n), n)]
TD = TransversalDesign(blocks, k, n, check=check, copy=False)
TD._classes = classes
return TD
if (k is None):
if ((n == 0) or (n == 1)):
if existence:
from sage.rings.infinity import Infinity
return Infinity
raise ValueError('there is no upper bound on k when 0<=n<=1')
k = orthogonal_array(None, n, existence=True)
if existence:
return k
if (existence and (_OA_cache_get(k, n) is not None)):
return _OA_cache_get(k, n)
if (n == 1):
if existence:
return True
TD = [list(range(k))]
elif (k >= (n + 2)):
if existence:
return False
raise EmptySetError('No Transversal Design exists when k>=n+2 if n>=2')
elif (orthogonal_array(k, n, existence=True) is not Unknown):
if orthogonal_array(k, n, existence=True):
if existence:
return True
else:
if existence:
return False
raise EmptySetError('There exists no TD({},{})!'.format(k, n))
OA = orthogonal_array(k, n, check=False)
TD = [[((i * n) + c) for (i, c) in enumerate(l)] for l in OA]
else:
if existence:
return Unknown
raise NotImplementedError("I don't know how to build a TD({},{})!".format(k, n))
return TransversalDesign(TD, k, n, check=check)
|
class TransversalDesign(GroupDivisibleDesign):
'\n Class for Transversal Designs\n\n INPUT:\n\n - ``blocks`` -- collection of blocks\n\n - ``k,n`` (integers) -- parameters of the transversal design. They can be\n set to ``None`` (default) in which case their value is determined by the\n blocks.\n\n - ``check`` (boolean) -- whether to check that the design is indeed a\n transversal design with the right parameters. Set to ``True`` by default.\n\n EXAMPLES::\n\n sage: designs.transversal_design(None,5)\n Transversal Design TD(6,5)\n sage: designs.transversal_design(None,30)\n Transversal Design TD(6,30)\n sage: designs.transversal_design(None,36)\n Transversal Design TD(10,36)\n '
def __init__(self, blocks, k=None, n=None, check=True, **kwds):
'\n Constructor of the class\n\n EXAMPLES::\n\n sage: designs.transversal_design(None,5)\n Transversal Design TD(6,5)\n '
from math import sqrt
if (k is None):
if blocks:
k = len(blocks[0])
else:
k = 0
if (n is None):
n = round(sqrt(len(blocks)))
self._n = n
self._k = k
if check:
assert is_transversal_design(blocks, k, n)
GroupDivisibleDesign.__init__(self, (k * n), [list(range((i * n), ((i + 1) * n))) for i in range(k)], blocks, check=False, **kwds)
def __repr__(self):
'\n Returns a string describing the transversal design.\n\n EXAMPLES::\n\n sage: designs.transversal_design(None,5)\n Transversal Design TD(6,5)\n sage: designs.transversal_design(None,30)\n Transversal Design TD(6,30)\n sage: designs.transversal_design(None,36)\n Transversal Design TD(10,36)\n '
return 'Transversal Design TD({},{})'.format(self._k, self._n)
|
def is_transversal_design(B, k, n, verbose=False):
'\n Check that a given set of blocks ``B`` is a transversal design.\n\n See :func:`~sage.combinat.designs.orthogonal_arrays.transversal_design`\n for a definition.\n\n INPUT:\n\n - ``B`` -- the list of blocks\n\n - ``k, n`` -- integers\n\n - ``verbose`` (boolean) -- whether to display information about what is\n going wrong.\n\n .. NOTE::\n\n The transversal design must have `\\{0, \\ldots, kn-1\\}` as a ground set,\n partitioned as `k` sets of size `n`: `\\{0, \\ldots, k-1\\} \\sqcup\n \\{k, \\ldots, 2k-1\\} \\sqcup \\cdots \\sqcup \\{k(n-1), \\ldots, kn-1\\}`.\n\n EXAMPLES::\n\n sage: TD = designs.transversal_design(5, 5, check=True) # indirect doctest\n sage: from sage.combinat.designs.orthogonal_arrays import is_transversal_design\n sage: is_transversal_design(TD, 5, 5)\n True\n sage: is_transversal_design(TD, 4, 4)\n False\n '
return is_orthogonal_array([[(x % n) for x in R] for R in B], k, n, verbose=verbose)
|
def wilson_construction(OA, k, r, m, u, check=True, explain_construction=False):
"\n Returns a `OA(k,rm+\\sum_i u_i)` from a truncated `OA(k+s,r)` by Wilson's\n construction.\n\n **Simple form:**\n\n Let `OA` be a truncated `OA(k+s,r)` with `s` truncated columns of sizes\n `u_1,...,u_s`, whose blocks have sizes in `\\{k+b_1,...,k+b_t\\}`. If there\n exist:\n\n - An `OA(k,m+b_i) - b_i.OA(k,1)` for every `1\\leq i\\leq t`\n\n - An `OA(k,u_i)` for every `1\\leq i\\leq s`\n\n Then there exists an `OA(k,rm+\\sum u_i)`. The construction is a\n generalization of Lemma 3.16 in [HananiBIBD]_.\n\n **Brouwer-Van Rees form:**\n\n Let `OA` be a truncated `OA(k+s,r)` with `s` truncated columns of sizes\n `u_1,...,u_s`. Let the set `H_i` of the `u_i` points of column `k+i` be\n partitionned into `\\sum_j H_{ij}`. Let `m_{ij}` be integers\n such that:\n\n - For `0\\leq i <l` there exists an `OA(k,\\sum_j m_{ij}|H_{ij}|)`\n\n - For any block `B\\in OA` intersecting the sets `H_{ij(i)}` there exists an\n `OA(k,m+\\sum_i m_{ij})-\\sum_i OA(k,m_{ij(j)})`.\n\n Then there exists an `OA(k,rm+\\sum_{i,j}m_{ij})`. This construction appears\n in [BvR1982]_.\n\n INPUT:\n\n - ``OA`` -- an incomplete orthogonal array with `k+s` columns. The elements\n of a column of size `c` must belong to `\\{0,...,c\\}`. The missing entries\n of a block are represented by ``None`` values. If ``OA=None``, it is\n defined as a truncated orthogonal arrays with `k+s` columns.\n\n - ``k,r,m`` (integers)\n\n - ``u`` (list) -- two cases depending on the form to use:\n\n - Simple form: a list of length `s` such that column ``k+i`` has size\n ``u[i]``. The untruncated points of column ``k+i`` are assumed to be\n ``[0,...,u[i]-1]``.\n\n - Brouwer-Van Rees form: a list of length `s` such that ``u[i]`` is the\n list of pairs `(m_{i0},|H_{i0}|),...,(m_{ip_i},|H_{ip_i}|)`. The\n untruncated points of column ``k+i`` are assumed to be `[0,...,u_i-1]`\n where `u_i=\\sum_j |H_{ip_i}|`. Besides, the first `|H_{i0}|` points\n represent `H_{i0}`, the next `|H_{i1}|` points represent `H_{i1}`,\n etc...\n\n - ``explain_construction`` (boolean) -- return a string describing\n the construction.\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 REFERENCE:\n\n .. [HananiBIBD] Balanced incomplete block designs and related designs,\n Haim Hanani,\n Discrete Mathematics 11.3 (1975) pages 255-369.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays import wilson_construction\n sage: from sage.combinat.designs.orthogonal_arrays import OA_relabel\n sage: from sage.combinat.designs.orthogonal_arrays_find_recursive import find_wilson_decomposition_with_one_truncated_group\n sage: total = 0\n sage: for k in range(3,8):\n ....: for n in range(1,30):\n ....: if find_wilson_decomposition_with_one_truncated_group(k,n):\n ....: total += 1\n ....: f, args = find_wilson_decomposition_with_one_truncated_group(k,n)\n ....: _ = f(*args)\n sage: total\n 41\n\n sage: print(designs.orthogonal_arrays.explain_construction(7,58))\n Wilson's construction n=8.7+1+1 with master design OA(7+2,8)\n sage: print(designs.orthogonal_arrays.explain_construction(9,115))\n Wilson's construction n=13.8+11 with master design OA(9+1,13)\n sage: print(wilson_construction(None,5,11,21,[[(5,5)]],explain_construction=True))\n Brouwer-van Rees construction n=11.21+(5.5) with master design OA(5+1,11)\n sage: print(wilson_construction(None,71,17,21,[[(4,9),(1,1)],[(9,9),(1,1)]],explain_construction=True))\n Brouwer-van Rees construction n=17.21+(9.4+1.1)+(9.9+1.1) with master design OA(71+2,17)\n\n An example using the Brouwer-van Rees generalization::\n\n sage: from sage.combinat.designs.orthogonal_arrays import is_orthogonal_array\n sage: from sage.combinat.designs.orthogonal_arrays import wilson_construction\n sage: OA = designs.orthogonal_arrays.build(6,11)\n sage: OA = [[x if (i<5 or x<5) else None for i,x in enumerate(R)] for R in OA]\n sage: OAb = wilson_construction(OA,5,11,21,[[(5,5)]])\n sage: is_orthogonal_array(OAb,5,256)\n True\n "
try:
if u:
int(u[0])
except TypeError:
pass
else:
u = [[(1, uu)] for uu in u]
n_trunc = len(u)
if explain_construction:
if (not u):
return 'Product of orthogonal arrays n={}.{}'.format(r, m)
elif all((((len(uu) == 1) and (uu[0][0] == 1)) for uu in u)):
return "Wilson's construction n={}.{}+{} with master design OA({}+{},{})".format(r, m, '+'.join((str(x) for ((_, x),) in u)), k, n_trunc, r)
else:
return 'Brouwer-van Rees construction n={}.{}+{} with master design OA({}+{},{})'.format(r, m, '+'.join(((('(' + '+'.join((((str(x) + '.') + str(mul)) for (mul, x) in uu))) + ')') for uu in u)), k, n_trunc, r)
if (OA is None):
master_design = orthogonal_array((k + n_trunc), r, check=False)
matrix = ([list(range(r))] * k)
for uu in u:
uu = sum((x[1] for x in uu))
matrix.append((list(range(uu)) + ([None] * (r - uu))))
master_design = OA_relabel(master_design, (k + n_trunc), r, matrix=matrix)
else:
master_design = OA
for c in u:
assert all((((m_ij >= 0) and (h_size >= 0)) for (m_ij, h_size) in c))
assert (sum((h_size for (m_ij, h_size) in c)) <= r)
point_to_mij = []
point_to_point_set = []
n = (r * m)
for (i, partition) in enumerate(u):
column_i_point_to_mij = []
column_i_point_to_point_set = []
for (mij, h_size) in partition:
for _ in range(h_size):
column_i_point_to_mij.append(mij)
column_i_point_to_point_set.append(list(range(n, (n + mij))))
n += mij
point_to_mij.append(column_i_point_to_mij)
point_to_point_set.append(column_i_point_to_point_set)
block_to_ij = (lambda B: ((i, j) for (i, j) in enumerate(B[k:]) if (j is not None)))
block_profiles = set((tuple((point_to_mij[i][j] for (i, j) in block_to_ij(B))) for B in master_design))
OA_incomplete = {profile: incomplete_orthogonal_array(k, (m + sum(profile)), profile) for profile in block_profiles}
OA_k_u = {sum(c): orthogonal_array(k, sum(c)) for c in point_to_mij}
OA = []
for B in master_design:
assert all(((x is not None) for x in B[:k]))
matrix = [list(range((i * m), ((i + 1) * m))) for i in B[:k]]
profile = []
for (i, j) in block_to_ij(B):
profile.append(point_to_mij[i][j])
for C in matrix:
C.extend(point_to_point_set[i][j])
OA.extend(OA_relabel(OA_incomplete[tuple(profile)], k, (m + sum(profile)), matrix=matrix))
for i in range(n_trunc):
length = sum(point_to_mij[i])
OA.extend(OA_relabel(OA_k_u[length], k, length, matrix=([sum(point_to_point_set[i], [])] * k)))
if check:
from .designs_pyx import is_orthogonal_array
assert is_orthogonal_array(OA, k, n, 2)
return OA
|
def TD_product(k, TD1, n1, TD2, n2, check=True):
'\n Return the product of two transversal designs.\n\n From a transversal design `TD_1` of parameters `k,n_1` and a transversal\n design `TD_2` of parameters `k,n_2`, this function returns a transversal\n design of parameters `k,n` where `n=n_1\\times n_2`.\n\n Formally, if the groups of `TD_1` are `V^1_1,\\dots,V^1_k` and the groups of\n `TD_2` are `V^2_1,\\dots,V^2_k`, the groups of the product design are\n `V^1_1\\times V^2_1,\\dots,V^1_k\\times V^2_k` and its blocks are the\n `\\{(x^1_1,x^2_1),\\dots,(x^1_k,x^2_k)\\}` where `\\{x^1_1,\\dots,x^1_k\\}` is a\n block of `TD_1` and `\\{x^2_1,\\dots,x^2_k\\}` is a block of `TD_2`.\n\n INPUT:\n\n - ``TD1, TD2`` -- transversal designs.\n\n - ``k,n1,n2`` (integers) -- see above.\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 .. NOTE::\n\n This function uses transversal designs with\n `V_1=\\{0,\\dots,n-1\\},\\dots,V_k=\\{(k-1)n,\\dots,kn-1\\}` both as input and\n output.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays import TD_product\n sage: TD1 = designs.transversal_design(6,7)\n sage: TD2 = designs.transversal_design(6,12)\n sage: TD6_84 = TD_product(6,TD1,7,TD2,12)\n '
N = (n1 * n2)
TD = []
for X1 in TD1:
for X2 in TD2:
TD.append([((x1 * n2) + (x2 % n2)) for (x1, x2) in zip(X1, X2)])
if check:
assert is_transversal_design(TD, k, N)
return TD
|
def orthogonal_array(k, n, t=2, resolvable=False, check=True, existence=False, explain_construction=False):
"\n Return an orthogonal array of parameters `k,n,t`.\n\n An orthogonal array of parameters `k,n,t` is a matrix with `k` columns\n filled with integers from `[n]` in such a way that for any `t` columns, each\n of the `n^t` possible rows occurs exactly once. In\n particular, the matrix has `n^t` rows.\n\n More general definitions sometimes involve a `\\lambda` parameter, and we\n assume here that `\\lambda=1`.\n\n An orthogonal array is said to be *resolvable* if it corresponds to a\n resolvable transversal design (see\n :meth:`sage.combinat.designs.incidence_structures.IncidenceStructure.is_resolvable`).\n\n For more information on orthogonal arrays, see\n :wikipedia:`Orthogonal_array`.\n\n INPUT:\n\n - ``k`` -- (integer) number of columns. If ``k=None`` it is set to the\n largest value available.\n\n - ``n`` -- (integer) number of symbols\n\n - ``t`` -- (integer; default: 2) -- strength of the array\n\n - ``resolvable`` (boolean) -- set to ``True`` if you want the design to be\n resolvable. The `n` classes of the resolvable design are obtained as the\n first `n` blocks, then the next `n` blocks, etc ... Set to ``False`` by\n default.\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\n ``True`` by default.\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 .. NOTE::\n\n When ``k=None`` and ``existence=True`` the function returns an\n integer, i.e. the largest `k` such that we can build a `OA(k,n)`.\n\n - ``explain_construction`` (boolean) -- return a string describing\n the construction.\n\n OUTPUT:\n\n The kind of output depends on the input:\n\n - if ``existence=False`` (the default) then the output is a list of lists\n that represent an orthogonal array with parameters ``k`` and ``n``\n\n - if ``existence=True`` and ``k`` is an integer, then the function returns a\n troolean: either ``True``, ``Unknown`` or ``False``\n\n - if ``existence=True`` and ``k=None`` then the output is the largest value\n of ``k`` for which Sage knows how to compute a `TD(k,n)`.\n\n .. NOTE::\n\n This method implements theorems from [Stinson2004]_. See the code's\n documentation for details.\n\n .. SEEALSO::\n\n When `t=2` an orthogonal array is also a transversal design (see\n :func:`transversal_design`) and a family of mutually orthogonal latin\n squares (see\n :func:`~sage.combinat.designs.latin_squares.mutually_orthogonal_latin_squares`).\n\n TESTS:\n\n The special cases `n=0,1`::\n\n sage: designs.orthogonal_arrays.build(3,0)\n []\n sage: designs.orthogonal_arrays.build(3,1)\n [[0, 0, 0]]\n sage: designs.orthogonal_arrays.largest_available_k(0)\n +Infinity\n sage: designs.orthogonal_arrays.largest_available_k(1)\n +Infinity\n sage: designs.orthogonal_arrays.build(16,0)\n []\n sage: designs.orthogonal_arrays.build(16,1)\n [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]\n\n when `t>2` and `k=None`::\n\n sage: t = 3\n sage: designs.orthogonal_arrays.largest_available_k(5,t=t) == t\n True\n sage: _ = designs.orthogonal_arrays.build(t,5,t)\n "
assert (n >= 0), 'n(={}) must be nonnegative'.format(n)
if resolvable:
assert (t == 2), 'resolvable designs are only handled when t=2'
if (existence and (k is not None)):
return orthogonal_array((k + 1), n, existence=True)
if (k is None):
k = (orthogonal_array(None, n, existence=True) - 1)
if existence:
return k
OA = sorted(orthogonal_array((k + 1), n, check=check))
return [B[1:] for B in OA]
if (k is None):
if existence:
return largest_available_k(n, t)
elif ((n == 0) or (n == 1)):
raise ValueError('there is no upper bound on k when 0<=n<=1')
else:
k = largest_available_k(n, t)
if (k < t):
raise ValueError('undefined for k<t')
if (existence and (_OA_cache_get(k, n) is not None) and (t == 2)):
return _OA_cache_get(k, n)
from .block_design import projective_plane
from .database import OA_constructions, MOLS_constructions, QDM
from .orthogonal_arrays_find_recursive import find_recursive_construction
from .difference_matrices import difference_matrix
may_be_available = (_OA_cache_construction_available(k, n) is not False)
if (n <= 1):
if existence:
return True
if explain_construction:
return 'Trivial construction'
OA = ([([0] * k)] * n)
elif (k >= (n + t)):
if existence:
return False
msg = 'There exists no OA({},{}) as k(={})>n+t-1={}'.format(k, n, k, ((n + t) - 1))
if explain_construction:
return msg
raise EmptySetError(msg)
elif (k <= t):
if existence:
return True
if explain_construction:
return 'Trivial construction [n]^k'
from itertools import product
return [list(x) for x in product(range(n), repeat=k)]
elif (t != 2):
if existence:
return Unknown
msg = 'Only trivial orthogonal arrays are implemented for t>=2'
if explain_construction:
return msg
raise NotImplementedError(msg)
elif (k <= 3):
if existence:
return True
if explain_construction:
return 'Cyclic latin square'
return [[i, j, ((i + j) % n)] for i in range(n) for j in range(n)]
elif ((projective_plane(n, existence=True) is True) or ((k == (n + 1)) and (projective_plane(n, existence=True) is False))):
_OA_cache_set((n + 1), n, projective_plane(n, existence=True))
if (k == (n + 1)):
if existence:
return projective_plane(n, existence=True)
if explain_construction:
return 'From a projective plane of order {}'.format(n)
from .block_design import projective_plane_to_OA
p = projective_plane(n, check=False)
OA = projective_plane_to_OA(p, check=False)
else:
if existence:
return True
if explain_construction:
return 'From a projective plane of order {}'.format(n)
from .block_design import projective_plane_to_OA
p = projective_plane(n, check=False)
OA = [l[:k] for l in projective_plane_to_OA(p, check=False)]
elif (may_be_available and (n in OA_constructions) and (k <= OA_constructions[n][0])):
_OA_cache_set(OA_constructions[n][0], n, True)
if existence:
return True
if explain_construction:
return 'the database contains an OA({},{})'.format(OA_constructions[n][0], n)
(_, construction) = OA_constructions[n]
OA = OA_from_wider_OA(construction(), k)
elif (may_be_available and (n in MOLS_constructions) and ((k - 2) <= MOLS_constructions[n][0])):
_OA_cache_set((MOLS_constructions[n][0] + 2), n, True)
if existence:
return True
elif explain_construction:
return 'the database contains {} MOLS of order {}'.format(MOLS_constructions[n][0], n)
else:
construction = MOLS_constructions[n][1]
mols = construction()
OA = [([i, j] + [m[(i, j)] for m in mols]) for i in range(n) for j in range(n)]
OA = OA_from_wider_OA(OA, k)
elif (may_be_available and ((n, 1) in QDM) and any((((kk >= k) and (mu <= lmbda) and (orthogonal_array(k, u, existence=True) is True)) for ((_, lmbda, mu, u), (kk, _)) in QDM[(n, 1)].items()))):
_OA_cache_set(k, n, True)
for ((nn, lmbda, mu, u), (kk, f)) in QDM[(n, 1)].items():
if ((kk >= k) and (mu <= lmbda) and (orthogonal_array(k, u, existence=True) is True)):
if existence:
return True
elif explain_construction:
return 'the database contains a ({},{};{},{};{})-quasi difference matrix'.format(nn, k, lmbda, mu, u)
(G, M) = f()
M = [R[:k] for R in M]
OA = OA_from_quasi_difference_matrix(M, G, add_col=False)
break
elif (may_be_available and (difference_matrix(n, (k - 1), existence=True) is True)):
_OA_cache_set(k, n, True)
if existence:
return True
if explain_construction:
return 'from a ({},{})-difference matrix'.format(n, (k - 1))
(G, M) = difference_matrix(n, (k - 1))
OA = OA_from_quasi_difference_matrix(M, G, add_col=True)
elif (may_be_available and find_recursive_construction(k, n)):
_OA_cache_set(k, n, True)
if existence:
return True
(f, args) = find_recursive_construction(k, n)
if explain_construction:
return f(*args, explain_construction=True)
OA = f(*args)
else:
_OA_cache_set(k, n, Unknown)
if existence:
return Unknown
elif explain_construction:
return 'No idea'
raise NotImplementedError("I don't know how to build an OA({},{})!".format(k, n))
if check:
assert is_orthogonal_array(OA, k, n, t, verbose=1), 'Sage built an incorrect OA({},{}) O_o'.format(k, n)
return OA
|
def largest_available_k(n, t=2):
'\n Return the largest `k` such that Sage can build an `OA(k,n)`.\n\n INPUT:\n\n - ``n`` (integer)\n\n - ``t`` -- (integer; default: 2) -- strength of the array\n\n EXAMPLES::\n\n sage: designs.orthogonal_arrays.largest_available_k(0)\n +Infinity\n sage: designs.orthogonal_arrays.largest_available_k(1)\n +Infinity\n sage: designs.orthogonal_arrays.largest_available_k(10)\n 4\n sage: designs.orthogonal_arrays.largest_available_k(27)\n 28\n sage: designs.orthogonal_arrays.largest_available_k(100)\n 10\n sage: designs.orthogonal_arrays.largest_available_k(-1)\n Traceback (most recent call last):\n ...\n ValueError: n(=-1) was expected to be >=0\n '
from .block_design import projective_plane
if (n < 0):
raise ValueError('n(={}) was expected to be >=0'.format(n))
if (t < 0):
raise ValueError('t(={}) was expected to be >=0'.format(t))
if ((n == 0) or (n == 1)):
from sage.rings.infinity import Infinity
return Infinity
elif (t == 2):
if (projective_plane(n, existence=True) is True):
return (n + 1)
else:
k = 1
while (_OA_cache_construction_available((k + 1), n) is True):
k = (k + 1)
else:
k = (t - 1)
while (orthogonal_array((k + 1), n, t, existence=True) is True):
k += 1
return k
|
def incomplete_orthogonal_array(k, n, holes, resolvable=False, existence=False):
"\n Return an `OA(k,n)-\\sum_{1\\leq i\\leq x} OA(k,s_i)`.\n\n An `OA(k,n)-\\sum_{1\\leq i\\leq x} OA(k,s_i)` is an orthogonal array from\n which have been removed disjoint `OA(k,s_1),...,OA(k,s_x)`. If there exist\n `OA(k,s_1),...,OA(k,s_x)` they can be used to fill the holes and give rise\n to an `OA(k,n)`.\n\n A very useful particular case (see e.g. the Wilson construction in\n :func:`wilson_construction`) is when all `s_i=1`. In that case the\n incomplete design is a `OA(k,n)-x.OA(k,1)`. Such design is equivalent to\n transversal design `TD(k,n)` from which has been removed `x` disjoint\n blocks.\n\n INPUT:\n\n - ``k,n`` (integers)\n\n - ``holes`` (list of integers) -- respective sizes of the holes to be found.\n\n - ``resolvable`` (boolean) -- set to ``True`` if you want the design to be\n resolvable. The classes of the resolvable design are obtained as the first\n `n` blocks, then the next `n` blocks, etc ... Set to ``False`` by default.\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 .. NOTE::\n\n By convention, the ground set is always `V = \\{0, ..., n-1\\}`.\n\n If all holes have size 1, in the incomplete orthogonal array returned by\n this function the holes are `\\{n-1, ..., n-s_1\\}^k`,\n `\\{n-s_1-1,...,n-s_1-s_2\\}^k`, etc.\n\n More generally, if ``holes`` is equal to `u1,...,uk`, the `i`-th hole is\n the set of points `\\{n-\\sum_{j\\geq i}u_j,...,n-\\sum_{j\\geq i+1}u_j\\}^k`.\n\n .. SEEALSO::\n\n :func:`OA_find_disjoint_blocks`\n\n EXAMPLES::\n\n sage: IOA = designs.incomplete_orthogonal_array(3,3,[1,1,1])\n sage: IOA\n [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]\n sage: missing_blocks = [[0,0,0],[1,1,1],[2,2,2]]\n sage: from sage.combinat.designs.orthogonal_arrays import is_orthogonal_array\n sage: is_orthogonal_array(IOA + missing_blocks,3,3,2)\n True\n\n TESTS:\n\n Affine planes and projective planes::\n\n sage: for q in range(2,100):\n ....: if is_prime_power(q):\n ....: assert designs.incomplete_orthogonal_array(q,q,[1]*q,existence=True)\n ....: assert not designs.incomplete_orthogonal_array(q+1,q,[1]*2,existence=True)\n\n Further tests::\n\n sage: designs.incomplete_orthogonal_array(8,4,[1,1,1],existence=True)\n False\n sage: designs.incomplete_orthogonal_array(5,10,[1,1,1],existence=True)\n Unknown\n sage: designs.incomplete_orthogonal_array(5,10,[1,1,1])\n Traceback (most recent call last):\n ...\n NotImplementedError: I don't know how to build an OA(5,10)!\n sage: designs.incomplete_orthogonal_array(4,3,[1,1])\n Traceback (most recent call last):\n ...\n EmptySetError: There is no OA(n+1,n) - 2.OA(n+1,1) as all blocks intersect in a projective plane.\n sage: n=10\n sage: k=designs.orthogonal_arrays.largest_available_k(n)\n sage: designs.incomplete_orthogonal_array(k,n,[1,1,1],existence=True)\n True\n sage: _ = designs.incomplete_orthogonal_array(k,n,[1,1,1])\n sage: _ = designs.incomplete_orthogonal_array(k,n,[1])\n\n A resolvable `OA(k,n)-n.OA(k,1)`. We check that extending each class and\n adding the `[i,i,...]` blocks turns it into an `OA(k+1,n)`.::\n\n sage: from sage.combinat.designs.orthogonal_arrays import is_orthogonal_array\n sage: k,n=5,7\n sage: OA = designs.incomplete_orthogonal_array(k,n,[1]*n,resolvable=True)\n sage: classes = [OA[i*n:(i+1)*n] for i in range(n-1)]\n sage: for classs in classes: # The design is resolvable !\n ....: assert(len(set(col))==n for col in zip(*classs))\n sage: OA.extend([[i]*(k) for i in range(n)])\n sage: for i,R in enumerate(OA):\n ....: R.append(i//n)\n sage: is_orthogonal_array(OA,k+1,n)\n True\n\n Non-existent resolvable incomplete OA::\n\n sage: designs.incomplete_orthogonal_array(9,13,[1]*10,resolvable=True,existence=True)\n False\n sage: designs.incomplete_orthogonal_array(9,13,[1]*10,resolvable=True)\n Traceback (most recent call last):\n ...\n EmptySetError: There is no resolvable incomplete OA(9,13) whose holes' sizes sum to 10<n(=13)\n\n Error message for big holes::\n\n sage: designs.incomplete_orthogonal_array(6,4*9,[9,9,8])\n Traceback (most recent call last):\n ...\n NotImplementedError: I was not able to build this OA(6,36)-OA(6,8)-2.OA(6,9)\n\n 10 holes of size 9 through the product construction::\n\n sage: # long time\n sage: iOA = designs.incomplete_orthogonal_array(10,153,[9]*10)\n sage: OA9 = designs.orthogonal_arrays.build(10,9)\n sage: for i in range(10):\n ....: iOA.extend([[153-9*(i+1)+x for x in B] for B in OA9])\n sage: is_orthogonal_array(iOA,10,153)\n True\n\n An `OA(9,82)-OA(9,9)-OA(9,1)`::\n\n sage: ioa = designs.incomplete_orthogonal_array(9,82,[9,1])\n sage: ioa.extend([[x+72 for x in B] for B in designs.orthogonal_arrays.build(9,9)])\n sage: ioa.extend([[x+81 for x in B] for B in designs.orthogonal_arrays.build(9,1)])\n sage: is_orthogonal_array(ioa,9,82,verbose=1)\n True\n\n An `OA(9,82)-OA(9,9)-2.OA(9,1)` in different orders::\n\n sage: ioa = designs.incomplete_orthogonal_array(9,82,[1,9,1])\n sage: ioa.extend([[x+71 for x in B] for B in designs.orthogonal_arrays.build(9,1)])\n sage: ioa.extend([[x+72 for x in B] for B in designs.orthogonal_arrays.build(9,9)])\n sage: ioa.extend([[x+81 for x in B] for B in designs.orthogonal_arrays.build(9,1)])\n sage: is_orthogonal_array(ioa,9,82,verbose=1)\n True\n sage: ioa = designs.incomplete_orthogonal_array(9,82,[9,1,1])\n sage: ioa.extend([[x+71 for x in B] for B in designs.orthogonal_arrays.build(9,9)])\n sage: ioa.extend([[x+80 for x in B] for B in designs.orthogonal_arrays.build(9,1)])\n sage: ioa.extend([[x+81 for x in B] for B in designs.orthogonal_arrays.build(9,1)])\n sage: is_orthogonal_array(ioa,9,82,verbose=1)\n True\n\n Three holes of size 1::\n\n sage: ioa = designs.incomplete_orthogonal_array(3,6,[1,1,1])\n sage: ioa.extend([[i]*3 for i in [3,4,5]])\n sage: is_orthogonal_array(ioa,3,6,verbose=1)\n True\n "
from sage.combinat.designs.database import QDM
for h in holes:
if (h < 0):
raise ValueError('Holes must have size >=0, but {} was in the list').format(h)
holes = [h for h in holes if (h > 0)]
if (not holes):
return orthogonal_array(k, n, existence=existence, resolvable=resolvable)
sum_of_holes = sum(holes)
number_of_holes = len(holes)
max_hole = max(holes)
min_hole = min(holes)
if (sum_of_holes > n):
if existence:
return False
raise EmptySetError('The total size of holes must be smaller or equal than the size of the ground set')
if ((max_hole == 1) and resolvable and (sum_of_holes != n)):
if existence:
return False
raise EmptySetError("There is no resolvable incomplete OA({},{}) whose holes' sizes sum to {}<n(={})".format(k, n, sum_of_holes, n))
if ((max_hole == 1) and resolvable):
if existence:
return orthogonal_array((k + 1), n, existence=True)
OA = sorted(orthogonal_array((k + 1), n))
OA = [B[1:] for B in OA]
relabel = [([0] * n) for _ in range(k)]
for (i, B) in enumerate(OA[(- n):]):
for (ii, xx) in enumerate(B):
relabel[ii][xx] = i
OA = [[relabel[i][xx] for (i, xx) in enumerate(B)] for B in OA]
assert all(((OA[((- n) + i)] == ([i] * k)) for i in range(n))), 'The last n blocks should be [i,i,...]'
return OA[:(- n)]
elif ((max_hole == 1) and (number_of_holes <= 1)):
if existence:
return orthogonal_array(k, n, existence=True)
OA = orthogonal_array(k, n)
independent_set = OA[:number_of_holes]
elif ((k >= 3) and (2 <= number_of_holes <= 3) and (n > ((k - 1) * max_hole)) and (holes.count(1) == (number_of_holes - 1)) and incomplete_orthogonal_array(k, n, [max_hole], existence=True)):
if existence:
return True
IOA = incomplete_orthogonal_array(k, n, [max_hole])
i = holes.index(max_hole)
holes[i] = [([ii] * k) for ii in range((n - max_hole), n)]
i = holes.index(1)
for h1 in IOA:
if all(((x < (n - max_hole)) for x in h1)):
break
holes[i] = [h1]
IOA.remove(h1)
if (number_of_holes == 3):
i = holes.index(1)
for h2 in IOA:
if all((((h1[j] != x) and (x < (n - max_hole))) for (j, x) in enumerate(h2))):
break
holes[i] = [h2]
IOA.remove(h2)
holes = sum(holes, [])
holes = [list(h) for h in zip(*holes)]
for l in holes:
for i in range(n):
if (i not in l):
l.insert(0, i)
for i in range(len(holes)):
holes[i] = {v: i for (i, v) in enumerate(holes[i])}
IOA = OA_relabel(IOA, k, n, matrix=holes)
return IOA
elif ((max_hole == 1) and (number_of_holes >= 2) and (k == (n + 1))):
if existence:
return False
raise EmptySetError('There is no OA(n+1,n) - {}.OA(n+1,1) as all blocks intersect in a projective plane.'.format(number_of_holes))
elif ((max_hole == 1) and (orthogonal_array((k + 1), n, existence=True) is True)):
if existence:
return True
OA = orthogonal_array((k + 1), n)
independent_set = [B[:(- 1)] for B in OA if (B[(- 1)] == 0)][:number_of_holes]
OA = [B[:(- 1)] for B in OA]
elif ((max_hole == 1) and (orthogonal_array(k, n, existence=True) is True)):
OA = orthogonal_array(k, n)
try:
independent_set = OA_find_disjoint_blocks(OA, k, n, number_of_holes)
except ValueError:
if existence:
return Unknown
raise NotImplementedError('I was not able to build this OA({},{})-{}.OA({},1)'.format(k, n, number_of_holes, k))
if existence:
return True
independent_set = OA_find_disjoint_blocks(OA, k, n, number_of_holes)
elif ((max_hole == 1) and (not (orthogonal_array(k, n, existence=True) is True))):
return orthogonal_array(k, n, existence=existence)
elif ((number_of_holes == 1) and any((((uu == sum_of_holes) and (mu <= 1) and (lmbda == 1) and (k <= (kk + 1))) for ((nn, lmbda, mu, uu), (kk, _)) in QDM.get((n, 1), {}).items()))):
for ((nn, lmbda, mu, uu), (kk, f)) in QDM[(n, 1)].items():
if ((uu == sum_of_holes) and (mu <= 1) and (lmbda == 1) and (k <= (kk + 1))):
break
(G, M) = f()
OA = OA_from_quasi_difference_matrix(M, G, fill_hole=False)
return [B[:k] for B in OA]
elif ((min_hole > 1) and (max_hole == min_hole) and ((n % min_hole) == 0) and orthogonal_array(k, min_hole, existence=True) and incomplete_orthogonal_array(k, (n // min_hole), ([1] * number_of_holes), existence=True)):
if existence:
return True
h = min_hole
iOA1 = incomplete_orthogonal_array(k, (n // holes[0]), ([1] * number_of_holes))
iOA2 = orthogonal_array(k, h)
return [[((B1[i] * h) + B2[i]) for i in range(k)] for B1 in iOA1 for B2 in iOA2]
else:
if existence:
return Unknown
f = (lambda x: ('' if (x == 1) else '{}.'.format(x)))
holes_string = ''.join(('-{}OA({},{})'.format(f(holes.count(x)), k, x) for x in sorted(set(holes))))
raise NotImplementedError('I was not able to build this OA({},{}){}'.format(k, n, holes_string))
assert (number_of_holes == len(independent_set))
for B in independent_set:
OA.remove(B)
OA = OA_relabel(OA, k, n, blocks=independent_set)
return OA
|
def OA_find_disjoint_blocks(OA, k, n, x, *, solver=None, integrality_tolerance=0.001):
'\n Return `x` disjoint blocks contained in a given `OA(k,n)`.\n\n `x` blocks of an `OA` are said to be disjoint if they all have\n different values for a every given index, i.e. if they correspond to\n disjoint blocks in the `TD` associated with the `OA`.\n\n INPUT:\n\n - ``OA`` -- an orthogonal array\n\n - ``k``, ``n``, ``x`` (integers)\n\n - ``solver`` -- (default: ``None``) Specify a Mixed Integer Linear\n Programming (MILP) solver to be used. If set to ``None``, the default one\n is used. For more information on MILP solvers and which default solver is\n used, see the method :meth:`solve\n <sage.numerical.mip.MixedIntegerLinearProgram.solve>` of the class\n :class:`MixedIntegerLinearProgram\n <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``integrality_tolerance`` -- parameter for use with MILP solvers over an\n inexact base ring; see :meth:`MixedIntegerLinearProgram.get_values`.\n\n .. SEEALSO::\n\n :func:`incomplete_orthogonal_array`\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays import OA_find_disjoint_blocks\n sage: k=3;n=4;x=3\n sage: Bs = OA_find_disjoint_blocks(designs.orthogonal_arrays.build(k,n),k,n,x)\n sage: assert len(Bs) == x\n sage: for i in range(k):\n ....: assert len(set([B[i] for B in Bs])) == x\n sage: OA_find_disjoint_blocks(designs.orthogonal_arrays.build(k,n),k,n,5)\n Traceback (most recent call last):\n ...\n ValueError: There does not exist 5 disjoint blocks in this OA(3,4)\n '
from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException
p = MixedIntegerLinearProgram(solver=solver)
b = p.new_variable(binary=True)
p.add_constraint((p.sum((b[i] for i in range(len(OA)))) == x))
t = [[[] for _ in range(n)] for _ in range(k)]
for (c, B) in enumerate(OA):
for (i, j) in enumerate(B):
t[i][j].append(c)
for R in t:
for L in R:
p.add_constraint((p.sum((b[i] for i in L)) <= 1))
try:
p.solve()
except MIPSolverException:
raise ValueError('There does not exist {} disjoint blocks in this OA({},{})'.format(x, k, n))
b = p.get_values(b, convert=bool, tolerance=integrality_tolerance)
independent_set = [OA[i] for (i, v) in b.items() if v]
return independent_set
|
def OA_relabel(OA, k, n, blocks=tuple(), matrix=None, symbol_list=None):
'\n Return a relabelled version of the OA.\n\n INPUT:\n\n - ``OA`` -- an OA, or rather a list of blocks of length `k`, each\n of which contains integers from `0` to `n-1`.\n\n - ``k,n`` (integers)\n\n - ``blocks`` (list of blocks) -- relabels the integers of the OA\n from `[0..n-1]` into `[0..n-1]` in such a way that the `i`\n blocks from ``block`` are respectively relabeled as\n ``[n-i,...,n-i]``, ..., ``[n-1,...,n-1]``. Thus, the blocks from\n this list are expected to have disjoint values for each\n coordinate.\n\n If set to the empty list (default) no such relabelling is\n performed.\n\n - ``matrix`` -- a matrix of dimensions `k,n` such that if the i th\n coordinate of a block is `x`, this `x` will be relabelled with\n ``matrix[i][x]``. This is not necessarily an integer between `0`\n and `n-1`, and it is not necessarily an integer either. This is\n performed *after* the previous relabelling.\n\n If set to ``None`` (default) no such relabelling is performed.\n\n - ``symbol_list`` -- a list of the desired symbols for the\n relabelled OA. If this is not ``None``, the same relabelling is\n done on all blocks such that the index of an element in\n symbol_list is its preimage in the relabelling map.\n\n .. NOTE::\n\n A ``None`` coordinate in one block remains a ``None``\n coordinate in the final block.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays import OA_relabel\n sage: OA = designs.orthogonal_arrays.build(3,2)\n sage: OA_relabel(OA,3,2,matrix=[["A","B"],["C","D"],["E","F"]])\n [[\'A\', \'C\', \'E\'], [\'A\', \'D\', \'F\'], [\'B\', \'C\', \'F\'], [\'B\', \'D\', \'E\']]\n\n sage: TD = OA_relabel(OA,3,2,matrix=[[0,1],[2,3],[4,5]]); TD\n [[0, 2, 4], [0, 3, 5], [1, 2, 5], [1, 3, 4]]\n sage: from sage.combinat.designs.orthogonal_arrays import is_transversal_design\n sage: is_transversal_design(TD,3,2)\n True\n\n sage: OA = designs.orthogonal_arrays.build(3,2)\n sage: OA_relabel(OA, 3, 2, symbol_list=[\'A\', \'B\'])\n [[\'A\', \'A\', \'A\'], [\'A\', \'B\', \'B\'], [\'B\', \'A\', \'B\'], [\'B\', \'B\', \'A\']]\n\n Making sure that ``[2,2,2,2]`` is a block of `OA(4,3)`. We do this\n by relabelling block ``[0,0,0,0]`` which belongs to the design::\n\n sage: designs.orthogonal_arrays.build(4,3)\n [[0, 0, 0, 0], [0, 1, 2, 1], [0, 2, 1, 2], [1, 0, 2, 2], [1, 1, 1, 0], [1, 2, 0, 1], [2, 0, 1, 1], [2, 1, 0, 2], [2, 2, 2, 0]]\n sage: OA_relabel(designs.orthogonal_arrays.build(4,3),4,3,blocks=[[0,0,0,0]])\n [[2, 2, 2, 2], [2, 0, 1, 0], [2, 1, 0, 1], [0, 2, 1, 1], [0, 0, 0, 2], [0, 1, 2, 0], [1, 2, 0, 0], [1, 0, 2, 1], [1, 1, 1, 2]]\n\n TESTS::\n\n sage: OA_relabel(designs.orthogonal_arrays.build(3,2),3,2,blocks=[[0,1],[0,1]])\n Traceback (most recent call last):\n ...\n RuntimeError: Two block have the same coordinate for one of the k dimensions\n\n '
if blocks:
l = []
for (i, B) in enumerate(zip(*blocks)):
if (len(B) != len(set(B))):
raise RuntimeError('Two block have the same coordinate for one of the k dimensions')
l.append(dict(zip(([xx for xx in range(n) if (xx not in B)] + list(B)), range(n))))
OA = [[l[i][x] for (i, x) in enumerate(R)] for R in OA]
if matrix:
OA = [[(matrix[i][j] if (j is not None) else None) for (i, j) in enumerate(R)] for R in OA]
if symbol_list:
mapping = {index: symbol for (index, symbol) in enumerate(symbol_list)}
OA = [[mapping[element] for element in row] for row in OA]
return OA
|
def OA_standard_label(OA):
"\n Return the inputted OA with entries relabelled as integers [0,...,n-1].\n\n INPUT:\n\n - ``OA`` -- a list of lists with symbols as entries that are not\n necessarily integers.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays import OA_standard_label\n sage: C = [['a', 'a', 'a', 'b'],\n ....: ['a', 'a', 'b', 'a'],\n ....: ['a', 'b', 'a', 'a'],\n ....: ['b', 'a', 'a', 'a'],\n ....: ['b', 'b', 'b', 'b']]\n sage: OA_standard_label(C)\n [[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1]]\n\n "
symbol_list = sorted({x for l in OA for x in l})
mapping = {symbol: index for (index, symbol) in enumerate(symbol_list)}
return [[mapping[element] for element in row] for row in OA]
|
def OA_n_times_2_pow_c_from_matrix(k, c, G, A, Y, check=True):
'\n Return an `OA(k, |G| \\cdot 2^c)` from a constrained `(G,k-1,2)`-difference\n matrix.\n\n This construction appears in [AC1994]_ and [Ab1995]_.\n\n Let `G` be an additive Abelian group. We denote by `H` a `GF(2)`-hyperplane\n in `GF(2^c)`.\n\n Let `A` be a `(k-1) \\times 2|G|` array with entries in `G \\times GF(2^c)`\n and `Y` be a vector with `k-1` entries in `GF(2^c)`. Let `B` and `C` be\n respectively the part of the array that belong to `G` and `GF(2^c)`.\n\n The input `A` and `Y` must satisfy the following conditions. For any `i \\neq\n j` and `g \\in G`:\n\n - there are exactly two values of `s` such that `B_{i,s} - B_{j,s} = g`\n (i.e. `B` is a `(G,k-1,2)`-difference matrix),\n\n - let `s_1` and `s_2` denote the two values of `s` given above, then exactly\n one of `C_{i,s_1} - C_{j,s_1}` and `C_{i,s_2} - C_{j,s_2}` belongs to the\n `GF(2)`-hyperplane `(Y_i - Y_j) \\cdot H` (we implicitly assumed that `Y_i\n \\not= Y_j`).\n\n Under these conditions, it is easy to check that the array whose `k-1` rows\n of length `|G|\\cdot 2^c` indexed by `1 \\leq i \\leq k-1` given by `A_{i,s} +\n (0, Y_i \\cdot v)` where `1\\leq s \\leq 2|G|,v\\in H` is a `(G \\times\n GF(2^c),k-1,1)`-difference matrix.\n\n INPUT:\n\n - ``k,c`` (integers) -- integers\n\n - ``G`` -- an additive Abelian group\n\n - ``A`` -- a matrix with entries in `G \\times GF(2^c)`\n\n - ``Y`` -- a vector with entries in `GF(2^c)`\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\n ``True`` by default.\n\n .. NOTE::\n\n By convention, a multiplicative generator `w` of `GF(2^c)^*` is fixed\n (inside the function). The hyperplane `H` is the one spanned by `w^0,\n w^1, \\ldots, w^{c-1}`. The `GF(2^c)` part of the input matrix `A` and\n vector `Y` are given in the following form: the integer `i` corresponds\n to the element `w^i` and ``None`` corresponds to `0`.\n\n .. SEEALSO::\n\n Several examples use this construction:\n\n - :func:`~sage.combinat.designs.database.OA_9_40`\n - :func:`~sage.combinat.designs.database.OA_11_80`\n - :func:`~sage.combinat.designs.database.OA_15_112`\n - :func:`~sage.combinat.designs.database.OA_11_160`\n - :func:`~sage.combinat.designs.database.OA_16_176`\n - :func:`~sage.combinat.designs.database.OA_16_208`\n - :func:`~sage.combinat.designs.database.OA_15_224`\n - :func:`~sage.combinat.designs.database.OA_20_352`\n - :func:`~sage.combinat.designs.database.OA_20_416`\n - :func:`~sage.combinat.designs.database.OA_20_544`\n - :func:`~sage.combinat.designs.database.OA_11_640`\n - :func:`~sage.combinat.designs.database.OA_15_896`\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays import OA_n_times_2_pow_c_from_matrix\n sage: from sage.combinat.designs.designs_pyx import is_orthogonal_array\n sage: A = [\n ....: [(0,None),(0,None),(0,None),(0,None),(0,None),(0,None),(0,None),(0,None),(0,None),(0,None)],\n ....: [(0,None),(1,None), (2,2), (3,2), (4,2),(2,None),(3,None),(4,None), (0,2), (1,2)],\n ....: [(0,None), (2,5), (4,5), (1,2), (3,6), (3,4), (0,0), (2,1), (4,1), (1,6)],\n ....: [(0,None), (3,4), (1,4), (4,0), (2,5),(3,None), (1,0), (4,1), (2,2), (0,3)],\n ....: ]\n sage: Y = [None, 0, 1, 6]\n sage: OA = OA_n_times_2_pow_c_from_matrix(5,3,GF(5),A,Y)\n sage: is_orthogonal_array(OA,5,40,2)\n True\n\n sage: A[0][0] = (1,None)\n sage: OA_n_times_2_pow_c_from_matrix(5,3,GF(5),A,Y)\n Traceback (most recent call last):\n ...\n ValueError: the first part of the matrix A must be a\n (G,k-1,2)-difference matrix\n\n sage: A[0][0] = (0,0)\n sage: OA_n_times_2_pow_c_from_matrix(5,3,GF(5),A,Y)\n Traceback (most recent call last):\n ...\n ValueError: B_2,0 - B_0,0 = B_2,6 - B_0,6 but the associated part of the\n matrix C does not satisfies the required condition\n '
from sage.rings.finite_rings.finite_field_constructor import FiniteField
from itertools import combinations
from .designs_pyx import is_difference_matrix
G_card = G.cardinality()
if ((len(A) != (k - 1)) or any(((len(a) != (2 * G_card)) for a in A))):
raise ValueError('A must be a (k-1) x (2|G|) array')
if (len(Y) != (k - 1)):
raise ValueError('Y must be a (k-1)-vector')
F = FiniteField((2 ** c), 'w')
GG = G.cartesian_product(F)
w = F.multiplicative_generator()
r = {i: (w ** i) for i in range(((2 ** c) - 1))}
r[None] = F.zero()
B = [[G(a) for (a, b) in R] for R in A]
if (check and (not is_difference_matrix(list(zip(*B)), G, (k - 1), 2))):
raise ValueError('the first part of the matrix A must be a (G,k-1,2)-difference matrix')
A = [[GG((G(a), r[b])) for (a, b) in R] for R in A]
Y = [r[b] for b in Y]
H = [sum((r[i] for i in S), F.zero()) for s in range(c) for S in combinations(range((c - 1)), s)]
assert (len(H) == (2 ** (c - 1)))
if check:
G_card = G.cardinality()
for i in range(len(B)):
for j in range(i):
g_to_col_indices = {g: [] for g in G}
Hij = set([((Y[i] - Y[j]) * v) for v in H])
for s in range((2 * G_card)):
g_to_col_indices[(B[i][s] - B[j][s])].append(s)
for (s1, s2) in g_to_col_indices.values():
v1 = (A[i][s1][1] - A[j][s1][1])
v2 = (A[i][s2][1] - A[j][s2][1])
if ((v1 in Hij) == (v2 in Hij)):
raise ValueError('B_{},{} - B_{},{} = B_{},{} - B_{},{} but the associated part of the matrix C does not satisfies the required condition'.format(i, s1, j, s1, i, s2, j, s2))
Mb = [[(e + GG((G.zero(), (x * v)))) for v in H for e in R] for (x, R) in zip(Y, A)]
return OA_from_quasi_difference_matrix(list(zip(*Mb)), GG, add_col=True)
|
def OA_from_quasi_difference_matrix(M, G, add_col=True, fill_hole=True):
'\n Return an Orthogonal Array from a Quasi-Difference matrix\n\n **Difference Matrices**\n\n Let `G` be a group of order `g`. A *difference matrix* `M` is a `g\\times k`\n matrix with entries from `G` such that for any `1\\leq i < j < k` the set\n `\\{d_{li}-d_{lj}:1\\leq l \\leq g\\}` is equal to `G`.\n\n By concatenating the `g` matrices `M+x` (where `x\\in G`), one obtains a\n matrix of size `g^2\\times x` which is also an `OA(k,g)`.\n\n **Quasi-difference Matrices**\n\n A quasi-difference matrix is a difference matrix with missing entries. The\n construction above can be applied again in this case, where the missing\n entries in each column of `M` are replaced by unique values on which `G` has\n a trivial action.\n\n This produces an incomplete orthogonal array with a "hole" (i.e. missing\n rows) of size \'u\' (i.e. the number of missing values per column of `M`). If\n there exists an `OA(k,u)`, then adding the rows of this `OA(k,u)` to the\n incomplete orthogonal array should lead to an OA...\n\n **Formal definition** (from the Handbook of Combinatorial Designs [DesignHandbook]_)\n\n Let `G` be an abelian group of order `n`. A\n `(n,k;\\lambda,\\mu;u)`-quasi-difference matrix (QDM) is a matrix `Q=(q_{ij})`\n with `\\lambda(n-1+2u)+\\mu` rows and `k` columns, with each entry either\n empty or containing an element of `G`. Each column contains exactly `\\lambda\n u` entries, and each row contains at most one empty entry. Furthermore, for\n each `1 \\leq i < j \\leq k` the multiset\n\n .. MATH::\n\n \\{ q_{li} - q_{lj}: 1 \\leq l \\leq \\lambda (n-1+2u)+\\mu, \\text{ with }q_{li}\\text{ and }q_{lj}\\text{ not empty}\\}\n\n contains every nonzero element of `G` exactly `\\lambda` times, and contains\n 0 exactly `\\mu` times.\n\n **Construction**\n\n If a `(n,k;\\lambda,\\mu;u)`-QDM exists and `\\mu \\leq \\lambda`, then an\n `ITD_\\lambda (k,n+u;u)` exists. Start with a `(n,k;\\lambda,\\mu;u)`-QDM `A`\n over the group `G`. Append `\\lambda-\\mu` rows of zeroes. Then select `u`\n elements `\\infty_1,\\dots,\\infty_u` not in `G`, and replace the empty\n entries, each by one of these infinite symbols, so that `\\infty_i` appears\n exactly once in each column. Develop the resulting matrix over the group `G`\n (leaving infinite symbols fixed), to obtain a `\\lambda (n^2+2nu)\\times k`\n matrix `T`. Then `T` is an orthogonal array with `k` columns and index\n `\\lambda`, having `n+u` symbols and one hole of size `u`.\n\n Adding to `T` an `OA(k,u)` with elements `\\infty_1,\\dots,\\infty_u` yields\n the `ITD_\\lambda(k,n+u;u)`.\n\n For more information, see the Handbook of Combinatorial Designs\n [DesignHandbook]_ or\n `<http://web.cs.du.edu/~petr/milehigh/2013/Colbourn.pdf>`_.\n\n INPUT:\n\n - ``M`` -- the difference matrix whose entries belong to ``G``\n\n - ``G`` -- a group\n\n - ``add_col`` (boolean) -- whether to add a column to the final OA equal to\n `(x_1,\\dots,x_g,x_1,\\dots,x_g,\\dots)` where `G=\\{x_1,\\dots,x_g\\}`.\n\n - ``fill_hole`` (boolean) -- whether to return the incomplete orthogonal\n array, or complete it with the `OA(k,u)` (default). When ``fill_hole is\n None``, no block of the incomplete OA contains more than one value `\\geq\n |G|`.\n\n EXAMPLES::\n\n sage: _ = designs.orthogonal_arrays.build(6,20) # indirect doctest\n '
Gn = int(G.cardinality())
k = (len(M[0]) + bool(add_col))
G_to_int = {x: i for (i, x) in enumerate(G)}
G_sum = [([0] * Gn) for _ in range(Gn)]
for (x, i) in G_to_int.items():
for (xx, ii) in G_to_int.items():
G_sum[i][ii] = G_to_int[(x + xx)]
M = [[(None if (x is None) else G_to_int[G(x)]) for x in line] for line in M]
new_M = []
for line in zip(*M):
inf = Gn
new_line = []
for x in line:
if (x is None):
new_line.extend(([inf] * Gn))
inf = (inf + 1)
else:
new_line.extend(G_sum[x])
new_M.append(new_line)
if add_col:
new_M.append([(i // Gn) for i in range(len(new_line))])
new_M = list(zip(*new_M))
if ((inf > Gn) and fill_hole):
for L in orthogonal_array(k, (inf - Gn), 2):
new_M.append(tuple([(x + Gn) for x in L]))
return new_M
|
def OA_from_Vmt(m, t, V):
'\n Return an Orthogonal Array from a `V(m,t)`\n\n INPUT:\n\n - ``m,t`` (integers)\n\n - ``V`` -- the vector `V(m,t)`.\n\n .. SEEALSO::\n\n - :func:`QDM_from_Vmt`\n\n - :func:`OA_from_quasi_difference_matrix`\n\n EXAMPLES::\n\n sage: _ = designs.orthogonal_arrays.build(6,46) # indirect doctest\n '
(Fq, M) = QDM_from_Vmt(m, t, V)
return OA_from_quasi_difference_matrix(M, Fq, add_col=False)
|
def QDM_from_Vmt(m, t, V):
'\n Return a QDM from a `V(m,t)`\n\n **Definition**\n\n Let `q` be a prime power and let `q=mt+1` for `m,t` integers. Let `\\omega`\n be a primitive element of `\\GF{q}`. A `V(m,t)` vector is a vector\n `(a_1,\\dots,a_{m+1}` for which, for each `1\\leq k < m`, the differences\n\n .. MATH::\n\n \\{a_{i+k}-a_i:1\\leq i \\leq m+1,i+k\\neq m+2\\}\n\n represent the `m` cyclotomic classes of `\\GF{mt+1}` (compute subscripts\n modulo `m+2`). In other words, for fixed `k`, is\n `a_{i+k}-a_i=\\omega^{mx+\\alpha}` and `a_{j+k}-a_j=\\omega^{my+\\beta}` then\n `\\alpha\\not\\equiv\\beta \\mod{m}`\n\n *Construction of a quasi-difference matrix from a `V(m,t)` vector*\n\n Starting with a `V(m,t)` vector `(a_1,\\dots,a_{m+1})`, form a single row of\n length `m+2` whose first entry is empty, and whose remaining entries are\n `(a_1,\\dots,a_{m+1})`. Form `t` rows by multiplying this row by the `t` th\n roots, i.e. the powers of `\\omega^m`. From each of these `t` rows, form\n `m+2` rows by taking the `m+2` cyclic shifts of the row. The result is a\n `(a,m+2;1,0;t)-QDM`.\n\n For more information, refer to the Handbook of Combinatorial Designs\n [DesignHandbook]_.\n\n INPUT:\n\n - ``m,t`` (integers)\n\n - ``V`` -- the vector `V(m,t)`.\n\n .. SEEALSO::\n\n :func:`OA_from_quasi_difference_matrix`\n\n EXAMPLES::\n\n sage: _ = designs.orthogonal_arrays.build(6,46) # indirect doctest\n '
from sage.rings.finite_rings.finite_field_constructor import FiniteField
q = ((m * t) + 1)
Fq = FiniteField(q, 'x')
w = Fq.multiplicative_generator()
M = []
wm = (w ** m)
for i in range(t):
L = [None]
for e in V:
L.append((e * (wm ** i)))
for ii in range((m + 2)):
M.append((L[(- ii):] + L[:(- ii)]))
M.append(([0] * (m + 2)))
return (Fq, M)
|
def OA_from_PBD(k, n, PBD, check=True):
'\n Return an `OA(k,n)` from a PBD\n\n **Construction**\n\n Let `\\mathcal B` be a `(n,K,1)`-PBD. If there exists for every `i\\in K` a\n `TD(k,i)-i\\times TD(k,1)` (i.e. if there exist `k` idempotent MOLS), then\n one can obtain a `OA(k,n)` by concatenating:\n\n - A `TD(k,i)-i\\times TD(k,1)` defined over the elements of `B` for every `B\n \\in \\mathcal B`.\n\n - The rows `(i,...,i)` of length `k` for every `i\\in [n]`.\n\n .. NOTE::\n\n This function raises an exception when Sage is unable to build the\n necessary designs.\n\n INPUT:\n\n - ``k,n`` (integers)\n\n - ``PBD`` -- a PBD on `0,...,n-1`.\n\n EXAMPLES:\n\n We start from the example VI.1.2 from the [DesignHandbook]_ to build an\n `OA(3,10)`::\n\n sage: from sage.combinat.designs.orthogonal_arrays import OA_from_PBD\n sage: from sage.combinat.designs.designs_pyx import is_orthogonal_array\n sage: pbd = [[0,1,2,3],[0,4,5,6],[0,7,8,9],[1,4,7],[1,5,8],\n ....: [1,6,9],[2,4,9],[2,5,7],[2,6,8],[3,4,8],[3,5,9],[3,6,7]]\n sage: oa = OA_from_PBD(3,10,pbd)\n sage: is_orthogonal_array(oa, 3, 10)\n True\n\n But we cannot build an `OA(4,10)` for this PBD (although there\n exists an `OA(4,10)`::\n\n sage: OA_from_PBD(4,10,pbd)\n Traceback (most recent call last):\n ...\n EmptySetError: There is no OA(n+1,n) - 3.OA(n+1,1)\n as all blocks intersect in a projective plane.\n\n Or an `OA(3,6)` (as the PBD has 10 points)::\n\n sage: _ = OA_from_PBD(3,6,pbd)\n Traceback (most recent call last):\n ...\n RuntimeError: PBD is not a valid Pairwise Balanced Design on [0,...,5]\n '
K = set(map(len, PBD))
if check:
from .designs_pyx import is_pairwise_balanced_design
if (not is_pairwise_balanced_design(PBD, n, K)):
raise RuntimeError('PBD is not a valid Pairwise Balanced Design on [0,...,{}]'.format((n - 1)))
OAs = {i: incomplete_orthogonal_array(k, i, ((1,) * i)) for i in K}
OA = []
for S in PBD:
for B in OAs[len(S)]:
OA.append([S[i] for i in B])
for i in range(n):
OA.append(([i] * k))
if check:
assert is_orthogonal_array(OA, k, n, 2)
return OA
|
def OA_from_wider_OA(OA, k):
'\n Return the first `k` columns of `OA`.\n\n If `OA` has `k` columns, this function returns `OA` immediately.\n\n INPUT:\n\n - ``OA`` -- an orthogonal array.\n\n - ``k`` (integer)\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays import OA_from_wider_OA\n sage: OA_from_wider_OA(designs.orthogonal_arrays.build(6,20,2),1)[:5]\n [(19,), (19,), (19,), (19,), (19,)]\n sage: _ = designs.orthogonal_arrays.build(5,46) # indirect doctest\n\n '
if (len(OA[0]) == k):
return OA
return [L[:k] for L in OA]
|
class OAMainFunctions():
"\n Functions related to orthogonal arrays.\n\n An orthogonal array of parameters `k,n,t` is a matrix with `k` columns\n filled with integers from `[n]` in such a way that for any `t` columns, each\n of the `n^t` possible rows occurs exactly once. In particular, the matrix\n has `n^t` rows.\n\n For more information on orthogonal arrays, see\n :wikipedia:`Orthogonal_array`.\n\n From here you have access to:\n\n - :meth:`build(k,n,t=2) <build>`: return an orthogonal array with the given\n parameters.\n - :meth:`is_available(k,n,t=2) <is_available>`: answer whether there is a\n construction available in Sage for a given set of parameters.\n - :meth:`exists(k,n,t=2) <exists>`: answer whether an orthogonal array with\n these parameters exist.\n - :meth:`largest_available_k(n,t=2) <largest_available_k>`: return the\n largest integer `k` such that Sage knows how to build an `OA(k,n)`.\n - :meth:`explain_construction(k,n,t=2) <explain_construction>`: return a\n string that explains the construction that Sage uses to build an\n `OA(k,n)`.\n\n EXAMPLES::\n\n sage: designs.orthogonal_arrays.build(3,2)\n [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]]\n\n sage: designs.orthogonal_arrays.build(5,5)\n [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 1, 3],\n [0, 3, 1, 4, 2], [0, 4, 3, 2, 1], [1, 0, 4, 3, 2],\n [1, 1, 1, 1, 1], [1, 2, 3, 4, 0], [1, 3, 0, 2, 4],\n [1, 4, 2, 0, 3], [2, 0, 3, 1, 4], [2, 1, 0, 4, 3],\n [2, 2, 2, 2, 2], [2, 3, 4, 0, 1], [2, 4, 1, 3, 0],\n [3, 0, 2, 4, 1], [3, 1, 4, 2, 0], [3, 2, 1, 0, 4],\n [3, 3, 3, 3, 3], [3, 4, 0, 1, 2], [4, 0, 1, 2, 3],\n [4, 1, 3, 0, 2], [4, 2, 0, 3, 1], [4, 3, 2, 1, 0],\n [4, 4, 4, 4, 4]]\n\n What is the largest value of `k` for which Sage knows how to compute a\n `OA(k,14,2)`?::\n\n sage: designs.orthogonal_arrays.largest_available_k(14)\n 6\n\n If you ask for an orthogonal array that does not exist, then you will\n either obtain an ``EmptySetError`` (if it knows that such an orthogonal array\n does not exist) or a ``NotImplementedError``::\n\n sage: designs.orthogonal_arrays.build(4,2)\n Traceback (most recent call last):\n ...\n EmptySetError: There exists no OA(4,2) as k(=4)>n+t-1=3\n sage: designs.orthogonal_arrays.build(12,20)\n Traceback (most recent call last):\n ...\n NotImplementedError: I don't know how to build an OA(12,20)!\n "
def __init__(self, *args, **kwds):
'\n There is nothing here.\n\n TESTS::\n\n sage: designs.orthogonal_arrays(4,5) # indirect doctest\n Traceback (most recent call last):\n ...\n RuntimeError: This is not a function but a class. You want to call the designs.orthogonal_arrays.* functions\n '
raise RuntimeError('This is not a function but a class. You want to call the designs.orthogonal_arrays.* functions')
largest_available_k = staticmethod(largest_available_k)
@staticmethod
def explain_construction(k, n, t=2):
'\n Return a string describing how to builds an `OA(k,n)`\n\n INPUT:\n\n - ``k,n,t`` (integers) -- parameters of the orthogonal array.\n\n EXAMPLES::\n\n sage: designs.orthogonal_arrays.explain_construction(9,565)\n "Wilson\'s construction n=23.24+13 with master design OA(9+1,23)"\n sage: designs.orthogonal_arrays.explain_construction(10,154)\n \'the database contains a (137,10;1,0;17)-quasi difference matrix\'\n '
return orthogonal_array(k, n, t, explain_construction=True)
@staticmethod
def build(k, n, t=2, resolvable=False):
'\n Return an `OA(k,n)` of strength `t`\n\n An orthogonal array of parameters `k,n,t` is a matrix with `k`\n columns filled with integers from `[n]` in such a way that for any\n `t` columns, each of the `n^t` possible rows occurs exactly\n once. In particular, the matrix has `n^t` rows.\n\n More general definitions sometimes involve a `\\lambda` parameter, and we\n assume here that `\\lambda=1`.\n\n For more information on orthogonal arrays, see\n :wikipedia:`Orthogonal_array`.\n\n INPUT:\n\n - ``k,n,t`` (integers) -- parameters of the orthogonal array.\n\n - ``resolvable`` (boolean) -- set to ``True`` if you want the design to be\n resolvable. The `n` classes of the resolvable design are obtained as the\n first `n` blocks, then the next `n` blocks, etc ... Set to ``False`` by\n default.\n\n EXAMPLES::\n\n sage: designs.orthogonal_arrays.build(3,3,resolvable=True) # indirect doctest\n [[0, 0, 0],\n [1, 2, 1],\n [2, 1, 2],\n [0, 2, 2],\n [1, 1, 0],\n [2, 0, 1],\n [0, 1, 1],\n [1, 0, 2],\n [2, 2, 0]]\n sage: OA_7_50 = designs.orthogonal_arrays.build(7,50) # indirect doctest\n\n '
return orthogonal_array(k, n, t, resolvable=resolvable)
@staticmethod
def exists(k, n, t=2):
'\n Return the existence status of an `OA(k,n)`\n\n INPUT:\n\n - ``k,n,t`` (integers) -- parameters of the orthogonal array.\n\n .. WARNING::\n\n The function does not only return booleans, but ``True``,\n ``False``, or ``Unknown``.\n\n .. SEEALSO::\n\n :meth:`is_available`\n\n EXAMPLES::\n\n sage: designs.orthogonal_arrays.exists(3,6) # indirect doctest\n True\n sage: designs.orthogonal_arrays.exists(4,6) # indirect doctest\n Unknown\n sage: designs.orthogonal_arrays.exists(7,6) # indirect doctest\n False\n '
return orthogonal_array(k, n, t, existence=True)
@staticmethod
def is_available(k, n, t=2):
'\n Return whether Sage can build an `OA(k,n)`.\n\n INPUT:\n\n - ``k,n,t`` (integers) -- parameters of the orthogonal array.\n\n .. SEEALSO::\n\n :meth:`exists`\n\n EXAMPLES::\n\n sage: designs.orthogonal_arrays.is_available(3,6) # indirect doctest\n True\n sage: designs.orthogonal_arrays.is_available(4,6) # indirect doctest\n False\n '
return (orthogonal_array(k, n, t, existence=True) is True)
|
def construction_3_3(k, n, m, i, explain_construction=False):
"\n Return an `OA(k,nm+i)`.\n\n This is Wilson's construction with `i` truncated columns of size 1 and such\n that a block `B_0` of the incomplete OA intersects all truncated columns. As\n a consequence, all other blocks intersect only `0` or `1` of the last `i`\n columns. This allow to consider the block `B_0` only up to its first `k`\n coordinates and then use a `OA(k,i)` instead of a `OA(k,m+i) - i.OA(k,1)`.\n\n This is construction 3.3 from [AC07]_.\n\n INPUT:\n\n - ``k,n,m,i`` (integers) such that the following designs are available:\n `OA(k,n)`, `OA(k,m)`, `OA(k,m+1)`, `OA(k,r)`.\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_construction_3_3`\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays_find_recursive import find_construction_3_3\n sage: from sage.combinat.designs.orthogonal_arrays_build_recursive import construction_3_3\n sage: from sage.combinat.designs.orthogonal_arrays import is_orthogonal_array\n sage: k = 11; n = 177\n sage: is_orthogonal_array(construction_3_3(*find_construction_3_3(k,n)[1]),k,n,2) # needs sage.schemes\n True\n\n sage: print(designs.orthogonal_arrays.explain_construction(9,91))\n Construction 3.3 with n=11,m=8,i=3 from:\n Julian R. Abel, Nicholas Cavenagh\n Concerning eight mutually orthogonal latin squares,\n Vol. 15, n.3, pp. 255-261,\n Journal of Combinatorial Designs, 2007\n "
from .orthogonal_arrays import wilson_construction, OA_relabel, incomplete_orthogonal_array
if explain_construction:
return ((('Construction 3.3 with n={},m={},i={} from:\n Julian R. Abel, Nicholas Cavenagh\n' + ' Concerning eight mutually orthogonal latin squares,\n') + ' Vol. 15, n.3, pp. 255-261,\n') + ' Journal of Combinatorial Designs, 2007').format(n, m, i)
OA = incomplete_orthogonal_array((k + i), n, (1,))
OA = [[((x + 1) % n) for x in B] for B in OA]
OA = [(B[:k] + [(0 if (x == 0) else None) for x in B[k:]]) for B in OA]
OA = wilson_construction(OA, k, n, m, ([1] * i), check=False)[:(- i)]
matrix = ([(list(range(m)) + list(range((n * m), ((n * m) + i))))] * k)
OA.extend(OA_relabel(orthogonal_array(k, (m + i)), k, (m + i), matrix=matrix))
assert is_orthogonal_array(OA, k, ((n * m) + i))
return OA
|
def construction_3_4(k, n, m, r, s, explain_construction=False):
"\n Return a `OA(k,nm+rs)`.\n\n This is Wilson's construction applied to a truncated `OA(k+r+1,n)` with `r`\n columns of size `1` and one column of size `s`.\n\n The unique elements of the `r` truncated columns are picked so that a block\n `B_0` contains them all.\n\n - If there exists an `OA(k,m+r+1)` the column of size `s` is truncated in\n order to intersect `B_0`.\n\n - Otherwise, if there exists an `OA(k,m+r)`, the last column must not\n intersect `B_0`\n\n This is construction 3.4 from [AC07]_.\n\n INPUT:\n\n - ``k,n,m,r,s`` (integers) -- we assume that `s<n` and `1\\leq r,s`\n\n The following designs must be available: `OA(k,n)`, `OA(k,m)`,\n `OA(k,m+1)`, `OA(k,m+2)`, `OA(k,s)`. Additionally, it requires either a\n `OA(k,m+r)` or a `OA(k,m+r+1)`.\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_construction_3_4`\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays_find_recursive import find_construction_3_4\n sage: from sage.combinat.designs.orthogonal_arrays_build_recursive import construction_3_4\n sage: from sage.combinat.designs.orthogonal_arrays import is_orthogonal_array\n sage: k = 8; n = 196\n sage: is_orthogonal_array(construction_3_4(*find_construction_3_4(k,n)[1]),k,n,2) # needs sage.schemes\n True\n\n sage: print(designs.orthogonal_arrays.explain_construction(8,164))\n Construction 3.4 with n=23,m=7,r=2,s=1 from:\n Julian R. Abel, Nicholas Cavenagh\n Concerning eight mutually orthogonal latin squares,\n Vol. 15, n.3, pp. 255-261,\n Journal of Combinatorial Designs, 2007\n "
if explain_construction:
return (((('Construction 3.4 with n={},m={},r={},s={} from:\n' + ' Julian R. Abel, Nicholas Cavenagh\n') + ' Concerning eight mutually orthogonal latin squares,\n') + ' Vol. 15, n.3, pp. 255-261,\n') + ' Journal of Combinatorial Designs, 2007').format(n, m, r, s)
from .orthogonal_arrays import wilson_construction, OA_relabel
assert (s < n)
master_design = orthogonal_array(((k + r) + 1), n)
matrix = ((([list(range(n))] * k) + ([([None] * n)] * r)) + [([None] * n)])
B0 = master_design[0]
for i in range(k, (k + r)):
matrix[i][B0[i]] = 0
if orthogonal_array(k, (m + r), existence=True):
last_group = [x for x in range((s + 1)) if (x != B0[(- 1)])][:s]
elif orthogonal_array(k, ((m + r) + 1), existence=True):
last_group = ([x for x in range((s + 1)) if (x != B0[(- 1)])][:(s - 1)] + [B0[(- 1)]])
else:
raise RuntimeError
for (i, x) in enumerate(last_group):
matrix[(- 1)][x] = i
OA = OA_relabel(master_design, ((k + r) + 1), n, matrix=matrix)
OA = wilson_construction(OA, k, n, m, (([1] * r) + [s]), check=False)
return OA
|
def construction_3_5(k, n, m, r, s, t, explain_construction=False):
"\n Return an `OA(k,nm+r+s+t)`.\n\n This is exactly Wilson's construction with three truncated groups\n except we make sure that all blocks have size `>k`, so we don't\n need a `OA(k,m+0)` but only `OA(k,m+1)`, `OA(k,m+2)` ,`OA(k,m+3)`.\n\n This is construction 3.5 from [AC07]_.\n\n INPUT:\n\n - ``k,n,m`` (integers)\n\n - ``r,s,t`` (integers) -- sizes of the three truncated groups,\n such that `r\\leq s` and `(q-r-1)(q-s) \\geq (q-s-1)*(q-r)`.\n\n - ``explain_construction`` (boolean) -- return a string describing\n the construction.\n\n The following designs must be available : `OA(k,n)`, `OA(k,r)`, `OA(k,s)`,\n `OA(k,t)`, `OA(k,m+1)`, `OA(k,m+2)`, `OA(k,m+3)`.\n\n .. SEEALSO::\n\n :func:`~sage.combinat.designs.orthogonal_arrays_find_recursive.find_construction_3_5`\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays_find_recursive import find_construction_3_5\n sage: from sage.combinat.designs.orthogonal_arrays_build_recursive import construction_3_5\n sage: from sage.combinat.designs.orthogonal_arrays import is_orthogonal_array\n sage: k=8;n=111\n sage: is_orthogonal_array(construction_3_5(*find_construction_3_5(k,n)[1]),k,n,2) # needs sage.schemes\n True\n\n sage: print(designs.orthogonal_arrays.explain_construction(8,90))\n Construction 3.5 with n=11,m=6,r=8,s=8,t=8 from:\n Julian R. Abel, Nicholas Cavenagh\n Concerning eight mutually orthogonal latin squares,\n Vol. 15, n.3, pp. 255-261,\n Journal of Combinatorial Designs, 2007\n\n "
from .orthogonal_arrays import wilson_construction, OA_relabel
assert (r <= s)
q = n
assert ((((q - r) - 1) * (q - s)) >= (((q - s) - 1) * (q - r)))
if explain_construction:
return ((('Construction 3.5 with n={},m={},r={},s={},t={} from:\n Julian R. Abel, Nicholas Cavenagh\n' + ' Concerning eight mutually orthogonal latin squares,\n') + ' Vol. 15, n.3, pp. 255-261,\n') + ' Journal of Combinatorial Designs, 2007').format(n, m, r, s, t)
master_design = orthogonal_array((k + 3), q)
blocks_crossing_0 = [B[(- 3):] for B in master_design if (B[(- 1)] == 0)][:(q - s)]
group_k_1 = [x[0] for x in blocks_crossing_0]
group_k_1 = [x for x in range(q) if (x not in group_k_1)][:r]
group_k_2 = [x[1] for x in blocks_crossing_0]
group_k_2 = [x for x in range(q) if (x not in group_k_2)][:s]
group_k_3 = [B[(- 1)] for B in master_design if ((B[(- 3)] not in group_k_1) and (B[(- 2)] not in group_k_2))]
group_k_3 = list(set(group_k_3))
assert (len(group_k_3) <= t)
group_k_3.extend([x for x in range(q) if (x not in group_k_3)])
group_k_3 = group_k_3[:t]
r1 = ([None] * q)
r2 = ([None] * q)
r3 = ([None] * q)
for (i, x) in enumerate(group_k_1):
r1[x] = i
for (i, x) in enumerate(group_k_2):
r2[x] = i
for (i, x) in enumerate(group_k_3):
r3[x] = i
OA = OA_relabel(master_design, (k + 3), q, matrix=(([list(range(q))] * k) + [r1, r2, r3]))
OA = wilson_construction(OA, k, q, m, [r, s, t], check=False)
return OA
|
def construction_3_6(k, n, m, i, explain_construction=False):
"\n Return a `OA(k,nm+i)`\n\n This is Wilson's construction with `r` columns of order `1`, in which each\n block intersects at most two truncated columns. Such a design exists when\n `n` is a prime power and is returned by :func:`OA_and_oval`.\n\n INPUT:\n\n - ``k,n,m,i`` (integers) -- `n` must be a prime power. The following designs\n must be available: `OA(k+r,q)`, `OA(k,m)`, `OA(k,m+1)`, `OA(k,m+2)`.\n\n - ``explain_construction`` (boolean) -- return a string describing\n the construction.\n\n This is construction 3.6 from [AC07]_.\n\n .. SEEALSO::\n\n - :func:`~sage.combinat.designs.orthogonal_arrays_find_recursive.find_construction_3_6`\n\n - :func:`OA_and_oval`\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays_find_recursive import find_construction_3_6\n sage: from sage.combinat.designs.orthogonal_arrays_build_recursive import construction_3_6\n sage: from sage.combinat.designs.orthogonal_arrays import is_orthogonal_array\n sage: k=8;n=95\n sage: is_orthogonal_array(construction_3_6(*find_construction_3_6(k,n)[1]),k,n,2) # needs sage.schemes\n True\n\n sage: print(designs.orthogonal_arrays.explain_construction(10,756))\n Construction 3.6 with n=16,m=47,i=4 from:\n Julian R. Abel, Nicholas Cavenagh\n Concerning eight mutually orthogonal latin squares,\n Vol. 15, n.3, pp. 255-261,\n Journal of Combinatorial Designs, 2007\n "
if explain_construction:
return ((('Construction 3.6 with n={},m={},i={} from:\n Julian R. Abel, Nicholas Cavenagh\n' + ' Concerning eight mutually orthogonal latin squares,\n') + ' Vol. 15, n.3, pp. 255-261,\n') + ' Journal of Combinatorial Designs, 2007').format(n, m, i)
from .orthogonal_arrays import wilson_construction
OA = OA_and_oval(n)
OA = [B[:(k + i)] for B in OA]
OA = [(B[:k] + [(x if (x == 0) else None) for x in B[k:]]) for B in OA]
OA = wilson_construction(OA, k, n, m, ([1] * i))
assert is_orthogonal_array(OA, k, ((n * m) + i))
return OA
|
def OA_and_oval(q, *, solver=None, integrality_tolerance=0.001):
'\n Return a `OA(q+1,q)` whose blocks contains `\\leq 2` zeroes in the last `q`\n columns.\n\n This `OA` is build from a projective plane of order `q`, in which there\n exists an oval `O` of size `q+1` (i.e. a set of `q+1` points no three of\n which are [colinear/contained in a common set of the projective plane]).\n\n Removing an element `x\\in O` and all sets that contain it, we obtain a\n `TD(q+1,q)` in which `O` intersects all columns except one. As `O` is an\n oval, no block of the `TD` intersects it more than twice.\n\n INPUT:\n\n - ``q`` -- a prime power\n\n - ``solver`` -- (default: ``None``) Specify a Mixed Integer Linear\n Programming (MILP) solver to be used. If set to ``None``, the default one\n is used. For more information on MILP solvers and which default solver is\n used, see the method :meth:`solve\n <sage.numerical.mip.MixedIntegerLinearProgram.solve>` of the class\n :class:`MixedIntegerLinearProgram\n <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``integrality_tolerance`` -- parameter for use with MILP solvers over an\n inexact base ring; see :meth:`MixedIntegerLinearProgram.get_values`.\n\n .. NOTE::\n\n This function is called by :func:`construction_3_6`, an implementation\n of Construction 3.6 from [AC07]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays_build_recursive import OA_and_oval\n sage: _ = OA_and_oval\n\n '
from sage.arith.misc import is_prime_power
from sage.combinat.designs.block_design import projective_plane
from .orthogonal_arrays import OA_relabel
assert is_prime_power(q)
B = projective_plane(q, check=False)
from sage.numerical.mip import MixedIntegerLinearProgram
p = MixedIntegerLinearProgram(solver=solver)
b = p.new_variable(binary=True)
V = B.ground_set()
p.add_constraint((p.sum([b[i] for i in V]) == (q + 1)))
for bl in B:
p.add_constraint((p.sum([b[i] for i in bl]) <= 2))
p.solve()
b = p.get_values(b, convert=bool, tolerance=integrality_tolerance)
oval = [x for (x, i) in b.items() if i]
assert (len(oval) == (q + 1))
x = oval.pop()
oval.sort()
r = {}
B = sorted(B, key=(lambda b: any(((xx in oval) for xx in b))))
BB = []
for b in B:
if (x in b):
for xx in b:
if (xx == x):
continue
r[xx] = len(r)
else:
BB.append(b)
assert (len(r) == ((q + 1) * q))
assert (len(set(r.values())) == len(r))
BB = [[r[xx] for xx in b] for b in BB]
oval = [r[xx] for xx in oval]
for b in BB:
b.sort()
oval.sort()
BB = [[(xx % q) for xx in b] for b in BB]
oval = [(xx % q) for xx in oval]
assert (len(oval) == q)
OA = OA_relabel((BB + [([0] + oval)]), (q + 1), q, blocks=[([0] + oval)])
OA = [[((x + 1) % q) for x in B] for B in OA]
OA.remove(([0] * (q + 1)))
assert all(((sum([(xx == 0) for xx in b[1:]]) <= 2) for b in OA))
return OA
|
def construction_q_x(k, q, x, check=True, explain_construction=False):
'\n Return an `OA(k,(q-1)*(q-x)+x+2)` using the `q-x` construction.\n\n Let `v=(q-1)*(q-x)+x+2`. If there exists a projective plane of order `q`\n (e.g. when `q` is a prime power) and `0<x<q` then there exists a\n `(v-1,\\{q-x-1,q-x+1\\})`-GDD of type `(q-1)^{q-x}(x+1)^1` (see [Greig99]_ or\n Theorem 2.50, section IV.2.3 of [DesignHandbook]_). By adding to the ground\n set one point contained in all groups of the GDD, one obtains a\n `(v,\\{q-x-1,q-x+1,q,x+2\\})`-PBD with exactly one set of size `x+2`.\n\n Thus, assuming that we have the following:\n\n - `OA(k,q-x-1)-(q-x-1).OA(k,1)`\n - `OA(k,q-x+1)-(q-x+1).OA(k,1)`\n - `OA(k,q)-q.OA(k,1)`\n - `OA(k,x+2)`\n\n Then we can build from the PBD an `OA(k,v)`.\n\n Construction of the PBD (shared by Julian R. Abel):\n\n Start with a resolvable `(q^2,q,1)`-BIBD and put the points into a `q\\times q`\n array so that rows form a parallel class and columns form another.\n\n Now delete:\n\n - All `x(q-1)` points from the first `x` columns and not in the first\n row\n\n - All `q-x` points in the last `q-x` columns AND the first row.\n\n Then add a point `p_1` to the blocks that are rows. Add a second point\n `p_2` to the `q-x` blocks that are columns of size `q-1`, plus the first\n row of size `x+1`.\n\n INPUT:\n\n - ``k,q,x`` -- integers such that `0<x<q` and such that Sage can build:\n\n - A projective plane of order `q`\n - `OA(k,q-x-1)-(q-x-1).OA(k,1)`\n - `OA(k,q-x+1)-(q-x+1).OA(k,1)`\n - `OA(k,q)-q.OA(k,1)`\n - `OA(k,x+2)`\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\n ``True`` by default.\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_q_x`\n - :func:`~sage.combinat.designs.block_design.projective_plane`\n - :func:`~sage.combinat.designs.orthogonal_arrays.orthogonal_array`\n - :func:`~sage.combinat.designs.orthogonal_arrays.OA_from_PBD`\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays_build_recursive import construction_q_x\n sage: _ = construction_q_x(9,16,6) # needs sage.schemes\n\n sage: print(designs.orthogonal_arrays.explain_construction(9,158))\n (q-x)-construction with q=16,x=6 from:\n Malcolm Greig,\n Designs from projective planes and PBD bases,\n vol. 7, num. 5, pp. 341--374,\n Journal of Combinatorial Designs, 1999\n\n REFERENCES:\n\n .. [Greig99] Designs from projective planes and PBD bases\n Malcolm Greig\n Journal of Combinatorial Designs\n vol. 7, num. 5, pp. 341--374\n 1999\n '
from sage.combinat.designs.orthogonal_arrays import OA_from_PBD
from sage.combinat.designs.orthogonal_arrays import incomplete_orthogonal_array
if explain_construction:
return (((('(q-x)-construction with q={},x={} from:\n' + ' Malcolm Greig,\n') + ' Designs from projective planes and PBD bases,\n') + ' vol. 7, num. 5, pp. 341--374,\n') + ' Journal of Combinatorial Designs, 1999').format(q, x)
n = ((((q - 1) * (q - x)) + x) + 2)
OA = incomplete_orthogonal_array(q, q, ((1,) * q))
TD = [[((i * q) + xx) for (i, xx) in enumerate(B)] for B in OA]
p1 = (q ** 2)
p2 = (p1 + 1)
TD.extend([([((ii * q) + i) for ii in range(q)] + [p1]) for i in range(1, q)])
TD.append(([(ii * q) for ii in range(q)] + [p1, p2]))
TD.extend([(list(range((i * q), ((i + 1) * q))) + [p2]) for i in range(x, q)])
points_to_delete = set(([((i * q) + j) for i in range(x) for j in range(1, q)] + [(i * q) for i in range(x, q)]))
points_to_keep = (set(range(((q ** 2) + 2))) - points_to_delete)
relabel = {i: j for (j, i) in enumerate(points_to_keep)}
PBD = [[relabel[xx] for xx in B if (xx not in points_to_delete)] for B in TD]
assert (list(map(len, PBD)).count((x + 2)) == 1)
for B in PBD:
if (len(B) == (x + 2)):
break
PBD.remove(B)
OA = OA_from_PBD(k, ((((q - 1) * (q - x)) + x) + 2), PBD, check=False)
for xx in B:
OA.remove(([xx] * k))
for BB in orthogonal_array(k, (x + 2)):
OA.append([B[x] for x in BB])
if check:
assert is_orthogonal_array(OA, k, n, 2)
return OA
|
def thwart_lemma_3_5(k, n, m, a, b, c, d=0, complement=False, explain_construction=False):
'\n Returns an `OA(k,nm+a+b+c+d)`\n\n *(When `d=0`)*\n\n According to [Thwarts]_ when `n` is a prime power and `a+b+c\\leq n+1`, one\n can build an `OA(k+3,n)` with three truncated columns of sizes `a,b,c` in\n such a way that all blocks have size `\\leq k+2`.\n\n (in order to build a `OA(k,nm+a+b+c)` the following designs must also exist:\n `OA(k,a)`, `OA(k,b)`, `OA(k,c)`, `OA(k,m+0)`, `OA(k,m+1)`, `OA(k,m+2)`)\n\n Considering the complement of each truncated column, it is also possible to\n build an `OA(k+3,n)` with three truncated columns of sizes `a,b,c` in such a\n way that all blocks have size `>k` whenever `(n-a)+(n-b)+(n-c)\\leq n+1`.\n\n (in order to build a `OA(k,nm+a+b+c)` the following designs must also exist:\n `OA(k,a)`, `OA(k,b)`, `OA(k,c)`, `OA(k,m+1)`, `OA(k,m+2)`, `OA(k,m+3)`)\n\n Here is the proof of Lemma 3.5 from [Thwarts]_ enriched with explanations\n from Julian R. Abel:\n\n For any prime power `n` one can build `k-1` MOLS by associating to every\n nonzero `x\\in \\mathbb F_n` the latin square:\n\n .. MATH::\n\n M_x(i,j) = i+x*j \\text{ where }i,j\\in \\mathbb F_n\n\n In particular `M_1(i,j)=i+j`, whose `n` columns and lines are indexed by\n the elements of `\\mathbb F_n`. If we order the elements of `\\mathbb F_n`\n as `0,1,...,n-1,x+0,...,x+n-1,x^2+0,...` and reorder the columns\n and lines of `M_1` accordingly, the top-left `a\\times b` squares\n contains at most `a+b-1` distinct symbols.\n\n *(When* `d\\neq 0` *)*\n\n If there exists an `OA(k+3,n)` with three truncated columns of sizes `a,b,c`\n in such a way that all blocks have size `\\leq k+2`, by truncating\n arbitrarily another column to size `d` one obtains an `OA` with 4 truncated\n columns whose blocks miss at least one value. Thus, following the proof\n again one can build an `OA(k+4)` with four truncated columns of sizes\n `a,b,c,d` with blocks of size `\\leq k+3`.\n\n (in order to build a `OA(k,nm+a+b+c+d)` the following designs must also\n exist: `OA(k,a)`, `OA(k,b)`, `OA(k,c)`, `OA(k,d)`, `OA(k,m+0)`, `OA(k,m+1)`,\n `OA(k,m+2)`, `OA(k,m+3)`)\n\n As before, this also shows that one can build an `OA(k+4,n)` with four\n truncated columns of sizes `a,b,c,d` in such a way that all blocks have size\n `>k` whenever `(n-a)+(n-b)+(n-c)\\leq n+1`\n\n (in order to build a `OA(k,nm+a+b+c+d)` the following designs must also\n exist: `OA(k,n-a)`, `OA(k,n-b)`, `OA(k,n-c)`, `OA(k,d)`, `OA(k,m+1)`,\n `OA(k,m+2)`, `OA(k,m+3)`, `OA(k,m+4)`)\n\n INPUT:\n\n - ``k,n,m,a,b,c,d`` -- integers which must satisfy the constraints above. In\n particular, `a+b+c\\leq n+1` must hold. By default, `d=0`.\n\n - ``complement`` (boolean) -- whether to complement the sets, i.e. follow\n the `n-a,n-b,n-c` variant described above.\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_3_5`\n\n EXAMPLES::\n\n sage: from sage.combinat.designs.orthogonal_arrays_build_recursive import thwart_lemma_3_5\n sage: from sage.combinat.designs.designs_pyx import is_orthogonal_array\n sage: OA = thwart_lemma_3_5(6,23,7,5,7,8) # needs sage.schemes\n sage: is_orthogonal_array(OA,6,23*7+5+7+8,2) # needs sage.schemes\n True\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 With sets of parameters from [Thwarts]_::\n\n sage: l = [\n ....: [11, 27, 78, 16, 17, 25, 0],\n ....: [12, 19, 208, 11, 13, 16, 0],\n ....: [12, 19, 208, 13, 13, 16, 0],\n ....: [10, 13, 78, 9, 9, 13, 1],\n ....: [10, 13, 79, 9, 9, 13, 1]]\n sage: for k,n,m,a,b,c,d in l: # not tested -- too long\n ....: OA = thwart_lemma_3_5(k,n,m,a,b,c,d,complement=True)\n ....: assert is_orthogonal_array(OA,k,n*m+a+b+c+d,verbose=True)\n\n sage: print(designs.orthogonal_arrays.explain_construction(10,1046))\n Lemma 3.5 with n=13,m=79,a=9,b=1,c=0,d=9 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 REFERENCE:\n\n .. [Thwarts] Thwarts in transversal designs\n Charles J.Colbourn, Jeffrey H. Dinitz, Mieczyslaw Wojtas.\n Designs, Codes and Cryptography 5, no. 3 (1995): 189-197.\n '
from sage.arith.misc import is_prime_power
from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF
if complement:
(a, b, c) = ((n - a), (n - b), (n - c))
if explain_construction:
return ((('Lemma 3.5 with n={},m={},a={},b={},c={},d={} 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, a, b, c, d)
assert is_prime_power(n), 'n(={}) must be a prime power'.format(n)
assert ((a <= n) and (b <= n) and (c <= n) and (d <= n)), 'a,b,c,d (={},{},{},{}) must be <=n(={})'.format(a, b, c, d, n)
assert (((a + b) + c) <= (n + 1)), '{}={}+{}+{}=a+b+c>n+1={}+1 violates the assumptions'.format(((a + b) + c), a, b, c, n)
assert (((k + 3) + bool(d)) <= (n + 1)), 'There exists no OA({},{}).'.format(((k + 3) + bool(d)), n)
G = GF(n, prefix='x')
G_set = sorted(G)
assert ((G_set[0] == G.zero()) and (G_set[1] == G.one())), 'problem with the ordering of {}'.format(G)
G_to_int = {v: i for (i, v) in enumerate(G_set)}
OA = [[G_to_int[(i + (x * j))] for i in G_set for j in G_set] for x in G_set[1:((k + 2) + bool(d))]]
OA.insert(0, [j for i in range(n) for j in range(n)])
OA.insert(0, [i for i in range(n) for j in range(n)])
OA = sorted(zip(*OA))
OA = [list((B[3:] + B[:3])) for B in OA]
third_complement = set((B[(- 1)] for B in OA if ((B[(- 3)] < a) and (B[(- 2)] < b))))
assert ((n - len(third_complement)) >= c)
first_set = list(range(a))
second_set = list(range(b))
third_set = [x for x in range(n) if (x not in third_complement)][:c]
last_sets = [first_set, second_set, third_set]
if complement:
last_sets = [set(range(n)).difference(s) for s in last_sets]
sizes = [len(_) for _ in last_sets]
last_sets_dict = [{v: i for (i, v) in enumerate(s)} for s in last_sets]
for (i, D) in enumerate(last_sets_dict):
kk = ((len(OA[0]) - 3) + i)
for R in OA:
R[kk] = (D[R[kk]] if (R[kk] in D) else None)
if d:
for R in OA:
if (R[(- 4)] >= d):
R[(- 4)] = None
sizes.insert(0, d)
return wilson_construction(OA, k, n, m, sizes, check=False)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.