code
stringlengths
17
6.64M
def _delsarte_Q_LP_building(q, d, solver, isinteger): '\n LP builder for Delsarte\'s LP for codes given Q matrix.\n\n LP builder for Delsarte\'s LP for codes, given Q matrix;\n used in :func:`delsarte_bound_Q_matrix`; not exported.\n\n INPUT:\n\n - ``q`` -- the Q matrix\n\n - ``d`` -- the (lower bound on) minimal distance of the code\n\n - ``solver`` -- the LP/ILP solver to be used. Defaults to\n ``PPL``. It is arbitrary precision, thus there will be no\n rounding errors. With other solvers (see\n :class:`MixedIntegerLinearProgram` for the list), you are on\n your own!\n\n - ``isinteger`` -- if ``True``, uses an integer programming solver\n (ILP), rather that an LP solver. Can be very slow if set to\n ``True``.\n\n EXAMPLES::\n\n sage: from sage.coding.delsarte_bounds import _delsarte_Q_LP_building\n sage: q = Matrix([[codes.bounds.krawtchouk(6,2,i,j) for j in range(7)] for i in range(7)])\n sage: _, p = _delsarte_Q_LP_building(q, 2, "PPL", False)\n sage: p.show()\n Maximization:\n x_0 + x_1 + x_2 + x_3 + x_4 + x_5 + x_6\n <BLANKLINE>\n Constraints:\n constraint_0: 1 <= x_0 <= 1\n constraint_1: 0 <= x_1 <= 0\n constraint_2: 0 <= 6 x_0 + 4 x_1 + 2 x_2 - 2 x_4 - 4 x_5 - 6 x_6\n constraint_3: 0 <= 15 x_0 + 5 x_1 - x_2 - 3 x_3 - x_4 + 5 x_5 + 15 x_6\n constraint_4: 0 <= 20 x_0 - 4 x_2 + 4 x_4 - 20 x_6\n constraint_5: 0 <= 15 x_0 - 5 x_1 - x_2 + 3 x_3 - x_4 - 5 x_5 + 15 x_6\n constraint_6: 0 <= 6 x_0 - 4 x_1 + 2 x_2 - 2 x_4 + 4 x_5 - 6 x_6\n constraint_7: 0 <= x_0 - x_1 + x_2 - x_3 + x_4 - x_5 + x_6\n Variables:\n x_0 is a continuous variable (min=0, max=+oo)\n x_1 is a continuous variable (min=0, max=+oo)\n x_2 is a continuous variable (min=0, max=+oo)\n x_3 is a continuous variable (min=0, max=+oo)\n x_4 is a continuous variable (min=0, max=+oo)\n x_5 is a continuous variable (min=0, max=+oo)\n x_6 is a continuous variable (min=0, max=+oo)\n ' from sage.numerical.mip import MixedIntegerLinearProgram (n, _) = q.dimensions() p = MixedIntegerLinearProgram(maximization=True, solver=solver) A = p.new_variable(integer=isinteger, nonnegative=True) p.set_objective(sum([A[i] for i in range(n)])) p.add_constraint((A[0] == 1)) try: for i in range(1, d): p.add_constraint((A[i] == 0)) except TypeError: for i in d: p.add_constraint((A[i] == 0)) for k in range(1, n): p.add_constraint(sum([(q[k][i] * A[i]) for i in range(n)]), min=0) return (A, p)
def delsarte_bound_Q_matrix(q, d, return_data=False, solver='PPL', isinteger=False): '\n Delsarte bound on a code with Q matrix ``q`` and lower bound on min. dist. ``d``.\n\n Find the Delsarte bound on a code with Q matrix ``q`` and lower bound on\n minimal distance ``d``.\n\n INPUT:\n\n - ``q`` -- the Q matrix\n\n - ``d`` -- the (lower bound on) minimal distance of the code\n\n - ``return_data`` -- if ``True``, return a triple\n ``(W,LP,bound)``, where ``W`` is a weights vector, and ``LP``\n the Delsarte upper bound LP; both of them are Sage LP data.\n ``W`` need not be a weight distribution of a code.\n\n - ``solver`` -- the LP/ILP solver to be used. Defaults to\n ``PPL``. It is arbitrary precision, thus there will be no\n rounding errors. With other solvers (see\n :class:`MixedIntegerLinearProgram` for the list), you are on\n your own!\n\n - ``isinteger`` -- if ``True``, uses an integer programming solver\n (ILP), rather that an LP solver. Can be very slow if set to\n ``True``.\n\n EXAMPLES:\n\n The bound on dimension of linear `\\GF{2}`-codes of length 10 and minimal distance 6::\n\n sage: q_matrix = Matrix([[codes.bounds.krawtchouk(10,2,i,j) for i in range(11)]\n ....: for j in range(11)])\n sage: codes.bounds.delsarte_bound_Q_matrix(q_matrix, 6)\n 2\n\n sage: a,p,val = codes.bounds.delsarte_bound_Q_matrix(q_matrix, 6, return_data=True)\n sage: [j for i,j in p.get_values(a).items()]\n [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]\n\n TESTS:\n\n Cases for using Hamming scheme Q matrix::\n\n sage: q_matrix = Matrix([[codes.bounds.krawtchouk(10,2,i,j) for i in range(11)] for j in range(11)])\n sage: codes.bounds.delsarte_bound_Q_matrix(q_matrix, 6)\n 2\n\n sage: a,p,val = codes.bounds.delsarte_bound_Q_matrix(q_matrix, 6, return_data=True)\n sage: [j for i,j in p.get_values(a).items()]\n [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]\n ' from sage.numerical.mip import MIPSolverException from sage.structure.element import is_Matrix if (not is_Matrix(q)): raise ValueError('Input to delsarte_bound_Q_matrix should be a sage Matrix()') (A, p) = _delsarte_Q_LP_building(q, d, solver, isinteger) try: bd = p.solve() except MIPSolverException as exc: print(f'Solver exception: {exc}') return ((A, p, False) if return_data else False) return ((A, p, bd) if return_data else bd)
class Encoder(SageObject): '\n Abstract top-class for :class:`Encoder` objects.\n\n Every encoder class for linear codes (of any metric) should inherit from\n this abstract class.\n\n To implement an encoder, you need to:\n\n - inherit from :class:`Encoder`,\n\n - call ``Encoder.__init__`` in the subclass constructor.\n Example: ``super().__init__(code)``.\n By doing that, your subclass will have its ``code`` parameter initialized.\n\n - Then, if the message space is a vector space, default implementations of :meth:`encode` and\n :meth:`unencode_nocheck` methods are provided. These implementations rely on :meth:`generator_matrix`\n which you need to override to use the default implementations.\n\n - If the message space is not of the form `F^k`, where `F` is a finite field,\n you cannot have a generator matrix.\n In that case, you need to override :meth:`encode`, :meth:`unencode_nocheck` and\n :meth:`message_space`.\n\n - By default, comparison of :class:`Encoder` (using methods ``__eq__`` and ``__ne__`` ) are\n by memory reference: if you build the same encoder twice, they will be different. If you\n need something more clever, override ``__eq__`` and ``__ne__`` in your subclass.\n\n - As :class:`Encoder` is not designed to be instantiated, it does not have any representation\n methods. You should implement ``_repr_`` and ``_latex_`` methods in the subclass.\n\n REFERENCES:\n\n - [Nie]_\n ' def __init__(self, code): '\n Initializes mandatory parameters for an :class:`Encoder` object.\n\n This method only exists for inheritance purposes as it initializes\n parameters that need to be known by every linear code. An abstract\n encoder object should never be created.\n\n INPUT:\n\n - ``code`` -- the associated code of ``self``\n\n EXAMPLES:\n\n We first create a new :class:`Encoder` subclass::\n\n sage: from sage.coding.encoder import Encoder\n sage: class EncoderExample(Encoder):\n ....: def __init__(self, code):\n ....: super().__init__(code)\n\n We now create a member of our newly made class::\n\n sage: G = Matrix(GF(2), [[1, 0, 0, 1], [0, 1, 1, 1]])\n sage: C = LinearCode(G)\n sage: E = EncoderExample(C)\n\n We can check its parameters::\n\n sage: E.code()\n [4, 2] linear code over GF(2)\n ' self._code = code def __ne__(self, other): '\n Tests inequality of ``self`` and ``other``.\n\n This is a generic implementation, which returns the inverse of ``__eq__`` for self.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: E1 = LinearCode(G).encoder()\n sage: E2 = LinearCode(G).encoder()\n sage: E1 != E2\n False\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,1,1]])\n sage: E2 = LinearCode(G).encoder()\n sage: E1 != E2\n True\n ' return (not (self == other)) def encode(self, word): "\n Transforms an element of the message space into a codeword.\n\n This is a default implementation which assumes that the message\n space of the encoder is `F^{k}`, where `F` is\n :meth:`sage.coding.linear_code_no_metric.AbstractLinearCodeNoMetric.base_field`\n and `k` is :meth:`sage.coding.linear_code_no_metric.AbstractLinearCodeNoMetric.dimension`.\n If this is not the case, this method should be overwritten by the subclass.\n\n .. NOTE::\n\n :meth:`encode` might be a partial function over ``self``'s :meth:`message_space`.\n One should use the exception :class:`EncodingError` to catch attempts\n to encode words that are outside of the message space.\n\n One can use the following shortcut to encode a word with an encoder ``E``::\n\n E(word)\n\n INPUT:\n\n - ``word`` -- a vector of the message space of the ``self``.\n\n OUTPUT:\n\n - a vector of :meth:`code`.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: word = vector(GF(2), (0, 1, 1, 0))\n sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C)\n sage: E.encode(word)\n (1, 1, 0, 0, 1, 1, 0)\n\n If ``word`` is not in the message space of ``self``, it will return an exception::\n\n sage: word = random_vector(GF(7), 4)\n sage: E.encode(word)\n Traceback (most recent call last):\n ...\n ValueError: The value to encode must be in\n Vector space of dimension 4 over Finite Field of size 2\n " M = self.message_space() if (word not in M): raise ValueError(('The value to encode must be in %s' % M)) return (vector(word) * self.generator_matrix()) def __call__(self, m): '\n Transforms an element of the message space into a codeword.\n\n This behaves the same as `self.encode`.\n See `sage.coding.encoder.Encoder.encode` for details.\n\n INPUT:\n\n - ``word`` -- a vector of the message space of the ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: word = vector(GF(2), (0, 1, 1, 0))\n sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C)\n sage: E(word)\n (1, 1, 0, 0, 1, 1, 0)\n\n sage: F = GF(11)\n sage: Fx.<x> = F[]\n sage: n, k = 10 , 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = C.encoder("EvaluationPolynomial")\n sage: p = x^2 + 3*x + 10\n sage: E(p)\n (10, 3, 9, 6, 5, 6, 9, 3, 10, 8)\n ' return self.encode(m) def unencode(self, c, nocheck=False): '\n Return the message corresponding to the codeword ``c``.\n\n This is the inverse of :meth:`encode`.\n\n INPUT:\n\n - ``c`` -- a codeword of :meth:`code`.\n\n - ``nocheck`` -- (default: ``False``) checks if ``c`` is in :meth:`code`. You might set\n this to ``True`` to disable the check for saving computation. Note that if ``c`` is\n not in :meth:`self` and ``nocheck = True``, then the output of :meth:`unencode` is\n not defined (except that it will be in the message space of ``self``).\n\n OUTPUT:\n\n - an element of the message space of ``self``\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: c = vector(GF(2), (1, 1, 0, 0, 1, 1, 0))\n sage: c in C\n True\n sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C)\n sage: E.unencode(c)\n (0, 1, 1, 0)\n\n TESTS:\n\n If ``nocheck`` is set to ``False``, and one provides a word which is not in\n :meth:`code`, :meth:`unencode` will return an error::\n\n sage: c = vector(GF(2), (0, 1, 0, 0, 1, 1, 0))\n sage: c in C\n False\n sage: E.unencode(c, False)\n Traceback (most recent call last):\n ...\n EncodingError: Given word is not in the code\n\n Note that since :trac:`21326`, codes cannot be of length zero::\n\n sage: G = Matrix(GF(17), [])\n sage: C = LinearCode(G)\n Traceback (most recent call last):\n ...\n ValueError: length must be a non-zero positive integer\n ' if ((not nocheck) and (c not in self.code())): raise EncodingError('Given word is not in the code') return self.unencode_nocheck(c) @cached_method def _unencoder_matrix(self): '\n Finds an information set for the matrix ``G`` returned by :meth:`generator_matrix`,\n and returns the inverse of that submatrix of ``G``.\n\n AUTHORS:\n\n This function is taken from codinglib [Nie]_\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: E = C.encoder()\n sage: E._unencoder_matrix()\n (\n [0 0 1 1]\n [0 1 0 1]\n [1 1 1 0]\n [0 1 1 1], (0, 1, 2, 3)\n )\n ' info_set = self.code().information_set() Gtinv = self.generator_matrix().matrix_from_columns(info_set).inverse() Gtinv.set_immutable() M = (Gtinv, info_set) return M def unencode_nocheck(self, c): '\n Returns the message corresponding to ``c``.\n\n When ``c`` is not a codeword, the output is unspecified.\n\n AUTHORS:\n\n This function is taken from codinglib [Nie]_\n\n INPUT:\n\n\n - ``c`` -- a codeword of :meth:`code`.\n\n OUTPUT:\n\n - an element of the message space of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: c = vector(GF(2), (1, 1, 0, 0, 1, 1, 0))\n sage: c in C\n True\n sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C)\n sage: E.unencode_nocheck(c)\n (0, 1, 1, 0)\n\n Taking a vector that does not belong to ``C`` will not raise an error but\n probably just give a non-sensical result::\n\n sage: c = vector(GF(2), (1, 1, 0, 0, 1, 1, 1))\n sage: c in C\n False\n sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C)\n sage: E.unencode_nocheck(c)\n (0, 1, 1, 0)\n sage: m = vector(GF(2), (0, 1, 1, 0))\n sage: c1 = E.encode(m)\n sage: c == c1\n False\n ' (U, info_set) = self._unencoder_matrix() cc = vector(self.code().base_ring(), [c[i] for i in info_set]) return (cc * U) def code(self): '\n Returns the code for this :class:`Encoder`.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: E = C.encoder()\n sage: E.code() == C\n True\n ' return self._code def message_space(self): '\n Returns the ambient space of allowed input to :meth:`encode`.\n Note that :meth:`encode` is possibly a partial function over\n the ambient space.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: E = C.encoder()\n sage: E.message_space()\n Vector space of dimension 4 over Finite Field of size 2\n ' return (self.code().base_field() ** self.code().dimension()) @abstract_method(optional=True) def generator_matrix(self): '\n Returns a generator matrix of the associated code of ``self``.\n\n This is an abstract method and it should be implemented separately.\n Reimplementing this for each subclass of :class:`Encoder` is not mandatory\n (as a generator matrix only makes sense when the message space is of the `F^k`,\n where `F` is the base field of :meth:`code`.)\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: E = C.encoder()\n sage: E.generator_matrix()\n [1 1 1 0 0 0 0]\n [1 0 0 1 1 0 0]\n [0 1 0 1 0 1 0]\n [1 1 0 1 0 0 1]\n '
class EncodingError(Exception): '\n Special exception class to indicate an error during encoding or unencoding.\n ' pass
class ExtendedCode(AbstractLinearCode): '\n Representation of an extended code.\n\n INPUT:\n\n - ``C`` -- A linear code\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Ce = codes.ExtendedCode(C)\n sage: Ce\n Extension of [11, 5] linear code over GF(7)\n ' _registered_encoders = {} _registered_decoders = {} def __init__(self, C): '\n TESTS:\n\n ``C`` must be a linear code::\n\n sage: C = VectorSpace(GF(7), 11)\n sage: codes.ExtendedCode(C)\n Traceback (most recent call last):\n ...\n ValueError: Provided code must be a linear code\n ' if (not isinstance(C, AbstractLinearCode)): raise ValueError('Provided code must be a linear code') super().__init__(C.base_ring(), (C.length() + 1), 'ExtendedMatrix', 'OriginalDecoder') self._original_code = C self._dimension = C.dimension() def __eq__(self, other): '\n Tests equality between two extended codes.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: C1 = codes.ExtendedCode(C)\n sage: C2 = codes.ExtendedCode(C)\n sage: C1 == C2\n True\n ' return (isinstance(other, ExtendedCode) and (self.original_code() == other.original_code())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Ce = codes.ExtendedCode(C)\n sage: Ce\n Extension of [11, 5] linear code over GF(7)\n ' return ('Extension of %s' % self.original_code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Ce = codes.ExtendedCode(C)\n sage: latex(Ce)\n \\textnormal{Extension of [11, 5] linear code over GF(7)}\n ' return ('\\textnormal{Extension of %s}' % self.original_code()) def original_code(self): '\n Return the code which was extended to get ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Ce = codes.ExtendedCode(C)\n sage: Ce.original_code()\n [11, 5] linear code over GF(7)\n ' return self._original_code @cached_method def parity_check_matrix(self): '\n Return a parity check matrix of ``self``.\n\n This matrix is computed directly from :func:`original_code`.\n\n EXAMPLES::\n\n sage: C = LinearCode(matrix(GF(2),[[1,0,0,1,1],\\\n [0,1,0,1,0],\\\n [0,0,1,1,1]]))\n sage: C.parity_check_matrix()\n [1 0 1 0 1]\n [0 1 0 1 1]\n sage: Ce = codes.ExtendedCode(C)\n sage: Ce.parity_check_matrix()\n [1 1 1 1 1 1]\n [1 0 1 0 1 0]\n [0 1 0 1 1 0]\n ' F = self.base_ring() zero = F.zero() one = F.one() H = self.original_code().parity_check_matrix() (nr, nc) = (H.nrows(), H.ncols()) Hlist = H.list() v = matrix(F, (nr + 1), 1, ([one] + ([zero] * nr))) M = matrix(F, (nr + 1), nc, (([one] * nc) + Hlist)).augment(v) M.set_immutable() return M def random_element(self): '\n Return a random element of ``self``.\n\n This random element is computed directly from the original code,\n and does not compute a generator matrix of ``self`` in the process.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 9, 5)\n sage: Ce = codes.ExtendedCode(C)\n sage: c = Ce.random_element() #random\n sage: c in Ce\n True\n ' c = self.original_code().random_element() c_list = c.list() F = self.base_ring() last_element = F.zero() for i in c_list: last_element += i c_list.append((- last_element)) return vector(F, c_list)
class ExtendedCodeExtendedMatrixEncoder(Encoder): "\n Encoder using original code's generator matrix to compute the extended code's one.\n\n INPUT:\n\n - ``code`` -- The associated code of ``self``.\n " def __init__(self, code): '\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Ce = codes.ExtendedCode(C)\n sage: E = codes.encoders.ExtendedCodeExtendedMatrixEncoder(Ce)\n sage: E\n Matrix-based Encoder for Extension of [11, 5] linear code over GF(7)\n ' if (not isinstance(code, ExtendedCode)): raise TypeError('code has to be an instance of ExtendedCode class') super().__init__(code) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Ce = codes.ExtendedCode(C)\n sage: E = codes.encoders.ExtendedCodeExtendedMatrixEncoder(Ce)\n sage: E\n Matrix-based Encoder for Extension of [11, 5] linear code over GF(7)\n ' return ('Matrix-based Encoder for %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Ce = codes.ExtendedCode(C)\n sage: E = codes.encoders.ExtendedCodeExtendedMatrixEncoder(Ce)\n sage: latex(E)\n \\textnormal{Matrix-based Encoder for }\\textnormal{Extension of [11, 5] linear code over GF(7)}\n ' return ('\\textnormal{Matrix-based Encoder for }%s' % self.code()._latex_()) def __eq__(self, other): '\n Tests equality between GRSEvaluationVectorEncoder objects.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Ce = codes.ExtendedCode(C)\n sage: D1 = codes.encoders.ExtendedCodeExtendedMatrixEncoder(Ce)\n sage: D2 = codes.encoders.ExtendedCodeExtendedMatrixEncoder(Ce)\n sage: D1.__eq__(D2)\n True\n sage: D1 is D2\n False\n ' return (isinstance(other, ExtendedCodeExtendedMatrixEncoder) and (self.code() == other.code())) @cached_method def generator_matrix(self): '\n Return a generator matrix of the associated code of ``self``.\n\n EXAMPLES::\n\n sage: C = LinearCode(matrix(GF(2),[[1,0,0,1,1],\\\n [0,1,0,1,0],\\\n [0,0,1,1,1]]))\n sage: Ce = codes.ExtendedCode(C)\n sage: E = codes.encoders.ExtendedCodeExtendedMatrixEncoder(Ce)\n sage: E.generator_matrix()\n [1 0 0 1 1 1]\n [0 1 0 1 0 0]\n [0 0 1 1 1 1]\n ' C = self.code() F = C.base_ring() Cor = C.original_code() G = Cor.generator_matrix() k = C.dimension() extra_col = [(- sum(G.rows()[i])) for i in range(k)] extra_col = matrix(F, k, 1, extra_col) M = G.augment(extra_col) M.set_immutable() return M
class ExtendedCodeOriginalCodeDecoder(Decoder): "\n Decoder which decodes through a decoder over the original code.\n\n INPUT:\n\n - ``code`` -- The associated code of this decoder\n\n - ``original_decoder`` -- (default: ``None``) the decoder that will be used over the original code.\n It has to be a decoder object over the original code.\n If ``original_decoder`` is set to ``None``, it will use the default decoder of the original code.\n\n - ``**kwargs`` -- all extra arguments are forwarded to original code's decoder\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Ce = codes.ExtendedCode(C)\n sage: D = codes.decoders.ExtendedCodeOriginalCodeDecoder(Ce)\n sage: D\n Decoder of Extension of [15, 7, 9] Reed-Solomon Code over GF(16)\n through Gao decoder for [15, 7, 9] Reed-Solomon Code over GF(16)\n " def __init__(self, code, original_decoder=None, **kwargs): "\n TESTS:\n\n If one tries to use a decoder whose code is not the original code, it returns an error::\n\n sage: C1 = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Ce = codes.ExtendedCode(C1)\n sage: C2 = codes.GeneralizedReedSolomonCode(GF(13).list()[:12], 7)\n sage: Dc2 = C2.decoder()\n sage: D = codes.decoders.ExtendedCodeOriginalCodeDecoder(Ce, original_decoder = Dc2)\n Traceback (most recent call last):\n ...\n ValueError: Original decoder must have the original code as associated code\n " if (not isinstance(code, ExtendedCode)): raise TypeError('code has to be an instance of ExtendedCode class') original_code = code.original_code() if ((original_decoder is not None) and (not (original_decoder.code() == original_code))): raise ValueError('Original decoder must have the original code as associated code') elif (original_decoder is None): self._original_decoder = original_code.decoder() else: self._original_decoder = original_decoder self._decoder_type = copy(self._decoder_type) self._decoder_type.remove('dynamic') self._decoder_type = self._original_decoder.decoder_type() super().__init__(code, code.ambient_space(), self._original_decoder.connected_encoder()) def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Ce = codes.ExtendedCode(C)\n sage: D = codes.decoders.ExtendedCodeOriginalCodeDecoder(Ce)\n sage: D\n Decoder of Extension of [15, 7, 9] Reed-Solomon Code over GF(16) through Gao decoder for [15, 7, 9] Reed-Solomon Code over GF(16)\n " return ('Decoder of %s through %s' % (self.code(), self.original_decoder())) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Ce = codes.ExtendedCode(C)\n sage: D = codes.decoders.ExtendedCodeOriginalCodeDecoder(Ce)\n sage: latex(D)\n \\textnormal{Decoder of } Extension of [15, 7, 9] Reed-Solomon Code over GF(16) \\textnormal{ through } Gao decoder for [15, 7, 9] Reed-Solomon Code over GF(16)\n " return ('\\textnormal{Decoder of } %s \\textnormal{ through } %s' % (self.code(), self.original_decoder())) def original_decoder(self): "\n Return the decoder over the original code that will be used to decode words of\n :meth:`sage.coding.decoder.Decoder.code`.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Ce = codes.ExtendedCode(C)\n sage: D = codes.decoders.ExtendedCodeOriginalCodeDecoder(Ce)\n sage: D.original_decoder()\n Gao decoder for [15, 7, 9] Reed-Solomon Code over GF(16)\n " return self._original_decoder def decode_to_code(self, y, **kwargs): "\n Decode ``y`` to an element in :meth:`sage.coding.decoder.Decoder.code`.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Ce = codes.ExtendedCode(C)\n sage: D = codes.decoders.ExtendedCodeOriginalCodeDecoder(Ce)\n sage: c = Ce.random_element()\n sage: Chan = channels.StaticErrorRateChannel(Ce.ambient_space(),\n ....: D.decoding_radius())\n sage: y = Chan(c)\n sage: y in Ce\n False\n sage: D.decode_to_code(y) == c\n True\n\n Another example, with a list decoder::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Ce = codes.ExtendedCode(C)\n sage: Dgrs = C.decoder('GuruswamiSudan', tau=4)\n sage: D = codes.decoders.ExtendedCodeOriginalCodeDecoder(Ce,\n ....: original_decoder=Dgrs)\n sage: c = Ce.random_element()\n sage: Chan = channels.StaticErrorRateChannel(Ce.ambient_space(),\n ....: D.decoding_radius())\n sage: y = Chan(c)\n sage: y in Ce\n False\n sage: c in D.decode_to_code(y)\n True\n " D = self.original_decoder() C = self.code() F = C.base_field() n = C.length() y_original = copy(y.list()) y_original.pop((n - 1)) decoded = D.decode_to_code(vector(y_original), **kwargs) if ('list-decoder' in self.decoder_type()): l = [] for word in decoded: last_pos = F.zero() for i in word: last_pos += i word_list = list(word) word_list.append(last_pos) l.append(vector(F, word_list)) return l else: last_pos = F.zero() for i in decoded: last_pos += i decoded_list = list(decoded) decoded_list.append(last_pos) return vector(F, decoded_list) def decoding_radius(self, *args, **kwargs): "\n Return maximal number of errors that ``self`` can decode.\n\n INPUT:\n\n - ``*args``, ``**kwargs`` -- arguments and optional arguments are\n forwarded to original decoder's ``decoding_radius`` method.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Ce = codes.ExtendedCode(C)\n sage: D = codes.decoders.ExtendedCodeOriginalCodeDecoder(Ce)\n sage: D.decoding_radius()\n 4\n " return self.original_decoder().decoding_radius(*args, **kwargs)
class GabidulinCode(AbstractLinearRankMetricCode): '\n A Gabidulin Code.\n\n DEFINITION:\n\n A linear Gabidulin code Gab[n, k] over `F_{q^m}` of length `n` (at most\n `m`) and dimension `k` (at most `n`) is the set of all codewords, that\n are the evaluation of a `q`-degree restricted skew polynomial `f(x)`\n belonging to the skew polynomial constructed over the base ring `F_{q^m}`\n and the twisting homomorphism `\\sigma`.\n\n .. math::\n\n \\{ \\text{Gab[n, k]} = \\big\\{ (f(g_0) f(g_1) ... f(g_{n-1})) = f(\\textbf{g}) : \\text{deg}_{q}f(x) < k \\big\\} \\}\n\n where the fixed evaluation points `g_0, g_1,..., g_{n-1}` are linearly\n independent over `F_{q^m}`.\n\n EXAMPLES:\n\n A Gabidulin Code can be constructed in the following way::\n\n sage: Fqm = GF(16)\n sage: Fq = GF(4)\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: C\n [2, 2, 1] linear Gabidulin code over GF(16)/GF(4)\n ' _registered_encoders = {} _registered_decoders = {} def __init__(self, base_field, length, dimension, sub_field=None, twisting_homomorphism=None, evaluation_points=None): "\n Representation of a Gabidulin Code.\n\n INPUT:\n\n - ``base_field`` -- finite field of order `q^m` where `q` is a prime power\n and `m` is an integer\n\n - ``length`` -- length of the resulting code\n\n - ``dimension`` -- dimension of the resulting code\n\n - ``sub_field`` -- (default: ``None``) finite field of order `q`\n which is a subfield of the ``base_field``. If not given, it is the\n prime subfield of the ``base_field``.\n\n - ``twisting_homomorphism`` -- (default: ``None``) homomorphism of the\n underlying skew polynomial ring. If not given, it is the Frobenius\n endomorphism on ``base_field``, which sends an element `x` to `x^{q}`.\n\n - ``evaluation_points`` -- (default: ``None``) list of elements\n `g_0, g_1,...,g_{n-1}` of the ``base_field`` that are linearly\n independent over the ``sub_field``. These elements form the first row\n of the generator matrix. If not specified, these are the `nth` powers\n of the generator of the ``base_field``.\n\n Both parameters ``sub_field`` and ``twisting_homomorphism`` are optional.\n Since they are closely related, here is a complete list of behaviours:\n\n - both ``sub_field`` and ``twisting_homomorphism`` given -- in this case\n we only check that given that ``twisting_homomorphism`` has a fixed\n field method, it returns ``sub_field``\n\n - only ``twisting_homomorphism`` given -- we set ``sub_field`` to be the\n fixed field of the ``twisting_homomorphism``. If such method does not\n exist, an error is raised.\n\n - only ``sub_field`` given -- we set ``twisting_homomorphism`` to be the\n Frobenius of the field extension\n\n - neither ``sub_field`` or ``twisting_homomorphism`` given -- we take\n ``sub_field`` to be the prime field of ``base_field`` and the\n ``twisting_homomorphism`` to be the Frobenius wrt. the prime field\n\n TESTS:\n\n If ``length`` is bigger than the degree of the extension, an error is\n raised::\n\n sage: C = codes.GabidulinCode(GF(64), 4, 3, GF(4))\n Traceback (most recent call last):\n ...\n ValueError: 'length' can be at most the degree of the extension, 3\n\n If the number of evaluation points is not equal to the length\n of the code, an error is raised::\n\n sage: Fqm = GF(5^20)\n sage: Fq = GF(5)\n sage: aa = Fqm.gen()\n sage: evals = [ aa^i for i in range(21) ]\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq, None, evals)\n Traceback (most recent call last):\n ...\n ValueError: the number of evaluation points should be equal to the length of the code\n\n If evaluation points are not linearly independent over the ``base_field``,\n an error is raised::\n\n sage: evals = [ aa*i for i in range(2) ]\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq, None, evals)\n Traceback (most recent call last):\n ...\n ValueError: the evaluation points provided are not linearly independent\n\n If an evaluation point does not belong to the ``base_field``, an error\n is raised::\n\n sage: a = GF(3).gen()\n sage: evals = [ a*i for i in range(2) ]\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq, None, evals)\n Traceback (most recent call last):\n ...\n ValueError: evaluation point does not belong to the 'base field'\n\n Given that both ``sub_field`` and ``twisting_homomorphism`` are specified\n and ``twisting_homomorphism`` has a fixed field method. If the fixed\n field of ``twisting_homomorphism`` is not ``sub_field``, an error is\n raised::\n\n sage: Fqm = GF(64)\n sage: Fq = GF(8)\n sage: twist = GF(64).frobenius_endomorphism(n=2)\n sage: C = codes.GabidulinCode(Fqm, 3, 2, Fq, twist)\n Traceback (most recent call last):\n ...\n ValueError: the fixed field of the twisting homomorphism has to be the relative field of the extension\n\n If ``twisting_homomorphism`` is given, but ``sub_field`` is not. In case\n ``twisting_homomorphism`` does not have a fixed field method, and error\n is raised::\n\n sage: Fqm.<z6> = GF(64)\n sage: sigma = Hom(Fqm, Fqm)[1]; sigma\n Ring endomorphism of Finite Field in z6 of size 2^6\n Defn: z6 |--> z6^2\n sage: C = codes.GabidulinCode(Fqm, 3, 2, None, sigma)\n Traceback (most recent call last):\n ...\n ValueError: if 'sub_field' is not given, the twisting homomorphism has to have a 'fixed_field' method\n " twist_fix_field = None have_twist = (twisting_homomorphism is not None) have_subfield = (sub_field is not None) if (have_twist and have_subfield): try: twist_fix_field = twisting_homomorphism.fixed_field()[0] except AttributeError: pass if (twist_fix_field and (twist_fix_field.order() != sub_field.order())): raise ValueError('the fixed field of the twisting homomorphism has to be the relative field of the extension') if (have_twist and (not have_subfield)): if (not twist_fix_field): raise ValueError("if 'sub_field' is not given, the twisting homomorphism has to have a 'fixed_field' method") else: sub_field = twist_fix_field if ((not have_twist) and have_subfield): twisting_homomorphism = base_field.frobenius_endomorphism(n=sub_field.degree()) if ((not have_twist) and (not have_subfield)): sub_field = base_field.base_ring() twisting_homomorphism = base_field.frobenius_endomorphism() self._twisting_homomorphism = twisting_homomorphism super().__init__(base_field, sub_field, length, 'VectorEvaluation', 'Gao') if (length > self.extension_degree()): raise ValueError("'length' can be at most the degree of the extension, {}".format(self.extension_degree())) if (evaluation_points is None): evaluation_points = [(base_field.gen() ** i) for i in range(base_field.degree())][:length] else: if (not (len(evaluation_points) == length)): raise ValueError('the number of evaluation points should be equal to the length of the code') for i in range(length): if (not (evaluation_points[i] in base_field)): raise ValueError("evaluation point does not belong to the 'base field'") basis = self.matrix_form_of_vector(vector(evaluation_points)) if (basis.rank() != length): raise ValueError('the evaluation points provided are not linearly independent') self._evaluation_points = evaluation_points self._dimension = dimension def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: Fqm = GF(16)\n sage: Fq = GF(4)\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq); C\n [2, 2, 1] linear Gabidulin code over GF(16)/GF(4)\n ' R = self.base_field() S = self.sub_field() if (R and (S in Fields())): return ('[%s, %s, %s] linear Gabidulin code over GF(%s)/GF(%s)' % (self.length(), self.dimension(), self.minimum_distance(), R.cardinality(), S.cardinality())) else: return ('[%s, %s, %s] linear Gabidulin code over %s/%s' % (self.length(), self.dimension(), self.minimum_distance(), R, S)) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: Fqm = GF(16)\n sage: Fq = GF(4)\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq);\n sage: latex(C)\n [2, 2, 1] \\textnormal{ linear Gabidulin code over } \\Bold{F}_{2^{4}}/\\Bold{F}_{2^{2}}\n ' txt = '[%s, %s, %s] \\textnormal{ linear Gabidulin code over } %s/%s' return (txt % (self.length(), self.dimension(), self.minimum_distance(), self.base_field()._latex_(), self.sub_field()._latex_())) def __eq__(self, other): '\n Test equality between Gabidulin Code objects.\n\n INPUT:\n\n - ``other`` -- another Gabidulin Code object\n\n OUTPUT:\n\n - ``True`` or ``False``\n\n EXAMPLES::\n\n sage: Fqm = GF(16)\n sage: Fq = GF(4)\n sage: C1 = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: C2 = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: C1.__eq__(C2)\n True\n\n sage: Fqmm = GF(64)\n sage: C3 = codes.GabidulinCode(Fqmm, 2, 2, Fq)\n sage: C3.__eq__(C2)\n False\n ' return (isinstance(other, GabidulinCode) and (self.base_field() == other.base_field()) and (self.sub_field() == other.sub_field()) and (self.length() == other.length()) and (self.dimension() == other.dimension()) and (self.evaluation_points() == other.evaluation_points())) def twisting_homomorphism(self): '\n Return the twisting homomorphism of ``self``.\n\n EXAMPLES::\n\n sage: Fqm = GF(5^20)\n sage: Fq = GF(5^4)\n sage: C = codes.GabidulinCode(Fqm, 5, 3, Fq)\n sage: C.twisting_homomorphism()\n Frobenius endomorphism z20 |--> z20^(5^4) on Finite Field in z20 of size 5^20\n ' return self._twisting_homomorphism def minimum_distance(self): '\n Return the minimum distance of ``self``.\n\n Since Gabidulin Codes are Maximum-Distance-Separable (MDS), this returns\n ``self.length() - self.dimension() + 1``.\n\n EXAMPLES::\n\n sage: Fqm = GF(5^20)\n sage: Fq = GF(5)\n sage: C = codes.GabidulinCode(Fqm, 20, 15, Fq)\n sage: C.minimum_distance()\n 6\n ' return ((self.length() - self.dimension()) + 1) def parity_evaluation_points(self): '\n Return the parity evaluation points of ``self``.\n\n These form the first row of the parity check matrix of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GabidulinCode(GF(2^10), 5, 2)\n sage: list(C.parity_check_matrix().row(0)) == C.parity_evaluation_points() #indirect_doctest\n True\n ' eval_pts = self.evaluation_points() n = self.length() k = self.dimension() sigma = self.twisting_homomorphism() coefficient_matrix = matrix(self.base_field(), (n - 1), n, (lambda i, j: (sigma ** ((((- n) + k) + 1) + i))(eval_pts[j]))) solution_space = coefficient_matrix.right_kernel() return list(solution_space.basis()[0]) def dual_code(self): '\n Return the dual code `C^{\\perp}` of ``self``, the code `C`,\n\n .. MATH::\n\n C^{\\perp} = \\{ v \\in V\\ |\\ v\\cdot c = 0,\\ \\forall c \\in C \\}.\n\n EXAMPLES::\n\n sage: C = codes.GabidulinCode(GF(2^10), 5, 2)\n sage: C1 = C.dual_code(); C1\n [5, 3, 3] linear Gabidulin code over GF(1024)/GF(2)\n sage: C == C1.dual_code()\n True\n ' return GabidulinCode(self.base_field(), self.length(), (self.length() - self.dimension()), self.sub_field(), self.twisting_homomorphism(), self.parity_evaluation_points()) def parity_check_matrix(self): '\n Return the parity check matrix of ``self``.\n\n This is the generator matrix of the dual code of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GabidulinCode(GF(2^3), 3, 2)\n sage: C.parity_check_matrix()\n [ 1 z3 z3^2 + z3]\n sage: C.parity_check_matrix() == C.dual_code().generator_matrix()\n True\n ' return self.dual_code().generator_matrix() def evaluation_points(self): '\n Return the evaluation points of ``self``.\n\n EXAMPLES::\n\n sage: Fqm = GF(5^20)\n sage: Fq = GF(5^4)\n sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq)\n sage: C.evaluation_points()\n [1, z20, z20^2, z20^3]\n ' return self._evaluation_points
class GabidulinVectorEvaluationEncoder(Encoder): def __init__(self, code): '\n This method constructs the vector evaluation encoder for\n Gabidulin Codes.\n\n INPUT:\n\n - ``code`` -- the associated code of this encoder.\n\n EXAMPLES::\n\n sage: Fqm = GF(16)\n sage: Fq = GF(4)\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: E = codes.encoders.GabidulinVectorEvaluationEncoder(C)\n sage: E\n Vector evaluation style encoder for [2, 2, 1] linear Gabidulin code over GF(16)/GF(4)\n\n Alternatively, we can construct the encoder from ``C`` directly::\n\n sage: E = C.encoder("VectorEvaluation")\n sage: E\n Vector evaluation style encoder for [2, 2, 1] linear Gabidulin code over GF(16)/GF(4)\n\n TESTS:\n\n If the code is not a Gabidulin code, an error is raised::\n\n sage: C = codes.HammingCode(GF(4), 2)\n sage: E = codes.encoders.GabidulinVectorEvaluationEncoder(C)\n Traceback (most recent call last):\n ...\n ValueError: code has to be a Gabidulin code\n ' if (not isinstance(code, GabidulinCode)): raise ValueError('code has to be a Gabidulin code') super().__init__(code) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: Fqm = GF(5^20)\n sage: Fq = GF(5^4)\n sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq)\n sage: E = codes.encoders.GabidulinVectorEvaluationEncoder(C); E\n Vector evaluation style encoder for [4, 4, 1] linear Gabidulin code over GF(95367431640625)/GF(625)\n ' return ('Vector evaluation style encoder for %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: Fqm = GF(5^20)\n sage: Fq = GF(5^4)\n sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq)\n sage: E = codes.encoders.GabidulinVectorEvaluationEncoder(C)\n sage: latex(E)\n \\textnormal{Vector evaluation style encoder for } [4, 4, 1] \\textnormal{ linear Gabidulin code over } \\Bold{F}_{5^{20}}/\\Bold{F}_{5^{4}}\n ' return ('\\textnormal{Vector evaluation style encoder for } %s' % self.code()._latex_()) def __eq__(self, other): '\n Test equality between Gabidulin Generator Matrix Encoder objects.\n\n INPUT:\n\n - ``other`` -- another Gabidulin Generator Matrix Encoder\n\n OUTPUT:\n\n - ``True`` or ``False``\n\n EXAMPLES::\n\n sage: Fqm = GF(16)\n sage: Fq = GF(4)\n sage: C1 = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: E1 = codes.encoders.GabidulinVectorEvaluationEncoder(C1)\n sage: C2 = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: E2 = codes.encoders.GabidulinVectorEvaluationEncoder(C2)\n sage: E1.__eq__(E2)\n True\n\n sage: Fqmm = GF(64)\n sage: C3 = codes.GabidulinCode(Fqmm, 2, 2, Fq)\n sage: E3 = codes.encoders.GabidulinVectorEvaluationEncoder(C3)\n sage: E3.__eq__(E2)\n False\n ' return (isinstance(other, GabidulinVectorEvaluationEncoder) and (self.code() == other.code())) def generator_matrix(self): '\n Return the generator matrix of ``self``.\n\n EXAMPLES::\n\n sage: Fqm = GF(2^9)\n sage: Fq = GF(2^3)\n sage: C = codes.GabidulinCode(Fqm, 3, 3, Fq)\n sage: (list(C.generator_matrix().row(1))\n ....: == [C.evaluation_points()[i]**(2**3) for i in range(3)])\n True\n ' from functools import reduce C = self.code() eval_pts = C.evaluation_points() sigma = C.twisting_homomorphism() def create_matrix_elements(A, k, f): return reduce((lambda L, x: ([x] + [list(map(f, l)) for l in L])), ([A] * k), []) return matrix(C.base_field(), C.dimension(), C.length(), create_matrix_elements(eval_pts, C.dimension(), sigma))
class GabidulinPolynomialEvaluationEncoder(Encoder): '\n Encoder for Gabidulin codes which uses evaluation of skew polynomials to\n obtain codewords.\n\n Let `C` be a Gabidulin code of length `n` and dimension `k` over some\n finite field `F = GF(q^m)`. We denote by `\\alpha_i` its evaluations\n points, where `1 \\leq i \\leq n`. Let `p`, a skew polynomial of degree at\n most `k-1` in `F[x]`, be the message.\n\n The encoding of `m` will be the following codeword:\n\n .. MATH::\n\n (p(\\alpha_1), \\dots, p(\\alpha_n)).\n\n TESTS:\n\n This module uses the following experimental feature.\n This test block is here only to trigger the experimental warning so it does not\n interferes with doctests::\n\n sage: Fqm = GF(2^9)\n sage: Fq = GF(2^3)\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: S.<x> = Fqm[\'x\', C.twisting_homomorphism()]\n sage: z9 = Fqm.gen()\n sage: p = (z9^6 + z9^2 + z9 + 1)*x + z9^7 + z9^5 + z9^4 + z9^2\n sage: vector(p.multi_point_evaluation(C.evaluation_points()))\n doctest:...: FutureWarning: This class/method/function is marked as experimental.\n It, its functionality or its interface might change without a formal deprecation.\n See https://github.com/sagemath/sage/issues/13215 for details.\n (z9^7 + z9^6 + z9^5 + z9^4 + z9 + 1, z9^6 + z9^5 + z9^3 + z9)\n\n EXAMPLES::\n\n sage: Fqm = GF(16)\n sage: Fq = GF(4)\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C)\n sage: E\n Polynomial evaluation style encoder for\n [2, 2, 1] linear Gabidulin code over GF(16)/GF(4)\n\n Alternatively, we can construct the encoder from ``C`` directly::\n\n sage: E = C.encoder("PolynomialEvaluation")\n sage: E\n Polynomial evaluation style encoder for\n [2, 2, 1] linear Gabidulin code over GF(16)/GF(4)\n ' def __init__(self, code): '\n INPUT:\n\n - ``code`` -- the associated code of this encoder\n\n TESTS:\n\n If the code is not a Gabidulin code, an error is raised::\n\n sage: C = codes.HammingCode(GF(4), 2)\n sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C)\n Traceback (most recent call last):\n ...\n ValueError: code has to be a Gabidulin code\n ' if (not isinstance(code, GabidulinCode)): raise ValueError('code has to be a Gabidulin code') super().__init__(code) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: Fqm = GF(5^20)\n sage: Fq = GF(5^4)\n sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq)\n sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C); E\n Polynomial evaluation style encoder for [4, 4, 1] linear Gabidulin code over GF(95367431640625)/GF(625)\n ' return ('Polynomial evaluation style encoder for %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: Fqm = GF(5^20)\n sage: Fq = GF(5^4)\n sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq)\n sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C)\n sage: latex(E)\n \\textnormal{Polynomial evaluation style encoder for } [4, 4, 1] \\textnormal{ linear Gabidulin code over } \\Bold{F}_{5^{20}}/\\Bold{F}_{5^{4}}\n ' return ('\\textnormal{Polynomial evaluation style encoder for } %s' % self.code()._latex_()) def __eq__(self, other): '\n Test equality between Gabidulin Polynomial Evaluation Encoder objects.\n\n INPUT:\n\n - ``other`` -- another Gabidulin Polynomial Evaluation Encoder\n\n OUTPUT:\n\n - ``True`` or ``False``\n\n EXAMPLES::\n\n sage: Fqm = GF(16)\n sage: Fq = GF(4)\n sage: C1 = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: E1 = codes.encoders.GabidulinPolynomialEvaluationEncoder(C1)\n sage: C2 = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: E2 = codes.encoders.GabidulinPolynomialEvaluationEncoder(C2)\n sage: E1.__eq__(E2)\n True\n\n sage: Fqmm = GF(64)\n sage: C3 = codes.GabidulinCode(Fqmm, 2, 2, Fq)\n sage: E3 = codes.encoders.GabidulinPolynomialEvaluationEncoder(C3)\n sage: E3.__eq__(E2)\n False\n ' return (isinstance(other, GabidulinPolynomialEvaluationEncoder) and (self.code() == other.code())) def message_space(self): '\n Return the message space of the associated code of ``self``.\n\n EXAMPLES::\n\n sage: Fqm = GF(5^20)\n sage: Fq = GF(5^4)\n sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq)\n sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C)\n sage: E.message_space()\n Ore Polynomial Ring in x over Finite Field in z20 of size 5^20\n twisted by z20 |--> z20^(5^4)\n ' C = self.code() return C.base_field()[('x', C.twisting_homomorphism())] def encode(self, p, form='vector'): '\n Transform the polynomial ``p`` into a codeword of :meth:`code`.\n\n The output codeword can be represented as a vector or a matrix,\n depending on the ``form`` input.\n\n INPUT:\n\n - ``p`` -- a skew polynomial from the message space of ``self`` of degree\n less than ``self.code().dimension()``\n\n - ``form`` -- type parameter taking strings "vector" or "matrix"\n as values and converting the output codeword into the respective form\n (default: "vector")\n\n OUTPUT:\n\n - a codeword corresponding to `p` in vector or matrix form\n\n EXAMPLES::\n\n sage: Fqm = GF(2^9)\n sage: Fq = GF(2^3)\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C)\n sage: S.<x> = Fqm[\'x\', C.twisting_homomorphism()]\n sage: z9 = Fqm.gen()\n sage: p = (z9^6 + z9^2 + z9 + 1)*x + z9^7 + z9^5 + z9^4 + z9^2\n sage: codeword_vector = E.encode(p, "vector"); codeword_vector\n (z9^7 + z9^6 + z9^5 + z9^4 + z9 + 1, z9^6 + z9^5 + z9^3 + z9)\n sage: codeword_matrix = E.encode(p, "matrix"); codeword_matrix\n [ z3 z3^2 + z3]\n [ z3 1]\n [ z3^2 z3^2 + z3 + 1]\n\n TESTS:\n\n If the skew polynomial, `p`, has degree greater than or equal to the\n dimension of the code, an error is raised::\n\n sage: t = z9^4*x^2 + z9\n sage: codeword_vector = E.encode(t, "vector"); codeword_vector\n Traceback (most recent call last):\n ...\n ValueError: the skew polynomial to encode must have degree at most 1\n\n The skew polynomial, `p`, must belong to the message space of the code.\n Otherwise, an error is raised::\n\n sage: Fqmm = GF(2^12)\n sage: S.<x> = Fqmm[\'x\', Fqmm.frobenius_endomorphism(n=3)]\n sage: q = S.random_element(degree=2)\n sage: codeword_vector = E.encode(q, "vector"); codeword_vector\n Traceback (most recent call last):\n ...\n ValueError: the message to encode must be in Ore Polynomial Ring in x over Finite Field in z9 of size 2^9 twisted by z9 |--> z9^(2^3)\n ' C = self.code() M = self.message_space() if (p not in M): raise ValueError(('the message to encode must be in %s' % M)) if (p.degree() >= C.dimension()): raise ValueError(('the skew polynomial to encode must have degree at most %s' % (C.dimension() - 1))) eval_pts = C.evaluation_points() codeword = p.multi_point_evaluation(eval_pts) if (form == 'vector'): return vector(codeword) elif (form == 'matrix'): return C.matrix_form_of_vector(vector(codeword)) else: return ValueError("the argument 'form' takes only either 'vector' or 'matrix' as valid input") def unencode_nocheck(self, c): '\n Return the message corresponding to the codeword ``c``.\n\n Use this method with caution: it does not check if ``c``\n belongs to the code, and if this is not the case, the output is\n unspecified.\n\n INPUT:\n\n - ``c`` -- a codeword of :meth:`code`\n\n OUTPUT:\n\n - a skew polynomial of degree less than ``self.code().dimension()``\n\n EXAMPLES::\n\n sage: Fqm = GF(2^9)\n sage: Fq = GF(2^3)\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C)\n sage: S.<x> = Fqm[\'x\', C.twisting_homomorphism()]\n sage: z9 = Fqm.gen()\n sage: p = (z9^6 + z9^4)*x + z9^2 + z9\n sage: codeword_vector = E.encode(p, "vector")\n sage: E.unencode_nocheck(codeword_vector)\n (z9^6 + z9^4)*x + z9^2 + z9\n ' C = self.code() eval_pts = C.evaluation_points() values = [c[i] for i in range(len(c))] points = [(eval_pts[i], values[i]) for i in range(len(eval_pts))] p = self.message_space().lagrange_polynomial(points) return p
class GabidulinGaoDecoder(Decoder): def __init__(self, code): '\n Gao style decoder for Gabidulin Codes.\n\n INPUT:\n\n - ``code`` -- the associated code of this decoder\n\n EXAMPLES::\n\n sage: Fqm = GF(16)\n sage: Fq = GF(4)\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: D = codes.decoders.GabidulinGaoDecoder(C)\n sage: D\n Gao decoder for [2, 2, 1] linear Gabidulin code over GF(16)/GF(4)\n\n Alternatively, we can construct the encoder from ``C`` directly::\n\n sage: D = C.decoder("Gao")\n sage: D\n Gao decoder for [2, 2, 1] linear Gabidulin code over GF(16)/GF(4)\n\n TESTS:\n\n If the code is not a Gabidulin code, an error is raised::\n\n sage: C = codes.HammingCode(GF(4), 2)\n sage: D = codes.decoders.GabidulinGaoDecoder(C)\n Traceback (most recent call last):\n ...\n ValueError: code has to be a Gabidulin code\n ' if (not isinstance(code, GabidulinCode)): raise ValueError('code has to be a Gabidulin code') super().__init__(code, code.ambient_space(), 'PolynomialEvaluation') def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: Fqm = GF(5^20)\n sage: Fq = GF(5^4)\n sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq)\n sage: D = codes.decoders.GabidulinGaoDecoder(C); D\n Gao decoder for [4, 4, 1] linear Gabidulin code over GF(95367431640625)/GF(625)\n ' return ('Gao decoder for %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: Fqm = GF(5^20)\n sage: Fq = GF(5^4)\n sage: C = codes.GabidulinCode(Fqm, 4, 4, Fq)\n sage: D = codes.decoders.GabidulinGaoDecoder(C)\n sage: latex(D)\n \\textnormal{Gao decoder for } [4, 4, 1] \\textnormal{ linear Gabidulin code over } \\Bold{F}_{5^{20}}/\\Bold{F}_{5^{4}}\n ' return ('\\textnormal{Gao decoder for } %s' % self.code()._latex_()) def __eq__(self, other) -> bool: '\n Test equality between Gabidulin Gao Decoder objects.\n\n INPUT:\n\n - ``other`` -- another Gabidulin Gao Decoder\n\n OUTPUT:\n\n - ``True`` or ``False``\n\n EXAMPLES::\n\n sage: Fqm = GF(16)\n sage: Fq = GF(4)\n sage: C1 = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: D1 = codes.decoders.GabidulinGaoDecoder(C1)\n sage: C2 = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: D2 = codes.decoders.GabidulinGaoDecoder(C2)\n sage: D1.__eq__(D2)\n True\n\n sage: Fqmm = GF(64)\n sage: C3 = codes.GabidulinCode(Fqmm, 2, 2, Fq)\n sage: D3 = codes.decoders.GabidulinGaoDecoder(C3)\n sage: D3.__eq__(D2)\n False\n ' return (isinstance(other, GabidulinGaoDecoder) and (self.code() == other.code())) def _partial_xgcd(self, a, b, d_stop): '\n Compute the partial gcd of `a` and `b` using the right linearized\n extended Euclidean algorithm up to the `d_stop` iterations. This\n is a private method for internal use only.\n\n INPUT:\n\n - ``a`` -- a skew polynomial\n\n - ``b`` -- another skew polynomial\n\n - ``d_stop`` -- the number of iterations for which the algorithm\n is to be run\n\n OUTPUT:\n\n - ``r_c`` -- right linearized remainder of `a` and `b`\n\n - ``u_c`` -- right linearized quotient of `a` and `b`\n\n EXAMPLES::\n\n sage: Fqm = GF(2^9)\n sage: Fq = GF(2^3)\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: D = codes.decoders.GabidulinGaoDecoder(C)\n sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C)\n sage: S.<x> = Fqm[\'x\', C.twisting_homomorphism()]\n sage: z9 = Fqm.gen()\n sage: p = (z9^6 + z9^4)*x + z9^2 + z9\n sage: codeword_vector = E.encode(p, "vector")\n sage: r = D.decode_to_message(codeword_vector) #indirect_doctest\n sage: r\n (z9^6 + z9^4)*x + z9^2 + z9\n ' S = self.message_space() if ((a not in S) or (b not in S)): raise ValueError(('both the input polynomials must belong to %s' % S)) if (a.degree() < b.degree()): raise ValueError('degree of first polynomial must be greater than or equal to degree of second polynomial') r_p = a r_c = b u_p = S.zero() u_c = S.one() v_p = u_c v_c = u_p while (r_c.degree() >= d_stop): ((q, r_c), r_p) = (r_p.right_quo_rem(r_c), r_c) (u_c, u_p) = ((u_p - (q * u_c)), u_c) (v_c, v_p) = ((v_p - (q * v_c)), v_c) return (r_c, u_c) def _decode_to_code_and_message(self, r): '\n Return the decoded codeword and message (skew polynomial)\n corresponding to the received codeword `r`. This is a\n private method for internal use only.\n\n INPUT:\n\n - ``r`` -- received codeword\n\n OUTPUT:\n\n - the decoded codeword and decoded message corresponding to\n the received codeword `r`\n\n EXAMPLES::\n\n sage: Fqm = GF(2^9)\n sage: Fq = GF(2^3)\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: D = codes.decoders.GabidulinGaoDecoder(C)\n sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C)\n sage: S.<x> = Fqm[\'x\', C.twisting_homomorphism()]\n sage: z9 = Fqm.gen()\n sage: p = (z9^6 + z9^4)*x + z9^2 + z9\n sage: codeword_vector = E.encode(p, "vector")\n sage: r = D.decode_to_message(codeword_vector) #indirect doctest\n sage: r\n (z9^6 + z9^4)*x + z9^2 + z9\n ' C = self.code() length = len(r) eval_pts = C.evaluation_points() S = self.message_space() if ((length == C.dimension()) or (r in C)): return (r, self.connected_encoder().unencode_nocheck(r)) points = [(eval_pts[i], r[i]) for i in range(len(eval_pts))] R = S.lagrange_polynomial(points) (r_out, u_out) = self._partial_xgcd(S.minimal_vanishing_polynomial(eval_pts), R, ((C.length() + C.dimension()) // 2)) (quo, rem) = r_out.left_quo_rem(u_out) if (not rem.is_zero()): raise DecodingError('Decoding failed because the number of errors exceeded the decoding radius') if (quo not in S): raise DecodingError('Decoding failed because the number of errors exceeded the decoding radius') c = self.connected_encoder().encode(quo) if (C.rank_weight_of_vector((c - r)) > self.decoding_radius()): raise DecodingError('Decoding failed because the number of errors exceeded the decoding radius') return (c, quo) def decode_to_code(self, r): '\n Return the decoded codeword corresponding to the\n received word `r`.\n\n INPUT:\n\n - ``r`` -- received codeword\n\n OUTPUT:\n\n - the decoded codeword corresponding to the received codeword\n\n EXAMPLES::\n\n sage: Fqm = GF(3^20)\n sage: Fq = GF(3)\n sage: C = codes.GabidulinCode(Fqm, 5, 3, Fq)\n sage: D = codes.decoders.GabidulinGaoDecoder(C)\n sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C)\n sage: S.<x> = Fqm[\'x\', C.twisting_homomorphism()]\n sage: z20 = Fqm.gen()\n sage: p = x\n sage: codeword_vector = E.encode(p, "vector")\n sage: codeword_vector\n (1, z20^3, z20^6, z20^9, z20^12)\n sage: l = list(codeword_vector)\n sage: l[0] = l[1] #make an error\n sage: D.decode_to_code(vector(l))\n (1, z20^3, z20^6, z20^9, z20^12)\n ' return self._decode_to_code_and_message(r)[0] def decode_to_message(self, r): '\n Return the skew polynomial (message) corresponding to the\n received word `r`.\n\n INPUT:\n\n - ``r`` -- received codeword\n\n OUTPUT:\n\n - the message corresponding to the received codeword\n\n EXAMPLES::\n\n sage: Fqm = GF(2^9)\n sage: Fq = GF(2^3)\n sage: C = codes.GabidulinCode(Fqm, 2, 2, Fq)\n sage: D = codes.decoders.GabidulinGaoDecoder(C)\n sage: E = codes.encoders.GabidulinPolynomialEvaluationEncoder(C)\n sage: S.<x> = Fqm[\'x\', C.twisting_homomorphism()]\n sage: z9 = Fqm.gen()\n sage: p = (z9^6 + z9^4)*x + z9^2 + z9\n sage: codeword_vector = E.encode(p, "vector")\n sage: r = D.decode_to_message(codeword_vector)\n sage: r\n (z9^6 + z9^4)*x + z9^2 + z9\n ' return self._decode_to_code_and_message(r)[1] def decoding_radius(self): '\n Return the decoding radius of the Gabidulin Gao Decoder.\n\n EXAMPLES::\n\n sage: Fqm = GF(5^20)\n sage: Fq = GF(5)\n sage: C = codes.GabidulinCode(Fqm, 20, 4, Fq)\n sage: D = codes.decoders.GabidulinGaoDecoder(C)\n sage: D.decoding_radius()\n 8\n ' return ((self.code().minimum_distance() - 1) // 2)
class GolayCode(AbstractLinearCode): '\n Representation of a Golay Code.\n\n INPUT:\n\n - ``base_field`` -- The base field over which the code is defined.\n Can only be ``GF(2)`` or ``GF(3)``.\n\n - ``extended`` -- (default: ``True``) if set to ``True``, creates an extended Golay\n code.\n\n EXAMPLES::\n\n sage: codes.GolayCode(GF(2))\n [24, 12, 8] Extended Golay code over GF(2)\n\n Another example with the perfect binary Golay code::\n\n sage: codes.GolayCode(GF(2), False)\n [23, 12, 7] Golay code over GF(2)\n\n TESTS:\n\n sage: G = codes.GolayCode(GF(2),False)\n sage: G0 = codes.GolayCode(GF(2),True)\n sage: G0prime = G.extended_code()\n sage: G0.generator_matrix() * G0prime.parity_check_matrix().transpose() == 0\n True\n\n sage: G0perp = G0.dual_code()\n sage: G0.generator_matrix() * G0perp.generator_matrix().transpose() == 0\n True\n\n sage: G = codes.GolayCode(GF(3),False)\n sage: G0 = codes.GolayCode(GF(3),True)\n sage: G0prime = G.extended_code()\n sage: G0.generator_matrix() * G0prime.parity_check_matrix().transpose() == 0\n True\n\n sage: G0perp = G0.dual_code()\n sage: G0.generator_matrix() * G0perp.generator_matrix().transpose() == 0\n True\n ' _registered_encoders = {} _registered_decoders = {} def __init__(self, base_field, extended=True): '\n TESTS:\n\n If ``base_field`` is not ``GF(2)`` or ``GF(3)``, an error is raised::\n\n sage: C = codes.GolayCode(ZZ, true)\n Traceback (most recent call last):\n ...\n ValueError: finite_field must be either GF(2) or GF(3)\n ' if (base_field not in [GF(2), GF(3)]): raise ValueError('finite_field must be either GF(2) or GF(3)') if (extended not in [True, False]): raise ValueError('extension must be either True or False') if (base_field is GF(2)): length = 23 self._dimension = 12 else: length = 11 self._dimension = 6 if extended: length += 1 super().__init__(base_field, length, 'GeneratorMatrix', 'Syndrome') def __eq__(self, other): '\n Test equality between Golay Code objects.\n\n EXAMPLES::\n\n sage: C1 = codes.GolayCode(GF(2))\n sage: C2 = codes.GolayCode(GF(2))\n sage: C1.__eq__(C2)\n True\n ' return (isinstance(other, GolayCode) and (self.base_field() == other.base_field()) and (self.length() == other.length())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: codes.GolayCode(GF(2),extended=True)\n [24, 12, 8] Extended Golay code over GF(2)\n ' n = self.length() ext = '' if ((n % 2) == 0): ext = 'Extended' return ('[%s, %s, %s] %s Golay code over GF(%s)' % (n, self.dimension(), self.minimum_distance(), ext, self.base_field().cardinality())) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: latex(C)\n [24, 12, 8] \\textnormal{ Extended Golay Code over } \\Bold{F}_{2}\n ' n = self.length() ext = '' if ((n % 2) == 0): ext = 'Extended' return ('[%s, %s, %s] \\textnormal{ %s Golay Code over } %s' % (n, self.dimension(), self.minimum_distance(), ext, self.base_field()._latex_())) def dual_code(self): '\n Return the dual code of ``self``.\n\n If ``self`` is an extended Golay code, ``self`` is returned.\n Otherwise, it returns the output of\n :meth:`sage.coding.linear_code_no_metric.AbstractLinearCodeNoMetric.dual_code`\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2), extended=True)\n sage: Cd = C.dual_code(); Cd\n [24, 12, 8] Extended Golay code over GF(2)\n\n sage: Cd == C\n True\n ' n = self.length() if ((n % 2) == 0): return self return super().dual_code() def minimum_distance(self): '\n Return the minimum distance of ``self``.\n\n The minimum distance of Golay codes is already known,\n and is thus returned immediately without computing anything.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: C.minimum_distance()\n 8\n ' n = self.length() if (n == 24): return 8 elif (n == 23): return 7 elif (n == 12): return 6 elif (n == 11): return 5 def covering_radius(self): '\n Return the covering radius of ``self``.\n\n The covering radius of a linear code `C` is the smallest\n integer `r` s.t. any element of the ambient space of `C` is at most at\n distance `r` to `C`.\n\n The covering radii of all Golay codes are known, and are thus returned\n by this method without performing any computation\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: C.covering_radius()\n 4\n sage: C = codes.GolayCode(GF(2),False)\n sage: C.covering_radius()\n 3\n sage: C = codes.GolayCode(GF(3))\n sage: C.covering_radius()\n 3\n sage: C = codes.GolayCode(GF(3),False)\n sage: C.covering_radius()\n 2\n ' n = self.length() if (n == 23): return 3 elif (n == 24): return 4 elif (n == 11): return 2 elif (n == 12): return 3 def weight_distribution(self): "\n Return the list whose `i`'th entry is the number of words of weight `i`\n in ``self``.\n\n The weight distribution of all Golay codes are known, and are thus returned\n by this method without performing any computation\n MWS (67, 69)\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(3))\n sage: C.weight_distribution()\n [1, 0, 0, 0, 0, 0, 264, 0, 0, 440, 0, 0, 24]\n\n TESTS::\n\n sage: C = codes.GolayCode(GF(2))\n sage: C.weight_distribution() == super(codes.GolayCode, C).weight_distribution()\n True\n\n sage: C = codes.GolayCode(GF(2), extended=False)\n sage: C.weight_distribution() == super(codes.GolayCode, C).weight_distribution()\n True\n\n sage: C = codes.GolayCode(GF(3))\n sage: C.weight_distribution() == super(codes.GolayCode, C).weight_distribution()\n True\n\n sage: C = codes.GolayCode(GF(3), extended=False)\n sage: C.weight_distribution() == super(codes.GolayCode, C).weight_distribution()\n True\n " n = self.length() if (n == 23): return (((((((((([1] + ([0] * 6)) + [253]) + [506]) + ([0] * 2)) + ([1288] * 2)) + ([0] * 2)) + [506]) + [253]) + ([0] * 6)) + [1]) if (n == 24): return (((((((([1] + ([0] * 7)) + [759]) + ([0] * 3)) + [2576]) + ([0] * 3)) + [759]) + ([0] * 7)) + [1]) if (n == 11): return ((((((([1] + ([0] * 4)) + ([132] * 2)) + [0]) + [330]) + [110]) + [0]) + [24]) if (n == 12): return (((((([1] + ([0] * 5)) + [264]) + ([0] * 2)) + [440]) + ([0] * 2)) + [24]) def generator_matrix(self): '\n Return a generator matrix of ``self``\n\n Generator matrices of all Golay codes are known, and are thus returned\n by this method without performing any computation\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2), extended=True)\n sage: C.generator_matrix()\n [1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 1 1 0 0 0 1 1]\n [0 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 1 0 0 1 0]\n [0 0 1 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 1 0 1 0 1 1]\n [0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 1 0 1 1 0]\n [0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 1 0 1 1 0 0 1]\n [0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 1 0 1 1 0 1]\n [0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 1 0 1 1 1]\n [0 0 0 0 0 0 0 1 0 0 0 0 1 0 1 1 0 1 1 1 1 0 0 0]\n [0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 1 1 0 1 1 1 1 0 0]\n [0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 1 1 0 1 1 1 1 0]\n [0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 1 1 0 0 0 1 1 0 1]\n [0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 1 1 0 0 0 1 1 1]\n ' n = self.length() if (n == 23): G = matrix(GF(2), [[1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1]]) elif (n == 24): G = matrix(GF(2), [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1]]) elif (n == 11): G = matrix(GF(3), [[2, 0, 1, 2, 1, 1, 0, 0, 0, 0, 0], [0, 2, 0, 1, 2, 1, 1, 0, 0, 0, 0], [0, 0, 2, 0, 1, 2, 1, 1, 0, 0, 0], [0, 0, 0, 2, 0, 1, 2, 1, 1, 0, 0], [0, 0, 0, 0, 2, 0, 1, 2, 1, 1, 0], [0, 0, 0, 0, 0, 2, 0, 1, 2, 1, 1]]) else: G = matrix(GF(3), [[1, 0, 0, 0, 0, 0, 2, 0, 1, 2, 1, 2], [0, 1, 0, 0, 0, 0, 1, 2, 2, 2, 1, 0], [0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1], [0, 0, 0, 1, 0, 0, 1, 1, 0, 2, 2, 2], [0, 0, 0, 0, 1, 0, 2, 1, 2, 2, 0, 1], [0, 0, 0, 0, 0, 1, 0, 2, 1, 2, 2, 1]]) return G def parity_check_matrix(self): '\n Return the parity check matrix of ``self``.\n\n The parity check matrix of a linear code `C` corresponds to the\n generator matrix of the dual code of `C`.\n\n Parity check matrices of all Golay codes are known, and are thus returned\n by this method without performing any computation.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(3), extended=False)\n sage: C.parity_check_matrix()\n [1 0 0 0 0 1 2 2 2 1 0]\n [0 1 0 0 0 0 1 2 2 2 1]\n [0 0 1 0 0 2 1 2 0 1 2]\n [0 0 0 1 0 1 1 0 1 1 1]\n [0 0 0 0 1 2 2 2 1 0 1]\n ' n = self.length() if (n == 23): H = matrix(GF(2), [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1]]) elif (n == 11): H = matrix(GF(3), [[1, 0, 0, 0, 0, 1, 2, 2, 2, 1, 0], [0, 1, 0, 0, 0, 0, 1, 2, 2, 2, 1], [0, 0, 1, 0, 0, 2, 1, 2, 0, 1, 2], [0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1], [0, 0, 0, 0, 1, 2, 2, 2, 1, 0, 1]]) else: H = self.generator_matrix() return H
def _columnize(element): '\n Convert a finite field element to a column vector over the prime field.\n\n TESTS::\n\n sage: from sage.coding.goppa_code import _columnize\n sage: F.<a> = GF(2^6)\n sage: _columnize(a)\n [0]\n [1]\n [0]\n [0]\n [0]\n [0]\n sage: _columnize(a+1)\n [1]\n [1]\n [0]\n [0]\n [0]\n [0]\n ' v = vector(element) return v.column()
class GoppaCode(AbstractLinearCode): '\n Implementation of Goppa codes.\n\n Goppa codes are a generalization of narrow-sense BCH codes.\n These codes are defined by a generating polynomial `g` over a finite field\n `\\GF{p^m}`, and a defining set `L` of elements from `\\GF{p^m}`, which are not roots\n of `g`. The number of defining elements determines the length of the code.\n\n In binary cases, the minimum distance is `2t + 1`, where `t` is the degree\n of `g`.\n\n INPUT:\n\n - ``generating_pol`` -- a monic polynomial with coefficients in a finite\n field `\\GF{p^m}`, the code is defined over `\\GF{p}`, `p` must be a prime number\n\n - ``defining_set`` -- a set of elements of `\\GF{p^m}` that are not roots\n of `g`, its cardinality is the length of the code\n\n EXAMPLES::\n\n sage: F = GF(2^6)\n sage: R.<x> = F[]\n sage: g = x^9 + 1\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: C\n [55, 16] Goppa code over GF(2)\n ' _registered_encoders = {} _registered_decoders = {} def __init__(self, generating_pol, defining_set): '\n Initialize.\n\n TESTS::\n\n sage: F = GF(2^6)\n sage: R.<x> = F[]\n sage: g = x^9 + 1\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: TestSuite(C).run()\n ' self._field = generating_pol.base_ring().prime_subfield() self._length = len(defining_set) self._generating_pol = generating_pol self._defining_set = defining_set super().__init__(self._field, self._length, 'GoppaEncoder', 'Syndrome') if (not generating_pol.is_monic()): raise ValueError('generating polynomial must be monic') F = self._field if ((not F.is_field()) or (not F.is_finite())): raise ValueError('generating polynomial must be defined over a finite field') for a in defining_set: if (generating_pol(a) == 0): raise ValueError('defining elements cannot be roots of generating polynomial') def _repr_(self): '\n Representation of a Goppa code\n\n EXAMPLES::\n\n sage: F = GF(2^3)\n sage: R.<x> = F[]\n sage: g = x^2 + x+ 1\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: C\n [8, 2] Goppa code over GF(2)\n ' return '[{}, {}] Goppa code over GF({})'.format(self.length(), self.dimension(), self.base_field().cardinality()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(2^3)\n sage: R.<x> = F[]\n sage: g = x^2 + x+ 1\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: latex(C)\n [8, 2]\\text{ Goppa code over }\\Bold{F}_{2}\n ' return '[{}, {}]\\text{{ Goppa code over }}{}'.format(self.length(), self.dimension(), self.base_field()._latex_()) def __eq__(self, other): '\n Test equality with ``other``.\n\n Two Goppa codes are considered the same when defining sets and\n generating polynomials are the same.\n\n EXAMPLES::\n\n sage: F = GF(2^3)\n sage: R.<x> = F[]\n sage: g = x^2 + x+ 1\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: D = codes.GoppaCode(g, L)\n sage: C == D\n True\n\n Note that equality check will be false if ``other`` represents the same\n linear code as ``self`` but not constructed as a Goppa code::\n\n sage: E = LinearCode(C.generator_matrix())\n sage: C == E\n False\n ' return (isinstance(other, GoppaCode) and (self.length() == other.length()) and (self._generating_pol == other._generating_pol) and (self._defining_set == other._defining_set)) def parity_check_matrix(self): '\n Return a parity check matrix for ``self``.\n\n The element in row `t`, column `i` is `h[i](D[i]^t)`, where:\n\n - `h[i]` -- is the inverse of `g(D[i])`\n - `D[i]` -- is the `i`-th element of the defining set\n\n In the resulting `d \\times n` matrix we interpret each entry as an\n `m`-column vector and return a `dm \\times n` matrix.\n\n EXAMPLES::\n\n sage: F = GF(2^3)\n sage: R.<x> = F[]\n sage: g = x^2 + x+ 1\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: C\n [8, 2] Goppa code over GF(2)\n sage: C.parity_check_matrix()\n [1 0 0 0 0 0 0 1]\n [0 0 1 0 1 1 1 0]\n [0 1 1 1 0 0 1 0]\n [0 1 1 1 1 1 1 1]\n [0 1 0 1 1 0 1 0]\n [0 0 1 1 1 1 0 0]\n ' g = self._generating_pol F = g.base_ring() n = self._length d = g.degree() alpha = F.primitive_element() D = self._defining_set h = [g(D[i]).inverse_of_unit() for i in range(n)] M = _columnize(alpha) for i in range(n): v = _columnize(h[i]) M = M.augment(v) M = M.delete_columns([0]) old = M for t in range(1, d): M = _columnize(alpha) for i in range(n): v = _columnize((h[i] * (D[i] ** t))) M = M.augment(v) M = M.delete_columns([0]) new = M old = old.stack(new) return old def _parity_check_matrix_vandermonde(self): '\n Return a parity check matrix for ``self`` using Vandermonde matrix.\n\n EXAMPLES::\n\n sage: F = GF(2^3)\n sage: R.<x> = F[]\n sage: g = x^2 + x+ 1\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: C\n [8, 2] Goppa code over GF(2)\n sage: C._parity_check_matrix_vandermonde()\n [1 0 0 0 0 0 0 1]\n [0 0 1 0 1 1 1 0]\n [0 1 1 1 0 0 1 0]\n [---------------]\n [0 1 1 1 1 1 1 1]\n [0 1 0 1 1 0 1 0]\n [0 0 1 1 1 1 0 0]\n ' L = self._defining_set g = self._generating_pol t = g.degree() from sage.matrix.constructor import matrix, diagonal_matrix, block_matrix V = matrix.vandermonde(L) V = V.transpose() GL = [g(i) for i in L] GLI = [j.inverse_of_unit() for j in GL] D = diagonal_matrix(GLI) VF = matrix([V.row(i) for i in range(t)]) H = (VF * D) matrices = [matrix([vector(i) for i in H.row(j)]) for j in range(t)] matrices = [m.transpose() for m in matrices] m = block_matrix(t, 1, matrices) return m def distance_bound(self): '\n Return a lower bound for the minimum distance of the code.\n\n Computed using the degree of the generating polynomial of ``self``.\n The minimum distance is guaranteed to be bigger than or equal to this bound.\n\n EXAMPLES::\n\n sage: F = GF(2^3)\n sage: R.<x> = F[]\n sage: g = x^2 + x + 1\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: C\n [8, 2] Goppa code over GF(2)\n sage: C.distance_bound()\n 3\n sage: C.minimum_distance() # needs sage.libs.gap\n 5\n ' return (1 + self._generating_pol.degree())
class GoppaCodeEncoder(Encoder): '\n Encoder for Goppa codes\n\n Encodes words represented as vectors of length `k`, where `k` is\n the dimension of ``self``, with entries from `\\GF{p}`, the prime field of\n the base field of the generating polynomial of ``self``, into codewords\n of length `n`, with entries from `\\GF{p}`.\n\n EXAMPLES::\n\n sage: F = GF(2^3)\n sage: R.<x> = F[]\n sage: g = x^2 + x + 1\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: C\n [8, 2] Goppa code over GF(2)\n sage: E = codes.encoders.GoppaCodeEncoder(C)\n sage: E\n Encoder for [8, 2] Goppa code over GF(2)\n sage: word = vector(GF(2), (0, 1))\n sage: c = E.encode(word)\n sage: c\n (0, 1, 1, 1, 1, 1, 1, 0)\n sage: c in C\n True\n ' def __init__(self, code): '\n Initialize.\n\n TESTS::\n\n sage: F = GF(2^3)\n sage: R.<x> = F[]\n sage: g = x^2 + x + 1\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: E = codes.encoders.GoppaCodeEncoder(C)\n sage: TestSuite(E).run()\n ' super().__init__(code) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(2^3)\n sage: R.<x> = F[]\n sage: g = (x^2 + x + 1)^2\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: E = codes.encoders.GoppaCodeEncoder(C)\n sage: E\n Encoder for [8, 2] Goppa code over GF(2)\n ' return 'Encoder for {}'.format(self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(2^3)\n sage: R.<x> = F[]\n sage: g = (x^2 + x + 1)^2\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: E = codes.encoders.GoppaCodeEncoder(C)\n sage: latex(E)\n \\text{Encoder for }[8, 2]\\text{ Goppa code over }\\Bold{F}_{2}\n ' return '\\text{{Encoder for }}{}'.format(self.code()._latex_()) def __eq__(self, other): '\n Test equality with ``other``\n\n EXAMPLES::\n\n sage: F = GF(2^3)\n sage: R.<x> = F[]\n sage: g = (x^2 + x + 1)^2\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: E1 = codes.encoders.GoppaCodeEncoder(C)\n sage: E2 = codes.encoders.GoppaCodeEncoder(C)\n sage: E1 == E2\n True\n ' return (isinstance(other, GoppaCodeEncoder) and (self.code() == other.code())) def generator_matrix(self): '\n A generator matrix for ``self``\n\n Dimension of resulting matrix is `k \\times n`, where `k` is\n the dimension of ``self`` and `n` is the length of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(2^3)\n sage: R.<x> = F[]\n sage: g = (x^2 + x + 1)^2\n sage: L = [a for a in F.list() if g(a) != 0]\n sage: C = codes.GoppaCode(g, L)\n sage: C\n [8, 2] Goppa code over GF(2)\n sage: C.generator_matrix()\n [1 0 0 1 0 1 1 1]\n [0 1 1 1 1 1 1 0]\n ' c = self.code() pmat = c.parity_check_matrix() aux = codes.from_parity_check_matrix(pmat) return aux.generator_matrix()
class GeneralizedReedSolomonCode(AbstractLinearCode): '\n Representation of a (Generalized) Reed-Solomon code.\n\n INPUT:\n\n - ``evaluation_points`` -- a list of distinct elements of some\n finite field `F`\n\n - ``dimension`` -- the dimension of the resulting code\n\n - ``column_multipliers`` -- (default: ``None``) list of non-zero\n elements of `F`; all column multipliers are set to 1 if default\n value is kept\n\n EXAMPLES:\n\n Often, one constructs a Reed-Solomon code by taking all non-zero elements of\n the field as evaluation points, and specifying no column multipliers (see\n also :func:`ReedSolomonCode` for constructing classical Reed-Solomon codes\n directly)::\n\n sage: F = GF(7)\n sage: evalpts = [F(i) for i in range(1,7)]\n sage: C = codes.GeneralizedReedSolomonCode(evalpts, 3)\n sage: C\n [6, 3, 4] Reed-Solomon Code over GF(7)\n\n More generally, the following is a Reed-Solomon code where the evaluation\n points are a subset of the field and includes zero::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C\n [40, 12, 29] Reed-Solomon Code over GF(59)\n\n It is also possible to specify the column multipliers::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: colmults = F.list()[1:n+1]\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k, colmults)\n sage: C\n [40, 12, 29] Generalized Reed-Solomon Code over GF(59)\n\n SageMath implements efficient decoding algorithms for GRS codes::\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[1:n+1], k)\n sage: r = vector(F, (8, 2, 6, 10, 6, 10, 7, 6, 7, 2))\n sage: C.decode_to_message(r)\n (3, 6, 6, 3, 1)\n\n TESTS:\n\n Test that the bug in :trac:`30045` is fixed::\n\n sage: F = GF(5)\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:5], 2)\n sage: D = codes.decoders.GRSErrorErasureDecoder(C)\n sage: y = (vector(F, [3, 0, 3, 0, 3]), vector(GF(2),[0, 1, 0, 1, 0]))\n sage: D.decode_to_code(y)\n (3, 3, 3, 3, 3)\n sage: D.decode_to_message(y)\n (3, 0)\n ' _registered_encoders = {} _registered_decoders = {} def __init__(self, evaluation_points, dimension, column_multipliers=None): '\n TESTS:\n\n If the evaluation points are not from a finite field, it raises an error::\n\n sage: C = codes.GeneralizedReedSolomonCode([1,2,3], 1)\n Traceback (most recent call last):\n ...\n ValueError: Evaluation points must be in a finite field (and Integer Ring is not one)\n\n If the evaluation points are not from the same finite field, it raises an error::\n\n sage: F2, F3 = GF(2) , GF(3)\n sage: C = codes.GeneralizedReedSolomonCode([F2.zero(),F2.one(),F3(2)], 1)\n Traceback (most recent call last):\n ...\n ValueError: Failed converting all evaluation points to the same field (unable to find a common ring for all elements)\n\n If the column multipliers cannot be converted into the finite are not from a finite field, or cannot be not in the same\n finite field as the evaluation points, it raises an error::\n\n sage: F = GF(59)\n sage: F2 = GF(61)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k, [.3]*n )\n Traceback (most recent call last):\n ...\n ValueError: Failed converting all evaluation points and column multipliers to the same field (unable to find a common ring for all elements)\n\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k, F2.list()[1:n+1])\n Traceback (most recent call last):\n ...\n ValueError: Failed converting all evaluation points and column multipliers to the same field (unable to find a common ring for all elements)\n\n The number of column multipliers is checked as well::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k, F.list()[1:n])\n Traceback (most recent call last):\n ...\n ValueError: There must be the same number of evaluation points as column multipliers\n\n It is not allowed to have 0 as a column multiplier::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k, F.list()[:n])\n Traceback (most recent call last):\n ...\n ValueError: All column multipliers must be non-zero\n\n And all the evaluation points must be different. Note that they should\n be different after converting into the same field::\n\n sage: F = GF(5)\n sage: C = codes.GeneralizedReedSolomonCode([ F(0), 1, 2, 3, 5 ], 3)\n Traceback (most recent call last):\n ...\n ValueError: All evaluation points must be different\n\n The dimension is not allowed to exceed the length::\n\n sage: F = GF(59)\n sage: n, k = 40, 100\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n Traceback (most recent call last):\n ...\n ValueError: The dimension must be a positive integer at most the length of the code.\n ' if column_multipliers: if (len(evaluation_points) != len(column_multipliers)): raise ValueError('There must be the same number of evaluation points as column multipliers') try: common_points = vector((list(evaluation_points) + list(column_multipliers))) F = common_points.base_ring() self._evaluation_points = common_points[:len(evaluation_points)] self._column_multipliers = common_points[len(evaluation_points):] except (TypeError, ValueError) as e: raise ValueError(('Failed converting all evaluation points and column multipliers to the same field (%s)' % e)) else: try: self._evaluation_points = vector(evaluation_points) F = self._evaluation_points.base_ring() self._column_multipliers = vector(F, ([F.one()] * len(self._evaluation_points))) except (TypeError, ValueError) as e: raise ValueError(('Failed converting all evaluation points to the same field (%s)' % e)) if ((not F.is_finite()) or (not F.is_field())): raise ValueError(('Evaluation points must be in a finite field (and %s is not one)' % F)) super().__init__(F, len(self._evaluation_points), 'EvaluationVector', 'Gao') if ((dimension not in ZZ) or (dimension > self._length) or (dimension < 1)): raise ValueError('The dimension must be a positive integer at most the length of the code.') self._dimension = dimension if (F.zero() in self._column_multipliers): raise ValueError('All column multipliers must be non-zero') if (len(self._evaluation_points) != len(set(self._evaluation_points))): raise ValueError('All evaluation points must be different') def __eq__(self, other): '\n Test equality between Generalized Reed-Solomon codes.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C1 = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C2 = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C1 == C2\n True\n ' return (isinstance(other, GeneralizedReedSolomonCode) and (self.base_field() == other.base_field()) and (self.length() == other.length()) and (self.dimension() == other.dimension()) and (self.evaluation_points() == other.evaluation_points()) and (self.column_multipliers() == other.column_multipliers())) def __hash__(self): '\n Return the hash of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C1 = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C2 = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: hash(C1) == hash(C2)\n True\n ' return hash((self.base_field(), self.length(), self.dimension(), tuple(self.evaluation_points()), tuple(self.column_multipliers()))) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C\n [40, 12, 29] Reed-Solomon Code over GF(59)\n sage: colmults = F.list()[1:n+1]\n sage: C2 = codes.GeneralizedReedSolomonCode(F.list()[:n], k, colmults)\n sage: C2\n [40, 12, 29] Generalized Reed-Solomon Code over GF(59)\n ' return ('[%s, %s, %s] %sReed-Solomon Code over GF(%s)' % (self.length(), self.dimension(), self.minimum_distance(), ('Generalized ' if self.is_generalized() else ''), self.base_field().cardinality())) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: latex(C)\n [40, 12, 29] \\textnormal{ Reed-Solomon Code over } \\Bold{F}_{59}\n sage: colmults = F.list()[1:n+1]\n sage: C2 = codes.GeneralizedReedSolomonCode(F.list()[:n], k, colmults)\n sage: latex(C2)\n [40, 12, 29] \\textnormal{ Generalized Reed-Solomon Code over } \\Bold{F}_{59}\n ' return ('[%s, %s, %s] \\textnormal{ %sReed-Solomon Code over } %s' % (self.length(), self.dimension(), self.minimum_distance(), ('Generalized ' if self.is_generalized() else ''), self.base_field()._latex_())) def minimum_distance(self): '\n Return the minimum distance between any two words in ``self``.\n\n Since a GRS code is always Maximum-Distance-Separable (MDS),\n this returns ``C.length() - C.dimension() + 1``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C.minimum_distance()\n 29\n ' return ((self.length() - self.dimension()) + 1) def evaluation_points(self): '\n Return the vector of field elements used for the polynomial evaluations.\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C.evaluation_points()\n (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n ' return self._evaluation_points def column_multipliers(self): '\n Return the vector of column multipliers of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C.column_multipliers()\n (1, 1, 1, 1, 1, 1, 1, 1, 1, 1)\n ' return self._column_multipliers def is_generalized(self): '\n Return whether ``self`` is a Generalized Reed-Solomon code or\n a regular Reed-Solomon code.\n\n ``self`` is a Generalized Reed-Solomon code if its column multipliers\n are not all 1.\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C.column_multipliers()\n (1, 1, 1, 1, 1, 1, 1, 1, 1, 1)\n sage: C.is_generalized()\n False\n sage: colmults = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 1]\n sage: C2 = codes.GeneralizedReedSolomonCode(F.list()[:n], k, colmults)\n sage: C2.is_generalized()\n True\n ' return (not all((beta.is_one() for beta in self.column_multipliers()))) @cached_method def multipliers_product(self): "\n Return the component-wise product of the column multipliers of ``self``\n with the column multipliers of the dual GRS code.\n\n This is a simple Cramer's rule-like expression on the evaluation points\n of ``self``. Recall that the column multipliers of the dual GRS code are\n also the column multipliers of the parity check matrix of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C.multipliers_product()\n [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n " a = self.evaluation_points() one = self.base_ring().one() return [(one / prod(((ai - ah) for (h, ah) in enumerate(a) if (h != i)))) for (i, ai) in enumerate(a)] @cached_method def parity_column_multipliers(self): '\n Return the list of column multipliers of the parity check matrix of\n ``self``. They are also column multipliers of the generator matrix for\n the dual GRS code of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C.parity_column_multipliers()\n [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n ' n = self.length() col_mults = self.column_multipliers() etas = self.multipliers_product() return [(etas[i] / col_mults[i]) for i in range(n)] @cached_method def parity_check_matrix(self): '\n Return the parity check matrix of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C.parity_check_matrix()\n [10 9 8 7 6 5 4 3 2 1]\n [ 0 9 5 10 2 3 2 10 5 9]\n [ 0 9 10 8 8 4 1 4 7 4]\n [ 0 9 9 2 10 9 6 6 1 3]\n [ 0 9 7 6 7 1 3 9 8 5]\n ' return self.dual_code().generator_matrix() @cached_method def dual_code(self): '\n Return the dual code of ``self``, which is also a GRS code.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: colmults = [ F._random_nonzero_element() for i in range(40) ]\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:40], 12, colmults)\n sage: Cd = C.dual_code(); Cd\n [40, 28, 13] Generalized Reed-Solomon Code over GF(59)\n\n The dual code of the dual code is the original code::\n\n sage: C == Cd.dual_code()\n True\n ' col_mults = self.parity_column_multipliers() return GeneralizedReedSolomonCode(self.evaluation_points(), (self.length() - self.dimension()), col_mults) def covering_radius(self): "\n Return the covering radius of ``self``.\n\n The covering radius of a linear code `C` is the smallest\n number `r` s.t. any element of the ambient space of `C` is\n at most at distance `r` to `C`.\n\n As GRS codes are Maximum Distance Separable codes (MDS), their covering\n radius is always `d-1`, where `d` is the minimum distance. This is\n opposed to random linear codes where the covering radius is\n computationally hard to determine.\n\n EXAMPLES::\n\n sage: F = GF(2^8, 'a')\n sage: n, k = 256, 100\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C.covering_radius()\n 156\n " return (self.length() - self.dimension()) @cached_method def weight_distribution(self): "\n Return the list whose `i`'th entry is the number of words of weight `i`\n in ``self``.\n\n Computing the weight distribution for a GRS code is very fast. Note that\n for random linear codes, it is computationally hard.\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: C.weight_distribution() # optional - sage.symbolic\n [1, 0, 0, 0, 0, 0, 2100, 6000, 29250, 61500, 62200]\n\n TESTS:\n\n Test that this method agrees with the generic algorithm::\n\n sage: F = GF(7)\n sage: C = codes.GeneralizedReedSolomonCode(F.list(), 3)\n sage: C.weight_distribution() == super(codes.GeneralizedReedSolomonCode, C).weight_distribution() # long time # optional - sage.symbolic\n True\n sage: F = GF(8)\n sage: C = codes.GeneralizedReedSolomonCode(F.list(), 3)\n sage: C.weight_distribution() == super(codes.GeneralizedReedSolomonCode, C).weight_distribution() # long time # optional - sage.symbolic\n True\n " from sage.symbolic.ring import SR from sage.functions.other import binomial d = self.minimum_distance() n = self.length() q = self.base_ring().order() s = SR.var('s') wd = ([1] + ([0] * (d - 1))) for i in range(d, (n + 1)): tmp = (binomial(n, i) * (q - 1)) wd.append((tmp * symbolic_sum(((binomial((i - 1), s) * ((- 1) ** s)) * (q ** ((i - d) - s))), s, 0, (i - d)))) return wd def _punctured_form(self, points): '\n Return a representation of ``self`` as a\n :class:`GeneralizedReedSolomonCode` punctured in ``points``.\n\n INPUT:\n\n - ``points`` -- a set of positions where to puncture ``self``\n\n EXAMPLES::\n\n sage: C_grs = codes.GeneralizedReedSolomonCode(GF(59).list()[:40], 12)\n sage: C_grs._punctured_form({4, 3})\n [38, 12, 27] Reed-Solomon Code over GF(59)\n ' if (not isinstance(points, (Integer, int, set))): raise TypeError('points must be either a Sage Integer, a Python int, or a set') alphas = list(self.evaluation_points()) col_mults = list(self.column_multipliers()) n = self.length() punctured_alphas = [] punctured_col_mults = [] punctured_alphas = [alphas[i] for i in range(n) if (i not in points)] punctured_col_mults = [col_mults[i] for i in range(n) if (i not in points)] G = self.generator_matrix() G = G.delete_columns(list(points)) dimension = G.rank() return GeneralizedReedSolomonCode(punctured_alphas, dimension, punctured_col_mults)
def ReedSolomonCode(base_field, length, dimension, primitive_root=None): "\n Construct a classical Reed-Solomon code.\n\n A classical `[n,k]` Reed-Solomon code over `\\GF{q}` with `1 \\le k \\le n` and\n `n | (q-1)` is a Reed-Solomon code whose evaluation points are the\n consecutive powers of a primitive `n`'th root of unity `\\alpha`, i.e.\n `\\alpha_i = \\alpha^{i-1}`, where `\\alpha_1, \\ldots, \\alpha_n` are the\n evaluation points. A classical Reed-Solomon codes has all column multipliers\n equal `1`.\n\n Classical Reed-Solomon codes are cyclic, unlike most Generalized\n Reed-Solomon codes.\n\n Use :class:`GeneralizedReedSolomonCode` if you instead wish to construct\n non-classical Reed-Solomon and Generalized Reed-Solomon codes.\n\n INPUT:\n\n - ``base_field`` -- the finite field for which to build the classical\n Reed-Solomon code.\n\n - ``length`` -- the length of the classical Reed-Solomon code. Must divide\n `q-1` where `q` is the cardinality of ``base_field``.\n\n - ``dimension`` -- the dimension of the resulting code.\n\n - ``primitive_root`` -- (default: ``None``) a primitive `n`'th root of unity\n to use for constructing the classical Reed-Solomon code. If not supplied,\n one will be computed and can be recovered as ``C.evaluation_points()[1]``\n where `C` is the code returned by this method.\n\n EXAMPLES::\n\n sage: C = codes.ReedSolomonCode(GF(7), 6, 3); C\n [6, 3, 4] Reed-Solomon Code over GF(7)\n\n This code is cyclic as can be seen by coercing it into a cyclic code::\n\n sage: Ccyc = codes.CyclicCode(code=C); Ccyc\n [6, 3] Cyclic Code over GF(7)\n\n sage: Ccyc.generator_polynomial()\n x^3 + 3*x^2 + x + 6\n\n Another example over an extension field::\n\n sage: C = codes.ReedSolomonCode(GF(64,'a'), 9, 4); C\n [9, 4, 6] Reed-Solomon Code over GF(64)\n\n The primitive `n`'th root of unity can be recovered as the 2nd evaluation point of the code::\n\n sage: alpha = C.evaluation_points()[1]; alpha\n a^5 + a^4 + a^2 + a\n\n We can also supply a different primitive `n`'th root of unity::\n\n sage: beta = alpha^2; beta\n a^4 + a\n sage: beta.multiplicative_order()\n 9\n sage: D = codes.ReedSolomonCode(GF(64), 9, 4, primitive_root=beta); D\n [9, 4, 6] Reed-Solomon Code over GF(64)\n sage: C == D\n False\n " if (not length.divides((base_field.cardinality() - 1))): raise ValueError('A classical Reed-Solomon code has a length which divides the field cardinality minus 1') if (primitive_root is None): g = base_field.multiplicative_generator() primitive_root = (g ** ((base_field.cardinality() - 1) / length)) elif (primitive_root.multiplicative_order() != length): raise ValueError("Supplied primitive_root is not a primitive n'th root of unity") return GeneralizedReedSolomonCode([(primitive_root ** i) for i in range(length)], dimension)
class GRSEvaluationVectorEncoder(Encoder): '\n Encoder for (Generalized) Reed-Solomon codes that encodes vectors\n into codewords.\n\n Let `C` be a GRS code of length `n` and dimension `k` over some\n finite field `F`. We denote by `\\alpha_i` its evaluations points\n and by `\\beta_i` its column multipliers, where `1 \\leq i \\leq n`.\n Let `m = (m_1, \\dots, m_k)`, a vector over `F`, be the message.\n We build a polynomial using the coordinates of `m` as coefficients:\n\n .. MATH::\n\n p = \\Sigma_{i=1}^{m} m_i x^i.\n\n The encoding of `m` will be the following codeword:\n\n .. MATH::\n\n (\\beta_1 p(\\alpha_1), \\dots, \\beta_n p(\\alpha_n)).\n\n INPUT:\n\n - ``code`` -- the associated code of this encoder\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = codes.encoders.GRSEvaluationVectorEncoder(C)\n sage: E\n Evaluation vector-style encoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n\n Actually, we can construct the encoder from ``C`` directly::\n\n sage: E = C.encoder("EvaluationVector")\n sage: E\n Evaluation vector-style encoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n ' def __init__(self, code): '\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = codes.encoders.GRSEvaluationVectorEncoder(C)\n sage: E\n Evaluation vector-style encoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n ' super().__init__(code) def __eq__(self, other): '\n Test equality between GRSEvaluationVectorEncoder objects.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D1 = codes.encoders.GRSEvaluationVectorEncoder(C)\n sage: D2 = codes.encoders.GRSEvaluationVectorEncoder(C)\n sage: D1.__eq__(D2)\n True\n sage: D1 is D2\n False\n ' return (isinstance(other, GRSEvaluationVectorEncoder) and (self.code() == other.code())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = codes.encoders.GRSEvaluationVectorEncoder(C)\n sage: E\n Evaluation vector-style encoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n ' return ('Evaluation vector-style encoder for %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = codes.encoders.GRSEvaluationVectorEncoder(C)\n sage: latex(E)\n \\textnormal{Evaluation vector-style encoder for }[40, 12, 29]\n \\textnormal{ Reed-Solomon Code over } \\Bold{F}_{59}\n ' return ('\\textnormal{Evaluation vector-style encoder for }%s' % self.code()._latex_()) @cached_method def generator_matrix(self): '\n Return a generator matrix of ``self``\n\n Considering a GRS code of length `n`, dimension `k`, with\n evaluation points `(\\alpha_1, \\dots, \\alpha_n)` and column multipliers\n `(\\beta_1, \\dots, \\beta_n)`, its generator matrix `G` is built using\n the following formula:\n\n .. MATH::\n\n G = [g_{i,j}], g_{i,j} = \\beta_j \\alpha_{j}^{i}.\n\n This matrix is a Vandermonde matrix.\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = codes.encoders.GRSEvaluationVectorEncoder(C)\n sage: E.generator_matrix()\n [1 1 1 1 1 1 1 1 1 1]\n [0 1 2 3 4 5 6 7 8 9]\n [0 1 4 9 5 3 3 5 9 4]\n [0 1 8 5 9 4 7 2 6 3]\n [0 1 5 4 3 9 9 3 4 5]\n ' C = self.code() alphas = C.evaluation_points() col_mults = C.column_multipliers() g = matrix(C.base_field(), C.dimension(), C.length(), (lambda i, j: (col_mults[j] * (alphas[j] ** i)))) g.set_immutable() return g
class GRSEvaluationPolynomialEncoder(Encoder): '\n Encoder for (Generalized) Reed-Solomon codes which uses evaluation of\n polynomials to obtain codewords.\n\n Let `C` be a GRS code of length `n` and dimension `k` over some\n finite field `F`. We denote by `\\alpha_i` its evaluations points\n and by `\\beta_i` its column multipliers, where `1 \\leq i \\leq n`.\n Let `p` be a polynomial of degree at most `k-1` in `F[x]` be the message.\n\n The encoding of `m` will be the following codeword:\n\n .. MATH::\n\n (\\beta_1 p(\\alpha_1), \\dots, \\beta_n p(\\alpha_n)).\n\n INPUT:\n\n - ``code`` -- the associated code of this encoder\n\n - ``polynomial_ring`` -- (default: ``None``) a polynomial ring to specify\n the message space of ``self``, if needed; it is set to `F[x]` (where `F`\n is the base field of ``code``) if default value is kept\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = codes.encoders.GRSEvaluationPolynomialEncoder(C)\n sage: E\n Evaluation polynomial-style encoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n sage: E.message_space()\n Univariate Polynomial Ring in x over Finite Field of size 59\n\n Actually, we can construct the encoder from ``C`` directly::\n\n sage: E = C.encoder("EvaluationPolynomial")\n sage: E\n Evaluation polynomial-style encoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n\n We can also specify another polynomial ring::\n\n sage: R = PolynomialRing(F, \'y\')\n sage: E = C.encoder("EvaluationPolynomial", polynomial_ring=R)\n sage: E.message_space()\n Univariate Polynomial Ring in y over Finite Field of size 59\n ' def __init__(self, code, polynomial_ring=None): "\n TESTS:\n\n If ``polynomial_ring`` is not a polynomial ring, an exception\n is raised::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = codes.encoders.GRSEvaluationPolynomialEncoder(C, polynomial_ring = F)\n Traceback (most recent call last):\n ...\n ValueError: polynomial_ring has to be a univariate polynomial ring\n\n Same if ``polynomial_ring`` is a multivariate polynomial ring::\n\n sage: Fxy.<x,y> = F[]\n sage: E = codes.encoders.GRSEvaluationPolynomialEncoder(C, polynomial_ring = Fxy)\n Traceback (most recent call last):\n ...\n ValueError: polynomial_ring has to be a univariate polynomial ring\n\n ``polynomial_ring``'s base field and ``code``'s base field have to be the same::\n\n sage: Gx.<x> = GF(7)[]\n sage: E = codes.encoders.GRSEvaluationPolynomialEncoder(C, polynomial_ring = Gx)\n Traceback (most recent call last):\n ...\n ValueError: polynomial_ring's base field has to be the same as code's\n\n " from sage.rings.polynomial.polynomial_ring import PolynomialRing_commutative super().__init__(code) if (polynomial_ring is None): self._polynomial_ring = code.base_field()['x'] else: if (not isinstance(polynomial_ring, PolynomialRing_commutative)): raise ValueError('polynomial_ring has to be a univariate polynomial ring') elif (not (len(polynomial_ring.variable_names()) == 1)): raise ValueError('polynomial_ring has to be a univariate polynomial ring') if (not (polynomial_ring.base_ring() == code.base_field())): raise ValueError("polynomial_ring's base field has to be the same as code's") self._polynomial_ring = polynomial_ring def __eq__(self, other): "\n Test equality between GRSEvaluationPolynomialEncoder objects.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D1 = codes.encoders.GRSEvaluationPolynomialEncoder(C)\n sage: D2 = codes.encoders.GRSEvaluationPolynomialEncoder(C)\n sage: D1 is D2\n False\n sage: D1.__eq__(D2)\n True\n sage: R = PolynomialRing(F, 'y')\n sage: D3 = codes.encoders.GRSEvaluationPolynomialEncoder(C, polynomial_ring=R)\n sage: D1.__eq__(D3)\n False\n " return (isinstance(other, GRSEvaluationPolynomialEncoder) and (self.code() == other.code()) and (self.polynomial_ring() == other.polynomial_ring())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = C.encoder("EvaluationPolynomial")\n sage: E\n Evaluation polynomial-style encoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n ' return ('Evaluation polynomial-style encoder for %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = C.encoder("EvaluationPolynomial")\n sage: latex(E)\n \\textnormal{Evaluation polynomial-style encoder for }[40, 12, 29]\n \\textnormal{ Reed-Solomon Code over } \\Bold{F}_{59}\n ' return ('\\textnormal{Evaluation polynomial-style encoder for }%s' % self.code()._latex_()) def encode(self, p): '\n Transform the polynomial ``p`` into a codeword of :meth:`code`.\n\n One can use the following shortcut to encode a word with\n an encoder ``E``::\n\n E(word)\n\n INPUT:\n\n - ``p`` -- a polynomial from the message space of ``self`` of degree\n less than ``self.code().dimension()``\n\n OUTPUT:\n\n - a codeword in associated code of ``self``\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: Fx.<x> = F[]\n sage: n, k = 10 , 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = C.encoder("EvaluationPolynomial")\n sage: p = x^2 + 3*x + 10\n sage: c = E.encode(p); c\n (10, 3, 9, 6, 5, 6, 9, 3, 10, 8)\n sage: c in C\n True\n\n If a polynomial of too high degree is given, an error is raised::\n\n sage: p = x^10\n sage: E.encode(p)\n Traceback (most recent call last):\n ...\n ValueError: The polynomial to encode must have degree at most 4\n\n If ``p`` is not an element of the proper polynomial ring, an error is raised::\n\n sage: Qy.<y> = QQ[]\n sage: p = y^2 + 1\n sage: E.encode(p)\n Traceback (most recent call last):\n ...\n ValueError: The value to encode must be in\n Univariate Polynomial Ring in x over Finite Field of size 11\n\n TESTS:\n\n The bug described in :trac:`20744` is now fixed::\n\n sage: F = GF(11)\n sage: Fm.<my_variable> = F[]\n sage: n, k = 10 , 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = C.encoder("EvaluationPolynomial", polynomial_ring = Fm)\n sage: p = my_variable^2 + 3*my_variable + 10\n sage: c = E.encode(p)\n sage: c in C\n True\n ' M = self.message_space() if (p not in M): raise ValueError(('The value to encode must be in %s' % M)) C = self.code() if (p.degree() >= C.dimension()): raise ValueError(('The polynomial to encode must have degree at most %s' % (C.dimension() - 1))) alphas = C.evaluation_points() col_mults = C.column_multipliers() c = vector(C.base_ring(), [(col_mults[i] * p(alphas[i])) for i in range(C.length())]) return c def unencode_nocheck(self, c): '\n Return the message corresponding to the codeword ``c``.\n\n Use this method with caution: it does not check if ``c``\n belongs to the code, and if this is not the case, the output is\n unspecified. Instead, use :meth:`unencode`.\n\n INPUT:\n\n - ``c`` -- a codeword of :meth:`code`\n\n OUTPUT:\n\n - a polynomial of degree less than ``self.code().dimension()``\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10 , 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = C.encoder("EvaluationPolynomial")\n sage: c = vector(F, (10, 3, 9, 6, 5, 6, 9, 3, 10, 8))\n sage: c in C\n True\n sage: p = E.unencode_nocheck(c); p\n x^2 + 3*x + 10\n sage: E.encode(p) == c\n True\n\n Note that no error is thrown if ``c`` is not a codeword, and that the\n result is undefined::\n\n sage: c = vector(F, (11, 3, 9, 6, 5, 6, 9, 3, 10, 8))\n sage: c in C\n False\n sage: p = E.unencode_nocheck(c); p\n 6*x^4 + 6*x^3 + 2*x^2\n sage: E.encode(p) == c\n False\n\n ' C = self.code() alphas = C.evaluation_points() col_mults = C.column_multipliers() c = [(c[i] / col_mults[i]) for i in range(C.length())] points = [(alphas[i], c[i]) for i in range(C.dimension())] Pc = self.polynomial_ring().lagrange_polynomial(points) return Pc def message_space(self): '\n Return the message space of ``self``\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10 , 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: E = C.encoder("EvaluationPolynomial")\n sage: E.message_space()\n Univariate Polynomial Ring in x over Finite Field of size 11\n ' return self._polynomial_ring polynomial_ring = message_space
class GRSBerlekampWelchDecoder(Decoder): '\n Decoder for (Generalized) Reed-Solomon codes which uses Berlekamp-Welch\n decoding algorithm to correct errors in codewords.\n\n This algorithm recovers the error locator polynomial by solving a\n linear system. See [HJ2004]_ pp. 51-52 for details.\n\n INPUT:\n\n - ``code`` -- a code associated to this decoder\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSBerlekampWelchDecoder(C)\n sage: D\n Berlekamp-Welch decoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n\n Actually, we can construct the decoder from ``C`` directly::\n\n sage: D = C.decoder("BerlekampWelch")\n sage: D\n Berlekamp-Welch decoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n ' def __init__(self, code): '\n TESTS:\n\n If ``code`` is not a GRS code, an error is raised::\n\n sage: C = codes.random_linear_code(GF(11), 10, 4)\n sage: codes.decoders.GRSBerlekampWelchDecoder(C)\n Traceback (most recent call last):\n ...\n ValueError: code has to be a generalized Reed-Solomon code\n ' if (not isinstance(code, GeneralizedReedSolomonCode)): raise ValueError('code has to be a generalized Reed-Solomon code') super().__init__(code, code.ambient_space(), 'EvaluationPolynomial') def __eq__(self, other): '\n Test equality between GRSBerlekampWelchDecoder objects.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D1 = codes.decoders.GRSBerlekampWelchDecoder(C)\n sage: D2 = codes.decoders.GRSBerlekampWelchDecoder(C)\n sage: D1.__eq__(D2)\n True\n sage: D1 is D2\n False\n ' return (isinstance(other, GRSBerlekampWelchDecoder) and (self.code() == other.code()) and (self.input_space() == other.input_space())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSBerlekampWelchDecoder(C)\n sage: D\n Berlekamp-Welch decoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n ' return ('Berlekamp-Welch decoder for %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSBerlekampWelchDecoder(C)\n sage: latex(D)\n \\textnormal{Berlekamp Welch decoder for }[40, 12, 29]\n \\textnormal{ Reed-Solomon Code over } \\Bold{F}_{59}\n ' return ('\\textnormal{Berlekamp Welch decoder for }%s' % self.code()._latex_()) def _decode_to_code_and_message(self, r): '\n Decode ``r`` to an element in message space of ``self`` and its\n representation in the ambient space of the code associated to ``self``.\n\n INPUT:\n\n - ``r`` -- a codeword of ``self``\n\n OUTPUT:\n\n - a pair ``(c, f)``, where\n\n * ``c`` is the representation of ``r`` decoded in the ambient\n space of the associated code of ``self``\n * ``f`` its representation in the message space of ``self``\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSBerlekampWelchDecoder(C)\n sage: c = C.random_element()\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(), D.decoding_radius())\n sage: y = Chan(c)\n sage: c_dec, f_dec = D._decode_to_code_and_message(y)\n sage: f_dec == D.connected_encoder().unencode(c)\n True\n sage: c_dec == c\n True\n ' C = self.code() if (r not in C.ambient_space()): raise ValueError('The word to decode has to be in the ambient space of the code') (n, k) = (C.length(), C.dimension()) if (n == k): return (r, self.connected_encoder().unencode_nocheck(r)) if (r in C): return (r, self.connected_encoder().unencode_nocheck(r)) col_mults = C.column_multipliers() r_list = copy(r) r_list = [(r[i] / col_mults[i]) for i in range(0, C.length())] t = ((C.minimum_distance() - 1) // 2) l0 = ((n - 1) - t) l1 = (((n - 1) - t) - (k - 1)) S = matrix(C.base_field(), n, ((l0 + l1) + 2), (lambda i, j: ((C.evaluation_points()[i] ** j) if (j < (l0 + 1)) else (r_list[i] * (C.evaluation_points()[i] ** (j - (l0 + 1))))))) S = S.right_kernel() S = S.basis_matrix().row(0) R = C.base_field()['x'] Q0 = R(S.list_from_positions(range((l0 + 1)))) Q1 = R(S.list_from_positions(range((l0 + 1), ((l0 + l1) + 2)))) (f, rem) = (- Q0).quo_rem(Q1) if (not rem.is_zero()): raise DecodingError('Decoding failed because the number of errors exceeded the decoding radius') if (f not in R): raise DecodingError('Decoding failed because the number of errors exceeded the decoding radius') c = self.connected_encoder().encode(f) if ((c - r).hamming_weight() > self.decoding_radius()): raise DecodingError('Decoding failed because the number of errors exceeded the decoding radius') return (c, f) def decode_to_message(self, r): '\n Decode ``r`` to an element in message space of ``self``.\n\n .. NOTE::\n\n If the code associated to ``self`` has the same length as its\n dimension, ``r`` will be unencoded as is. In that case,\n if ``r`` is not a codeword, the output is unspecified.\n\n INPUT:\n\n - ``r`` -- a codeword of ``self``\n\n OUTPUT:\n\n - a vector of ``self`` message space\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSBerlekampWelchDecoder(C)\n sage: c = C.random_element()\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(),\n ....: D.decoding_radius())\n sage: y = Chan(c)\n sage: D.connected_encoder().unencode(c) == D.decode_to_message(y)\n True\n\n TESTS:\n\n If one tries to decode a word which is too far from any codeword, an exception is raised::\n\n sage: e = vector(F,[0, 0, 54, 23, 1, 0, 0, 0, 53, 21, 0, 0, 0, 34, 6, 11, 0, 0, 16, 0, 0, 0, 9, 0, 10, 27, 35, 0, 0, 0, 0, 46, 0, 0, 0, 0, 0, 0, 44, 0]); e.hamming_weight()\n 15\n sage: D.decode_to_message(c + e)\n Traceback (most recent call last):\n ...\n DecodingError: Decoding failed because the number of errors exceeded the decoding radius\n\n If one tries to decode something which is not in the ambient space of the code,\n an exception is raised::\n\n sage: D.decode_to_message(42)\n Traceback (most recent call last):\n ...\n ValueError: The word to decode has to be in the ambient space of the code\n\n The bug detailed in :trac:`20340` has been fixed::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(59).list()[:40], 12)\n sage: c = C.random_element()\n sage: D = C.decoder("BerlekampWelch")\n sage: E = D.connected_encoder()\n sage: m = E.message_space().random_element()\n sage: c = E.encode(m)\n sage: D.decode_to_message(c) == m\n True\n ' return self._decode_to_code_and_message(r)[1] def decode_to_code(self, r): '\n Correct the errors in ``r`` and returns a codeword.\n\n .. NOTE::\n\n If the code associated to ``self`` has the same length as its\n dimension, ``r`` will be returned as is.\n\n INPUT:\n\n - ``r`` -- a vector of the ambient space of ``self.code()``\n\n OUTPUT:\n\n - a vector of ``self.code()``\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSBerlekampWelchDecoder(C)\n sage: c = C.random_element()\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(),\n ....: D.decoding_radius())\n sage: y = Chan(c)\n sage: c == D.decode_to_code(y)\n True\n\n TESTS:\n\n If one tries to decode a word which is too far from any codeword, an exception is raised::\n\n sage: e = vector(F,[0, 0, 54, 23, 1, 0, 0, 0, 53, 21, 0, 0, 0, 34, 6, 11, 0, 0, 16, 0, 0, 0, 9, 0, 10, 27, 35, 0, 0, 0, 0, 46, 0, 0, 0, 0, 0, 0, 44, 0]); e.hamming_weight()\n 15\n sage: D.decode_to_code(c + e)\n Traceback (most recent call last):\n ...\n DecodingError: Decoding failed because the number of errors exceeded the decoding radius\n\n If one tries to decode something which is not in the ambient space of the code,\n an exception is raised::\n\n sage: D.decode_to_code(42)\n Traceback (most recent call last):\n ...\n ValueError: The word to decode has to be in the ambient space of the code\n\n The bug detailed in :trac:`20340` has been fixed::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(59).list()[:40], 12)\n sage: c = C.random_element()\n sage: D = C.decoder("BerlekampWelch")\n sage: D.decode_to_code(c) == c\n True\n ' return self._decode_to_code_and_message(r)[0] def decoding_radius(self): '\n Return maximal number of errors that ``self`` can decode.\n\n OUTPUT:\n\n - the number of errors as an integer\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSBerlekampWelchDecoder(C)\n sage: D.decoding_radius()\n 14\n ' return ((self.code().minimum_distance() - 1) // 2)
class GRSGaoDecoder(Decoder): '\n Decoder for (Generalized) Reed-Solomon codes which uses Gao\n decoding algorithm to correct errors in codewords.\n\n Gao decoding algorithm uses early terminated extended Euclidean algorithm\n to find the error locator polynomial. See [Ga02]_ for details.\n\n INPUT:\n\n - ``code`` -- the associated code of this decoder\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSGaoDecoder(C)\n sage: D\n Gao decoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n\n Actually, we can construct the decoder from ``C`` directly::\n\n sage: D = C.decoder("Gao")\n sage: D\n Gao decoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n ' def __init__(self, code): '\n TESTS:\n\n If ``code`` is not a GRS code, an error is raised::\n\n sage: C = codes.random_linear_code(GF(11), 10, 4)\n sage: codes.decoders.GRSGaoDecoder(C)\n Traceback (most recent call last):\n ...\n ValueError: code has to be a generalized Reed-Solomon code\n ' if (not isinstance(code, GeneralizedReedSolomonCode)): raise ValueError('code has to be a generalized Reed-Solomon code') super().__init__(code, code.ambient_space(), 'EvaluationPolynomial') def __eq__(self, other): '\n Test equality of GRSGaoDecoder objects.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D1 = codes.decoders.GRSGaoDecoder(C)\n sage: D2 = codes.decoders.GRSGaoDecoder(C)\n sage: D1 == D2\n True\n sage: D1 is D2\n False\n ' return (isinstance(other, GRSGaoDecoder) and (self.code() == other.code()) and (self.input_space() == other.input_space())) def __hash__(self): '\n Return the hash of self.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D1 = codes.decoders.GRSGaoDecoder(C)\n sage: D2 = codes.decoders.GRSGaoDecoder(C)\n sage: hash(D1) == hash(D2)\n True\n ' return hash((self.code(), self.input_space())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSGaoDecoder(C)\n sage: D\n Gao decoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n ' return ('Gao decoder for %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSGaoDecoder(C)\n sage: latex(D)\n \\textnormal{Gao decoder for }[40, 12, 29]\n \\textnormal{ Reed-Solomon Code over } \\Bold{F}_{59}\n ' return ('\\textnormal{Gao decoder for }%s' % self.code()._latex_()) @cached_method def _polynomial_vanishing_at_alphas(self, PolRing): "\n Return the unique minimal-degree polynomial vanishing at all\n the evaluation points.\n\n INPUT:\n\n - ``PolRing`` -- polynomial ring of the output\n\n OUTPUT:\n\n - a polynomial over ``PolRing``\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSGaoDecoder(C)\n sage: P = PolynomialRing(F,'x')\n sage: D._polynomial_vanishing_at_alphas(P)\n x^10 + 10*x^9 + x^8 + 10*x^7 + x^6 + 10*x^5 + x^4 + 10*x^3 + x^2 + 10*x\n " G = PolRing.one() x = PolRing.gen() for i in range(0, self.code().length()): G = (G * (x - self.code().evaluation_points()[i])) return G def _partial_xgcd(self, a, b, PolRing): "\n Performs an Euclidean algorithm on ``a`` and ``b`` until a remainder\n has degree less than `\\frac{n+k}{2}`, `n` being the dimension of the\n code, `k` its dimension, and returns `(r, s)` such that in the step\n just before termination, `r = a s + b t`.\n\n INPUT:\n\n - ``a, b`` -- polynomials over ``PolRing``\n\n - ``PolRing`` -- polynomial ring of the output\n\n OUTPUT:\n\n - a tuple of polynomials\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSGaoDecoder(C)\n sage: P = PolynomialRing(F,'x')\n sage: x = P.parameter()\n sage: a = 5*x^2 + 9*x + 8\n sage: b = 10*x^2 + 3*x + 5\n sage: D._partial_xgcd(a, b, P)\n (10*x^2 + 3*x + 5, 1)\n " stop = ((self.code().dimension() + self.code().length()) // 2) s = PolRing.one() prev_s = PolRing.zero() r = b prev_r = a while (r.degree() >= stop): q = prev_r.quo_rem(r)[0] (prev_r, r) = (r, (prev_r - (q * r))) (prev_s, s) = (s, (prev_s - (q * s))) return (r, s) def _decode_to_code_and_message(self, r): '\n Decode ``r`` to an element in message space of ``self`` and its\n representation in the ambient space of the code associated to ``self``.\n\n INPUT:\n\n - ``r`` -- a codeword of ``self``\n\n OUTPUT:\n\n - ``(c, h)`` -- ``c`` is the representation of ``r`` decoded in the ambient\n space of the associated code of ``self``, ``h`` its representation in\n the message space of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSGaoDecoder(C)\n sage: c = C.random_element()\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(), D.decoding_radius())\n sage: y = Chan(c)\n sage: c_dec, h_dec = D._decode_to_code_and_message(y)\n sage: h_dec == D.connected_encoder().unencode(c)\n True\n sage: c_dec == c\n True\n ' C = self.code() if (r not in C.ambient_space()): raise ValueError('The word to decode has to be in the ambient space of the code') alphas = C.evaluation_points() col_mults = C.column_multipliers() PolRing = C.base_field()['x'] G = self._polynomial_vanishing_at_alphas(PolRing) n = C.length() if ((n == C.dimension()) or (r in C)): return (r, self.connected_encoder().unencode_nocheck(r)) points = [(alphas[i], (r[i] / col_mults[i])) for i in range(0, n)] R = PolRing.lagrange_polynomial(points) (Q1, Q0) = self._partial_xgcd(G, R, PolRing) (h, rem) = Q1.quo_rem(Q0) if (not rem.is_zero()): raise DecodingError('Decoding failed because the number of errors exceeded the decoding radius') if (h not in PolRing): raise DecodingError('Decoding failed because the number of errors exceeded the decoding radius') c = self.connected_encoder().encode(h) if ((c - r).hamming_weight() > self.decoding_radius()): raise DecodingError('Decoding failed because the number of errors exceeded the decoding radius') return (c, h) def decode_to_message(self, r): '\n Decode ``r`` to an element in message space of ``self``.\n\n .. NOTE::\n\n If the code associated to ``self`` has the same length as its\n dimension, ``r`` will be unencoded as is. In that case,\n if ``r`` is not a codeword, the output is unspecified.\n\n INPUT:\n\n - ``r`` -- a codeword of ``self``\n\n OUTPUT:\n\n - a vector of ``self`` message space\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSGaoDecoder(C)\n sage: c = C.random_element()\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(),\n ....: D.decoding_radius())\n sage: y = Chan(c)\n sage: D.connected_encoder().unencode(c) == D.decode_to_message(y)\n True\n\n TESTS:\n\n If one tries to decode a word which is too far from any codeword, an exception is raised::\n\n sage: e = vector(F,[0, 0, 54, 23, 1, 0, 0, 0, 53, 21, 0, 0, 0, 34, 6, 11, 0, 0, 16, 0, 0, 0, 9, 0, 10, 27, 35, 0, 0, 0, 0, 46, 0, 0, 0, 0, 0, 0, 44, 0]); e.hamming_weight()\n 15\n sage: D.decode_to_message(c + e)\n Traceback (most recent call last):\n ...\n DecodingError: Decoding failed because the number of errors exceeded the decoding radius\n\n If one tries to decode something which is not in the ambient space of the code,\n an exception is raised::\n\n sage: D.decode_to_message(42)\n Traceback (most recent call last):\n ...\n ValueError: The word to decode has to be in the ambient space of the code\n\n The bug detailed in :trac:`20340` has been fixed::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(59).list()[:40], 12)\n sage: c = C.random_element()\n sage: D = C.decoder("Gao")\n sage: E = D.connected_encoder()\n sage: m = E.message_space().random_element()\n sage: c = E.encode(m)\n sage: D.decode_to_message(c) == m\n True\n ' return self._decode_to_code_and_message(r)[1] def decode_to_code(self, r): '\n Correct the errors in ``r`` and returns a codeword.\n\n .. NOTE::\n\n If the code associated to ``self`` has the same length as its\n dimension, ``r`` will be returned as is.\n\n INPUT:\n\n - ``r`` -- a vector of the ambient space of ``self.code()``\n\n OUTPUT:\n\n - a vector of ``self.code()``\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSGaoDecoder(C)\n sage: c = C.random_element()\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(),\n ....: D.decoding_radius())\n sage: y = Chan(c)\n sage: c == D.decode_to_code(y)\n True\n\n TESTS:\n\n\n If one tries to decode a word which is too far from any codeword, an exception is raised::\n\n sage: e = vector(F,[0, 0, 54, 23, 1, 0, 0, 0, 53, 21, 0, 0, 0, 34, 6, 11, 0, 0, 16, 0, 0, 0, 9, 0, 10, 27, 35, 0, 0, 0, 0, 46, 0, 0, 0, 0, 0, 0, 44, 0]); e.hamming_weight()\n 15\n sage: D.decode_to_code(c + e)\n Traceback (most recent call last):\n ...\n DecodingError: Decoding failed because the number of errors exceeded the decoding radius\n\n If one tries to decode something which is not in the ambient space of the code,\n an exception is raised::\n\n sage: D.decode_to_code(42)\n Traceback (most recent call last):\n ...\n ValueError: The word to decode has to be in the ambient space of the code\n\n The bug detailed in :trac:`20340` has been fixed::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(59).list()[:40], 12)\n sage: c = C.random_element()\n sage: D = C.decoder("Gao")\n sage: c = C.random_element()\n sage: D.decode_to_code(c) == c\n True\n ' return self._decode_to_code_and_message(r)[0] def decoding_radius(self): '\n Return maximal number of errors that ``self`` can decode\n\n OUTPUT:\n\n - the number of errors as an integer\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSGaoDecoder(C)\n sage: D.decoding_radius()\n 14\n ' return ((self.code().minimum_distance() - 1) // 2)
class GRSErrorErasureDecoder(Decoder): '\n Decoder for (Generalized) Reed-Solomon codes which is able to correct both\n errors and erasures in codewords.\n\n Let `C` be a GRS code of length `n` and dimension `k`.\n Considering `y` a codeword with at most `t` errors\n (`t` being the `\\left\\lfloor \\frac{d-1}{2} \\right\\rfloor`\n decoding radius), and `e` the erasure vector,\n this decoder works as follows:\n\n - Puncture the erased coordinates which are identified in `e`.\n - Create a new GRS code of length `n - w(e)`, where `w` is\n the Hamming weight function, and dimension `k`.\n - Use Gao decoder over this new code one the punctured word built on\n the first step.\n - Recover the original message from the decoded word computed on the\n previous step.\n - Encode this message using an encoder over `C`.\n\n INPUT:\n\n - ``code`` -- the associated code of this decoder\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSErrorErasureDecoder(C)\n sage: D\n Error-Erasure decoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n\n Actually, we can construct the decoder from ``C`` directly::\n\n sage: D = C.decoder("ErrorErasure")\n sage: D\n Error-Erasure decoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n ' def __init__(self, code): '\n TESTS:\n\n If ``code`` is not a GRS code, an error is raised::\n\n sage: C = codes.random_linear_code(GF(11), 10, 4)\n sage: codes.decoders.GRSErrorErasureDecoder(C)\n Traceback (most recent call last):\n ...\n ValueError: code has to be a generalized Reed-Solomon code\n ' if (not isinstance(code, GeneralizedReedSolomonCode)): raise ValueError('code has to be a generalized Reed-Solomon code') input_space = cartesian_product([code.ambient_space(), VectorSpace(GF(2), code.ambient_space().dimension())]) super().__init__(code, input_space, 'EvaluationVector') def __eq__(self, other): '\n Test equality of GRSErrorErasureDecoder objects.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D1 = codes.decoders.GRSErrorErasureDecoder(C)\n sage: D2 = codes.decoders.GRSErrorErasureDecoder(C)\n sage: D1.__eq__(D2)\n True\n sage: D1 is D2\n False\n ' return (isinstance(other, GRSErrorErasureDecoder) and (self.code() == other.code())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSErrorErasureDecoder(C)\n sage: D\n Error-Erasure decoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n ' return ('Error-Erasure decoder for %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSErrorErasureDecoder(C)\n sage: latex(D)\n \\textnormal{Error-Erasure decoder for }[40, 12, 29]\n \\textnormal{ Reed-Solomon Code over } \\Bold{F}_{59}\n ' return ('\\textnormal{Error-Erasure decoder for }%s' % self.code()._latex_()) def decode_to_message(self, word_and_erasure_vector): "\n Decode ``word_and_erasure_vector`` to an element in message space\n of ``self``\n\n INPUT:\n\n - ``word_and_erasure_vector`` -- a tuple whose:\n\n * first element is an element of the ambient space of the code\n * second element is a vector over `\\GF{2}` whose length is the\n same as the code's, containing erasure positions\n\n .. NOTE::\n\n If the code associated to ``self`` has the same length as its\n dimension, ``r`` will be unencoded as is.\n If the number of erasures is exactly `n - k`, where `n` is the\n length of the code associated to ``self`` and `k` its dimension,\n ``r`` will be returned as is.\n In either case, if ``r`` is not a codeword,\n the output is unspecified.\n\n OUTPUT:\n\n - a vector of ``self`` message space\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSErrorErasureDecoder(C)\n sage: c = C.random_element()\n sage: n_era = randint(0, C.minimum_distance() - 2)\n sage: Chan = channels.ErrorErasureChannel(C.ambient_space(),\n ....: D.decoding_radius(n_era), n_era)\n sage: y = Chan(c)\n sage: D.connected_encoder().unencode(c) == D.decode_to_message(y)\n True\n\n TESTS:\n\n If one tries to decode a word with too many erasures, it returns\n an exception::\n\n sage: Chan = channels.ErrorErasureChannel(C.ambient_space(), 0, C.minimum_distance() + 1)\n sage: y = Chan(c)\n sage: D.decode_to_message(y)\n Traceback (most recent call last):\n ...\n DecodingError: Too many erasures in the received word\n\n If one tries to decode something which is not in the ambient space of the code,\n an exception is raised::\n\n sage: D.decode_to_message((42, random_vector(GF(2), C.length())))\n Traceback (most recent call last):\n ...\n ValueError: The word to decode has to be in the ambient space of the code\n\n If one tries to pass an erasure_vector which is not a vector over GF(2) of the same length as code's,\n an exception is raised::\n\n sage: D.decode_to_message((C.random_element(), 42))\n Traceback (most recent call last):\n ...\n ValueError: The erasure vector has to be a vector over GF(2) of the same length as the code\n " C = self.code() (word, erasure_vector) = word_and_erasure_vector (n, k) = (C.length(), C.dimension()) if (word not in C.ambient_space()): raise ValueError('The word to decode has to be in the ambient space of the code') if (erasure_vector not in VectorSpace(GF(2), n)): raise ValueError('The erasure vector has to be a vector over GF(2) of the same length as the code') if (erasure_vector.hamming_weight() >= self.code().minimum_distance()): raise DecodingError('Too many erasures in the received word') punctured_word = vector(self.code().base_ring(), [word[i] for i in range(len(word)) if (not erasure_vector[i])]) C1_length = len(punctured_word) if (C1_length == k): return self.connected_encoder().unencode_nocheck(word) C1_evaluation_points = [self.code().evaluation_points()[i] for i in range(n) if (erasure_vector[i] != 1)] C1_column_multipliers = [self.code().column_multipliers()[i] for i in range(n) if (erasure_vector[i] != 1)] C1 = GeneralizedReedSolomonCode(C1_evaluation_points, k, C1_column_multipliers) return C1.decode_to_message(punctured_word) def decoding_radius(self, number_erasures): '\n Return maximal number of errors that ``self`` can decode according\n to how many erasures it receives.\n\n INPUT:\n\n - ``number_erasures`` -- the number of erasures when we try to decode\n\n OUTPUT:\n\n - the number of errors as an integer\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: D = codes.decoders.GRSErrorErasureDecoder(C)\n sage: D.decoding_radius(5)\n 11\n\n If we receive too many erasures, it returns an exception as codeword will\n be impossible to decode::\n\n sage: D.decoding_radius(30)\n Traceback (most recent call last):\n ...\n ValueError: The number of erasures exceed decoding capability\n ' diff = ((self.code().minimum_distance() - 1) - number_erasures) if (diff <= 0): raise ValueError('The number of erasures exceed decoding capability') else: return (diff // 2)
class GRSKeyEquationSyndromeDecoder(Decoder): '\n Decoder for (Generalized) Reed-Solomon codes which uses a\n Key equation decoding based on the syndrome polynomial to\n correct errors in codewords.\n\n This algorithm uses early terminated extended euclidean algorithm\n to solve the key equations, as described in [Rot2006]_, pp. 183-195.\n\n INPUT:\n\n - ``code`` -- The associated code of this decoder.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[1:n+1], k)\n sage: D = codes.decoders.GRSKeyEquationSyndromeDecoder(C)\n sage: D\n Key equation decoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n\n Actually, we can construct the decoder from ``C`` directly::\n\n sage: D = C.decoder("KeyEquationSyndrome")\n sage: D\n Key equation decoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n ' def __init__(self, code): '\n TESTS::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[:n], k)\n sage: codes.decoders.GRSKeyEquationSyndromeDecoder(C)\n Traceback (most recent call last):\n ...\n ValueError: Impossible to use this decoder over a GRS code which contains 0 amongst its evaluation points\n\n If ``code`` is not a GRS code, an error is raised::\n\n sage: C = codes.random_linear_code(GF(11), 10, 4)\n sage: codes.decoders.GRSKeyEquationSyndromeDecoder(C)\n Traceback (most recent call last):\n ...\n ValueError: code has to be a generalized Reed-Solomon code\n ' if (not isinstance(code, GeneralizedReedSolomonCode)): raise ValueError('code has to be a generalized Reed-Solomon code') if (code.base_field().zero() in code.evaluation_points()): raise ValueError('Impossible to use this decoder over a GRS code which contains 0 amongst its evaluation points') super().__init__(code, code.ambient_space(), 'EvaluationVector') def __eq__(self, other): '\n Test equality of GRSKeyEquationSyndromeDecoder objects.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[1:n+1], k)\n sage: D1 = codes.decoders.GRSKeyEquationSyndromeDecoder(C)\n sage: D2 = codes.decoders.GRSKeyEquationSyndromeDecoder(C)\n sage: D1.__eq__(D2)\n True\n sage: D1 is D2\n False\n ' return (isinstance(other, GRSKeyEquationSyndromeDecoder) and (self.code() == other.code()) and (self.input_space() == other.input_space())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[1:n+1], k)\n sage: D = codes.decoders.GRSKeyEquationSyndromeDecoder(C)\n sage: D\n Key equation decoder for [40, 12, 29] Reed-Solomon Code over GF(59)\n ' return ('Key equation decoder for %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[1:n+1], k)\n sage: D = codes.decoders.GRSKeyEquationSyndromeDecoder(C)\n sage: latex(D)\n \\textnormal{Key equation decoder for }[40, 12, 29]\n \\textnormal{ Reed-Solomon Code over } \\Bold{F}_{59}\n ' return ('\\textnormal{Key equation decoder for }%s' % self.code()._latex_()) def _partial_xgcd(self, a, b, PolRing): "\n Performs an Euclidean algorithm on ``a`` and ``b`` until a remainder\n has degree less than `\\frac{n+k}{2}`, `n` being the dimension of the\n code, `k` its dimension, and returns `(r, t)` such that in the step\n just before termination, `r = a s + b t`.\n\n INPUT:\n\n - ``a, b`` -- polynomials over ``PolRing``\n\n - ``PolRing`` -- polynomial ring of the output\n\n OUTPUT:\n\n - a tuple of polynomials\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[1:n+1], k)\n sage: D = codes.decoders.GRSKeyEquationSyndromeDecoder(C)\n sage: P = PolynomialRing(F,'x')\n sage: x = P.parameter()\n sage: a = 5*x^2 + 9*x + 8\n sage: b = 10*x^2 + 3*x + 5\n sage: D._partial_xgcd(a, b, P)\n (5, 8*x + 10)\n " prev_t = PolRing.zero() t = PolRing.one() prev_r = a r = b while (r.degree() >= t.degree()): q = prev_r.quo_rem(r)[0] (prev_r, r) = (r, (prev_r - (q * r))) (prev_t, t) = (t, (prev_t - (q * t))) return (r, t) def _syndrome(self, r): '\n Return the coefficients of the syndrome polynomial of ``r``.\n\n INPUT:\n\n - ``r`` -- a vector of the ambient space of ``self.code()``\n\n OUTPUT:\n\n - a list\n\n EXAMPLES::\n\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[1:n+1], k)\n sage: D = codes.decoders.GRSKeyEquationSyndromeDecoder(C)\n sage: r = vector(F, (8, 2, 6, 10, 6, 10, 7, 6, 7, 2))\n sage: D._syndrome(r)\n [1, 10, 1, 10, 1]\n ' C = self.code() F = C.base_ring() S = [] col_mults = C.parity_column_multipliers() alphas = C.evaluation_points() for l in range((C.minimum_distance() - 1)): Sl = F.zero() for j in range(C.length()): Sl += ((r[j] * col_mults[j]) * (alphas[j] ** l)) S.append(Sl) return S def _forney_formula(self, error_evaluator, error_locator): "\n Return the error vector computed through Forney's formula.\n\n INPUT:\n\n - ``error_evaluator``, ``error_locator`` -- two polynomials\n\n OUTPUT:\n\n - a vector\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: n, k = 10, 5\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[1:n+1], k)\n sage: D = codes.decoders.GRSKeyEquationSyndromeDecoder(C)\n sage: R.<x> = F[]\n sage: evaluator, locator = R(10), R([10, 10])\n sage: D._forney_formula(evaluator, locator)\n (0, 0, 0, 0, 0, 0, 0, 0, 0, 1)\n " C = self.code() alphas = C.evaluation_points() col_mults = C.parity_column_multipliers() ELPp = error_locator.derivative() F = C.base_ring() (zero, one) = (F.zero(), F.one()) e = [] for i in range(C.length()): alpha_inv = (one / alphas[i]) if (error_locator(alpha_inv) == zero): e.append(((((- alphas[i]) / col_mults[i]) * error_evaluator(alpha_inv)) / ELPp(alpha_inv))) else: e.append(zero) return vector(F, e) def decode_to_code(self, r): '\n Correct the errors in ``r`` and returns a codeword.\n\n .. NOTE::\n\n If the code associated to ``self`` has the same length as its\n dimension, ``r`` will be returned as is.\n\n INPUT:\n\n - ``r`` -- a vector of the ambient space of ``self.code()``\n\n OUTPUT:\n\n - a vector of ``self.code()``\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[1:n+1], k)\n sage: D = codes.decoders.GRSKeyEquationSyndromeDecoder(C)\n sage: c = C.random_element()\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(),\n ....: D.decoding_radius())\n sage: y = Chan(c)\n sage: c == D.decode_to_code(y)\n True\n\n TESTS:\n\n If one tries to decode a word with too many errors, it returns\n an exception::\n\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(), D.decoding_radius()+1)\n sage: while True:\n ....: try:\n ....: y = Chan(c)\n ....: D.decode_to_message(y)\n ....: except ZeroDivisionError:\n ....: pass\n Traceback (most recent call last):\n ...\n DecodingError: Decoding failed because the number of errors exceeded the decoding radius\n\n If one tries to decode something which is not in the ambient space of the code,\n an exception is raised::\n\n sage: D.decode_to_code(42)\n Traceback (most recent call last):\n ...\n ValueError: The word to decode has to be in the ambient space of the code\n ' C = self.code() if (r not in C.ambient_space()): raise ValueError('The word to decode has to be in the ambient space of the code') PolRing = C.base_field()['x'] x = PolRing.gen() if ((C.length() == C.dimension()) or (r in C)): return r S = PolRing(self._syndrome(r)) a = (x ** (C.minimum_distance() - 1)) (EEP, ELP) = self._partial_xgcd(a, S, PolRing) e = self._forney_formula(EEP, ELP) dec = (r - e) if (dec not in C): raise DecodingError('Decoding failed because the number of errors exceeded the decoding radius') return dec def decode_to_message(self, r): '\n Decode ``r`` to an element in message space of ``self``\n\n .. NOTE::\n\n If the code associated to ``self`` has the same length as its\n dimension, ``r`` will be unencoded as is. In that case,\n if ``r`` is not a codeword, the output is unspecified.\n\n INPUT:\n\n - ``r`` -- a codeword of ``self``\n\n OUTPUT:\n\n - a vector of ``self`` message space\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[1:n+1], k)\n sage: D = codes.decoders.GRSKeyEquationSyndromeDecoder(C)\n sage: c = C.random_element()\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(),\n ....: D.decoding_radius())\n sage: y = Chan(c)\n sage: D.connected_encoder().unencode(c) == D.decode_to_message(y)\n True\n ' C = self.code() if (C.length() == C.dimension()): return self.connected_encoder().unencode_nocheck(r) return super().decode_to_message(r) def decoding_radius(self): '\n Return maximal number of errors that ``self`` can decode\n\n OUTPUT:\n\n - the number of errors as an integer\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: n, k = 40, 12\n sage: C = codes.GeneralizedReedSolomonCode(F.list()[1:n+1], k)\n sage: D = codes.decoders.GRSKeyEquationSyndromeDecoder(C)\n sage: D.decoding_radius()\n 14\n ' return ((self.code().minimum_distance() - 1) // 2)
def QuasiQuadraticResidueCode(p): '\n A (binary) quasi-quadratic residue code (or QQR code).\n\n Follows the definition of Proposition 2.2 in [BM2003]_. The code has a generator\n matrix in the block form `G=(Q,N)`. Here `Q` is a `p \\times p` circulant\n matrix whose top row is `(0,x_1,...,x_{p-1})`, where `x_i=1` if and only if\n `i` is a quadratic residue mod `p`, and `N` is a `p \\times p` circulant\n matrix whose top row is `(0,y_1,...,y_{p-1})`, where `x_i+y_i=1` for all\n `i`.\n\n INPUT:\n\n - ``p`` -- a prime `>2`.\n\n OUTPUT:\n\n Returns a QQR code of length `2p`.\n\n EXAMPLES::\n\n sage: C = codes.QuasiQuadraticResidueCode(11); C # optional - gap_package_guava\n [22, 11] linear code over GF(2)\n\n These are self-orthogonal in general and self-dual when `p \\equiv 3 \\pmod 4`.\n\n AUTHOR: David Joyner (11-2005)\n ' GapPackage('guava', spkg='gap_packages').require() libgap.load_package('guava') C = libgap.QQRCode(p) G = C.GeneratorMat() MS = MatrixSpace(GF(2), len(G), len(G[0])) return LinearCode(MS(G))
def RandomLinearCodeGuava(n, k, F): '\n The method used is to first construct a `k \\times n` matrix of the block\n form `(I,A)`, where `I` is a `k \\times k` identity matrix and `A` is a\n `k \\times (n-k)` matrix constructed using random elements of `F`. Then\n the columns are permuted using a randomly selected element of the symmetric\n group `S_n`.\n\n INPUT:\n\n - ``n,k`` -- integers with `n>k>1`.\n\n OUTPUT:\n\n Returns a "random" linear code with length `n`, dimension `k` over field `F`.\n\n EXAMPLES::\n\n sage: C = codes.RandomLinearCodeGuava(30,15,GF(2)); C # optional - gap_package_guava\n [30, 15] linear code over GF(2)\n sage: C = codes.RandomLinearCodeGuava(10,5,GF(4,\'a\')); C # optional - gap_package_guava\n [10, 5] linear code over GF(4)\n\n AUTHOR: David Joyner (11-2005)\n ' current_randstate().set_seed_gap() GapPackage('guava', spkg='gap_packages').require() libgap.load_package('guava') C = libgap.RandomLinearCode(n, k, F) G = C.GeneratorMat() MS = MatrixSpace(F, len(G), len(G[0])) return LinearCode(MS(G))
def n_k_params(C, n_k): '\n Internal helper function for the :class:`GRSGuruswamiSudanDecoder` class for\n allowing to specify either a GRS code `C` or the length and dimensions `n,\n k` directly, in all the static functions.\n\n If neither `C` or `n,k` were specified to those functions, an appropriate\n error should be raised. Otherwise, `n, k` of the code or the supplied tuple\n directly is returned.\n\n INPUT:\n\n - ``C`` -- A GRS code or ``None``\n\n - ``n_k`` -- A tuple `(n,k)` being length and dimension of a GRS code, or\n ``None``.\n\n OUTPUT:\n\n - ``n_k`` -- A tuple `(n,k)` being length and dimension of a GRS code.\n\n EXAMPLES::\n\n sage: from sage.coding.guruswami_sudan.gs_decoder import n_k_params\n sage: n_k_params(None, (10, 5))\n (10, 5)\n sage: C = codes.GeneralizedReedSolomonCode(GF(11).list()[:10], 5)\n sage: n_k_params(C, None)\n (10, 5)\n sage: n_k_params(None,None)\n Traceback (most recent call last):\n ...\n ValueError: Please provide either the code or its length and dimension\n sage: n_k_params(C, (12, 2))\n Traceback (most recent call last):\n ...\n ValueError: Please provide only the code or its length and dimension\n ' if ((C is not None) and (n_k is not None)): raise ValueError('Please provide only the code or its length and dimension') elif ((C is None) and (n_k is None)): raise ValueError('Please provide either the code or its length and dimension') elif (C is not None): return (C.length(), C.dimension()) elif ((n_k is not None) and (not isinstance(n_k, tuple))): raise ValueError('n_k has to be a tuple') elif (n_k is not None): return n_k
def roth_ruckenstein_root_finder(p, maxd=None, precision=None): '\n Wrapper for Roth-Ruckenstein algorithm to compute the roots of a polynomial\n with coefficients in `F[x]`.\n\n TESTS::\n\n sage: from sage.coding.guruswami_sudan.gs_decoder import roth_ruckenstein_root_finder\n sage: R.<x> = GF(13)[]\n sage: S.<y> = R[]\n sage: p = (y - x^2 - x - 1) * (y + x + 1)\n sage: roth_ruckenstein_root_finder(p, maxd = 2)\n [12*x + 12, x^2 + x + 1]\n ' gens = p.parent().gens() if (len(gens) == 2): p = p.polynomial(gens[1]) return p.roots(multiplicities=False, degree_bound=maxd, algorithm='Roth-Ruckenstein')
def alekhnovich_root_finder(p, maxd=None, precision=None): "\n Wrapper for Alekhnovich's algorithm to compute the roots of a polynomial\n with coefficients in `F[x]`.\n\n TESTS::\n\n sage: from sage.coding.guruswami_sudan.gs_decoder import alekhnovich_root_finder\n sage: R.<x> = GF(13)[]\n sage: S.<y> = R[]\n sage: p = (y - x^2 - x - 1) * (y + x + 1)\n sage: alekhnovich_root_finder(p, maxd = 2)\n [12*x + 12, x^2 + x + 1]\n " gens = p.parent().gens() if (len(gens) == 2): p = p.polynomial(gens[1]) return p.roots(multiplicities=False, degree_bound=maxd, algorithm='Alekhnovich')
class GRSGuruswamiSudanDecoder(Decoder): '\n The Guruswami-Sudan list-decoding algorithm for decoding Generalized\n Reed-Solomon codes.\n\n The Guruswami-Sudan algorithm is a polynomial time algorithm to decode\n beyond half the minimum distance of the code. It can decode up to the\n Johnson radius which is `n - \\sqrt(n(n-d))`, where `n, d` is the length,\n respectively minimum distance of the RS code. See [GS1999]_ for more details.\n It is a list-decoder meaning that it returns a list of all closest codewords\n or their corresponding message polynomials. Note that the output of the\n ``decode_to_code`` and ``decode_to_message`` methods are therefore lists.\n\n The algorithm has two free parameters, the list size and the multiplicity,\n and these determine how many errors the method will correct: generally,\n higher decoding radius requires larger values of these parameters. To decode\n all the way to the Johnson radius, one generally needs values in the order\n of `O(n^2)`, while decoding just one error less requires just `O(n)`.\n\n This class has static methods for computing choices of parameters given the\n decoding radius or vice versa.\n\n The Guruswami-Sudan consists of two computationally intensive steps:\n Interpolation and Root finding, either of which can be completed in multiple\n ways. This implementation allows choosing the sub-algorithms among currently\n implemented possibilities, or supplying your own.\n\n INPUT:\n\n - ``code`` -- A code associated to this decoder.\n\n - ``tau`` -- (default: ``None``) an integer, the number of errors one wants the\n Guruswami-Sudan algorithm to correct.\n\n - ``parameters`` -- (default: ``None``) a pair of integers, where:\n\n - the first integer is the multiplicity parameter, and\n - the second integer is the list size parameter.\n\n - ``interpolation_alg`` -- (default: ``None``) the interpolation algorithm\n that will be used. The following possibilities are currently available:\n\n * ``"LinearAlgebra"`` -- uses a linear system solver.\n * ``"LeeOSullivan"`` -- uses Lee O\'Sullivan method based on row reduction\n of a matrix\n * ``None`` -- one of the above will be chosen based on the size of the\n code and the parameters.\n\n You can also supply your own function to perform the interpolation. See\n NOTE section for details on the signature of this function.\n\n - ``root_finder`` -- (default: ``None``) the rootfinding algorithm that will\n be used. The following possibilities are currently available:\n\n * ``"Alekhnovich"`` -- uses Alekhnovich\'s algorithm.\n\n * ``"RothRuckenstein"`` -- uses Roth-Ruckenstein algorithm.\n\n * ``None`` -- one of the above will be chosen based on the size of the\n code and the parameters.\n\n You can also supply your own function to perform the interpolation. See\n NOTE section for details on the signature of this function.\n\n .. NOTE::\n\n One has to provide either ``tau`` or ``parameters``. If neither are given,\n an exception will be raised.\n\n If one provides a function as ``root_finder``, its signature has to be:\n ``my_rootfinder(Q, maxd=default_value, precision=default_value)``. `Q`\n will be given as an element of `F[x][y]`. The function must return the\n roots as a list of polynomials over a univariate polynomial ring. See\n :meth:`roth_ruckenstein_root_finder` for an example.\n\n If one provides a function as ``interpolation_alg``, its signature has\n to be: ``my_inter(interpolation_points, tau, s_and_l, wy)``. See\n :meth:`sage.coding.guruswami_sudan.interpolation.gs_interpolation_linalg`\n for an example.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = codes.decoders.GRSGuruswamiSudanDecoder(C, tau=97); D\n Guruswami-Sudan decoder for [250, 70, 181] Reed-Solomon Code over GF(251)\n decoding 97 errors with parameters (1, 2)\n\n One can specify multiplicity and list size instead of ``tau``::\n\n sage: D = codes.decoders.GRSGuruswamiSudanDecoder(C, parameters=(1,2)); D\n Guruswami-Sudan decoder for [250, 70, 181] Reed-Solomon Code over GF(251)\n decoding 97 errors with parameters (1, 2)\n\n One can pass a method as ``root_finder`` (works also for ``interpolation_alg``)::\n\n sage: from sage.coding.guruswami_sudan.gs_decoder import roth_ruckenstein_root_finder\n sage: rf = roth_ruckenstein_root_finder\n sage: D = codes.decoders.GRSGuruswamiSudanDecoder(C, parameters=(1,2),\n ....: root_finder=rf); D\n Guruswami-Sudan decoder for [250, 70, 181] Reed-Solomon Code over GF(251)\n decoding 97 errors with parameters (1, 2)\n\n If one wants to use the native Sage algorithms for the root finding step,\n one can directly pass the string given in the ``Input`` block of this class.\n This works for ``interpolation_alg`` as well::\n\n\n sage: D = codes.decoders.GRSGuruswamiSudanDecoder(C, parameters=(1,2),\n ....: root_finder="RothRuckenstein"); D\n Guruswami-Sudan decoder for [250, 70, 181] Reed-Solomon Code over GF(251)\n decoding 97 errors with parameters (1, 2)\n\n Actually, we can construct the decoder from ``C`` directly::\n\n sage: D = C.decoder("GuruswamiSudan", tau=97); D\n Guruswami-Sudan decoder for [250, 70, 181] Reed-Solomon Code over GF(251)\n decoding 97 errors with parameters (1, 2)\n ' @staticmethod def parameters_given_tau(tau, C=None, n_k=None): '\n Return the smallest possible multiplicity and list size given the\n given parameters of the code and decoding radius.\n\n INPUT:\n\n - ``tau`` -- an integer, number of errors one wants the Guruswami-Sudan\n algorithm to correct\n - ``C`` -- (default: ``None``) a :class:`GeneralizedReedSolomonCode`\n - ``n_k`` -- (default: ``None``) a pair of integers, respectively the\n length and the dimension of the :class:`GeneralizedReedSolomonCode`\n\n OUTPUT:\n\n - ``(s, l)`` -- a pair of integers, where:\n\n - ``s`` is the multiplicity parameter, and\n - ``l`` is the list size parameter.\n\n .. NOTE::\n\n One should to provide either ``C`` or ``(n, k)``. If neither or both\n are given, an exception will be raised.\n\n EXAMPLES::\n\n sage: GSD = codes.decoders.GRSGuruswamiSudanDecoder\n sage: tau, n, k = 97, 250, 70\n sage: GSD.parameters_given_tau(tau, n_k=(n, k))\n (1, 2)\n\n Another example with a bigger decoding radius::\n\n sage: tau, n, k = 118, 250, 70\n sage: GSD.parameters_given_tau(tau, n_k=(n, k))\n (47, 89)\n\n Choosing a decoding radius which is too large results in an errors::\n\n sage: tau = 200\n sage: GSD.parameters_given_tau(tau, n_k=(n, k))\n Traceback (most recent call last):\n ...\n ValueError: The decoding radius must be less than\n the Johnson radius (which is 118.66)\n ' (n, k) = n_k_params(C, n_k) johnson = johnson_radius(n, ((n - k) + 1)) if (tau >= johnson): raise ValueError(('The decoding radius must be less than the Johnson radius (which is %.2f)' % float(johnson))) def try_l(l): (mins, maxs) = solve_degree2_to_integer_range(n, (n - ((2 * (l + 1)) * (n - tau))), (((k - 1) * l) * (l + 1))) if ((maxs > 0) and (maxs >= mins)): return max(1, mins) else: return None (s, l) = (None, 0) while (s is None): l += 1 s = try_l(l) return (s, l) @staticmethod def guruswami_sudan_decoding_radius(C=None, n_k=None, l=None, s=None): '\n Return the maximal decoding radius of the Guruswami-Sudan decoder and\n the parameter choices needed for this.\n\n If ``s`` is set but ``l`` is not it will return the best decoding radius using this ``s``\n alongside with the required ``l``. Vice versa for ``l``. If both are\n set, it returns the decoding radius given this parameter choice.\n\n INPUT:\n\n - ``C`` -- (default: ``None``) a :class:`GeneralizedReedSolomonCode`\n - ``n_k`` -- (default: ``None``) a pair of integers, respectively the\n length and the dimension of the :class:`GeneralizedReedSolomonCode`\n - ``s`` -- (default: ``None``) an integer, the multiplicity parameter of Guruswami-Sudan algorithm\n - ``l`` -- (default: ``None``) an integer, the list size parameter\n\n .. NOTE::\n\n One has to provide either ``C`` or ``n_k``. If none or both are\n given, an exception will be raised.\n\n OUTPUT:\n\n - ``(tau, (s, l))`` -- where\n\n - ``tau`` is the obtained decoding radius, and\n\n - ``s, ell`` are the multiplicity parameter, respectively list size\n parameter giving this radius.\n\n EXAMPLES::\n\n sage: GSD = codes.decoders.GRSGuruswamiSudanDecoder\n sage: n, k = 250, 70\n sage: GSD.guruswami_sudan_decoding_radius(n_k=(n, k))\n (118, (47, 89))\n\n One parameter can be restricted at a time::\n\n sage: n, k = 250, 70\n sage: GSD.guruswami_sudan_decoding_radius(n_k=(n, k), s=3)\n (109, (3, 5))\n sage: GSD.guruswami_sudan_decoding_radius(n_k=(n, k), l=7)\n (111, (4, 7))\n\n The function can also just compute the decoding radius given the parameters::\n\n sage: GSD.guruswami_sudan_decoding_radius(n_k=(n, k), s=2, l=6)\n (92, (2, 6))\n ' (n, k) = n_k_params(C, n_k) def get_tau(s, l): 'Return the decoding radius given this s and l' if ((s <= 0) or (l <= 0)): return (- 1) return gilt(((n - (((n / 2) * (s + 1)) / (l + 1))) - ((((k - 1) / 2) * l) / s))) if ((l is None) and (s is None)): tau = gilt(johnson_radius(n, ((n - k) + 1))) return (tau, GRSGuruswamiSudanDecoder.parameters_given_tau(tau, n_k=(n, k))) if ((l is not None) and (s is not None)): return (get_tau(s, l), (s, l)) def find_integral_max(real_max, f): 'Given a real (local) maximum of a function `f`, return that of\n the integers around `real_max` which gives the (local) integral\n maximum, and the value of at that point.' if (real_max in ZZ): int_max = ZZ(real_max) return (int_max, f(int_max)) else: x_f = floor(real_max) x_c = (x_f + 1) (f_f, f_c) = (f(x_f), f(x_c)) return ((x_f, f_f) if (f_f >= f_c) else (x_c, f_c)) if (s is not None): lmax = (sqrt((((n * s) * (s + 1.0)) / (k - 1.0))) - 1.0) (l, tau) = find_integral_max(lmax, (lambda l: get_tau(s, l))) return (tau, (s, l)) if (l is not None): smax = sqrt(((((k - 1.0) / n) * l) * (l + 1.0))) (s, tau) = find_integral_max(smax, (lambda s: get_tau(s, l))) return (tau, (s, l)) @staticmethod def _suitable_parameters_given_tau(tau, C=None, n_k=None): '\n Return quite good multiplicity and list size parameters for the code\n parameters and the decoding radius.\n\n These parameters are not guaranteed to be the best ones possible\n for the provided ``tau``, but arise from easily-evaluated closed\n expressions and are very good approximations of the best ones.\n\n See [Nie2013]_ pages 53-54, proposition 3.11 for details.\n\n INPUT:\n\n - ``tau`` -- an integer, number of errors one wants the Guruswami-Sudan\n algorithm to correct\n - ``C`` -- (default: ``None``) a :class:`GeneralizedReedSolomonCode`\n - ``n_k`` -- (default: ``None``) a pair of integers, respectively the\n length and the dimension of the :class:`GeneralizedReedSolomonCode`\n\n OUTPUT:\n\n - ``(s, l)`` -- a pair of integers, where:\n\n - ``s`` is the multiplicity parameter, and\n - ``l`` is the list size parameter.\n\n .. NOTE::\n\n One has to provide either ``C`` or ``(n, k)``. If neither or both\n are given, an exception will be raised.\n\n EXAMPLES:\n\n\n The following is an example where the parameters are optimal::\n\n sage: GSD = codes.decoders.GRSGuruswamiSudanDecoder\n sage: tau = 98\n sage: n, k = 250, 70\n sage: GSD._suitable_parameters_given_tau(tau, n_k=(n, k))\n (2, 3)\n sage: GSD.parameters_given_tau(tau, n_k=(n, k))\n (2, 3)\n\n This is an example where they are not::\n\n sage: tau = 97\n sage: n, k = 250, 70\n sage: GSD._suitable_parameters_given_tau(tau, n_k=(n, k))\n (2, 3)\n sage: GSD.parameters_given_tau(tau, n_k=(n, k))\n (1, 2)\n\n We can provide a GRS code instead of `n` and `k` directly::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: GSD._suitable_parameters_given_tau(tau, C=C)\n (2, 3)\n\n Another one with a bigger ``tau``::\n\n sage: GSD._suitable_parameters_given_tau(118, C=C)\n (47, 89)\n ' (n, k) = n_k_params(C, n_k) w = (k - 1) atau = (n - tau) smin = ((tau * w) / ((atau ** 2) - (n * w))) s = floor((1 + smin)) D = ((((s - smin) * ((atau ** 2) - (n * w))) * s) + ((w ** 2) / 4)) l = floor(((((atau / w) * s) + 0.5) - (sqrt(D) / w))) return (s, l) @staticmethod def gs_satisfactory(tau, s, l, C=None, n_k=None): '\n Return whether input parameters satisfy the governing equation of\n Guruswami-Sudan.\n\n See [Nie2013]_ page 49, definition 3.3 and proposition 3.4 for details.\n\n INPUT:\n\n - ``tau`` -- an integer, number of errors one expects Guruswami-Sudan algorithm\n to correct\n - ``s`` -- an integer, multiplicity parameter of Guruswami-Sudan algorithm\n - ``l`` -- an integer, list size parameter\n - ``C`` -- (default: ``None``) a :class:`GeneralizedReedSolomonCode`\n - ``n_k`` -- (default: ``None``) a tuple of integers, respectively the\n length and the dimension of the :class:`GeneralizedReedSolomonCode`\n\n .. NOTE::\n\n One has to provide either ``C`` or ``(n, k)``. If none or both are\n given, an exception will be raised.\n\n EXAMPLES::\n\n sage: GSD = codes.decoders.GRSGuruswamiSudanDecoder\n sage: tau, s, l = 97, 1, 2\n sage: n, k = 250, 70\n sage: GSD.gs_satisfactory(tau, s, l, n_k=(n, k))\n True\n\n One can also pass a GRS code::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: GSD.gs_satisfactory(tau, s, l, C=C)\n True\n\n Another example where ``s`` and ``l`` does not satisfy the equation::\n\n sage: tau, s, l = 118, 47, 80\n sage: GSD.gs_satisfactory(tau, s, l, n_k=(n, k))\n False\n\n If one provides both ``C`` and ``n_k`` an exception is returned::\n\n sage: tau, s, l = 97, 1, 2\n sage: n, k = 250, 70\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: GSD.gs_satisfactory(tau, s, l, C=C, n_k=(n, k))\n Traceback (most recent call last):\n ...\n ValueError: Please provide only the code or its length and dimension\n\n Same if one provides none of these::\n\n sage: GSD.gs_satisfactory(tau, s, l)\n Traceback (most recent call last):\n ...\n ValueError: Please provide either the code or its length and dimension\n ' (n, k) = n_k_params(C, n_k) return ((l > 0) and (s > 0) and (((n * s) * (s + 1)) < ((l + 1) * (((2 * s) * (n - tau)) - ((k - 1) * l))))) def __init__(self, code, tau=None, parameters=None, interpolation_alg=None, root_finder=None): '\n TESTS:\n\n If neither ``tau`` nor ``parameters`` is given, an exception is returned::\n\n sage: GSD = codes.decoders.GRSGuruswamiSudanDecoder\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = GSD(C)\n Traceback (most recent call last):\n ...\n ValueError: Specify either tau or parameters\n\n If one provides something else than one of the allowed strings or a method as ``interpolation_alg``,\n an exception is returned::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = GSD(C, tau=97, interpolation_alg=42)\n Traceback (most recent call last):\n ...\n ValueError: Please provide a method or one of the allowed strings for interpolation_alg\n\n Same thing for ``root_finder``::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = GSD(C, tau=97, root_finder="FortyTwo")\n Traceback (most recent call last):\n ...\n ValueError: Please provide a method or one of the allowed strings for root_finder\n\n If one provides a full set of parameters (tau, s and l) which are not satisfactory, an\n error message is returned::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = GSD(C, tau=142, parameters=(1, 2))\n Traceback (most recent call last):\n ...\n ValueError: Impossible parameters for the Guruswami-Sudan algorithm\n\n If ``code`` is not a GRS code, an error is raised::\n\n sage: C = codes.random_linear_code(GF(11), 10, 4)\n sage: GSD(C, tau=2)\n Traceback (most recent call last):\n ...\n ValueError: code has to be a generalized Reed-Solomon code\n ' if (not isinstance(code, GeneralizedReedSolomonCode)): raise ValueError('code has to be a generalized Reed-Solomon code') (n, k) = (code.length(), code.dimension()) if (tau and parameters): if (not GRSGuruswamiSudanDecoder.gs_satisfactory(tau, parameters[0], parameters[1], C=code)): raise ValueError('Impossible parameters for the Guruswami-Sudan algorithm') (self._tau, self._s, self._ell) = (tau, parameters[0], parameters[1]) elif tau: self._tau = tau (self._s, self._ell) = GRSGuruswamiSudanDecoder.parameters_given_tau(tau, n_k=(n, k)) elif parameters: self._s = parameters[0] self._ell = parameters[1] (self._tau, _) = GRSGuruswamiSudanDecoder.guruswami_sudan_decoding_radius(C=code, s=self._s, l=self._ell) else: raise ValueError('Specify either tau or parameters') if callable(interpolation_alg): self._interpolation_alg = interpolation_alg elif ((interpolation_alg is None) or (interpolation_alg == 'LeeOSullivan')): self._interpolation_alg = gs_interpolation_lee_osullivan elif (interpolation_alg == 'LinearAlgebra'): self._interpolation_alg = gs_interpolation_linalg else: raise ValueError('Please provide a method or one of the allowed strings for interpolation_alg') if callable(root_finder): self._root_finder = root_finder elif (root_finder == 'RothRuckenstein'): self._root_finder = roth_ruckenstein_root_finder elif ((root_finder is None) or (root_finder == 'Alekhnovich')): self._root_finder = alekhnovich_root_finder else: raise ValueError('Please provide a method or one of the allowed strings for root_finder') super().__init__(code, code.ambient_space(), 'EvaluationPolynomial') def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = C.decoder("GuruswamiSudan", tau=97)\n sage: D\n Guruswami-Sudan decoder for [250, 70, 181] Reed-Solomon Code over GF(251) decoding 97 errors with parameters (1, 2)\n ' return ('Guruswami-Sudan decoder for %s decoding %s errors with parameters %s' % (self.code(), self.decoding_radius(), (self.multiplicity(), self.list_size()))) def _latex_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = C.decoder("GuruswamiSudan", tau=97)\n sage: latex(D)\n \\textnormal{Guruswami-Sudan decoder for } [250, 70, 181] \\textnormal{ Reed-Solomon Code over } \\Bold{F}_{251}\\textnormal{ decoding }97\\textnormal{ errors with parameters }(1, 2)\n ' return ('\\textnormal{Guruswami-Sudan decoder for } %s\\textnormal{ decoding }%s\\textnormal{ errors with parameters }%s' % (self.code()._latex_(), self.decoding_radius(), (self.multiplicity(), self.list_size()))) def __eq__(self, other): '\n Tests equality between GRSGuruswamiSudanDecoder objects.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D1 = C.decoder("GuruswamiSudan", tau=97)\n sage: D2 = C.decoder("GuruswamiSudan", tau=97)\n sage: D1.__eq__(D2)\n True\n ' return (isinstance(other, GRSGuruswamiSudanDecoder) and (self.code() == other.code()) and (self.decoding_radius() == other.decoding_radius()) and (self.multiplicity() == other.multiplicity()) and (self.list_size() == other.list_size()) and (self.interpolation_algorithm() == other.interpolation_algorithm()) and (self.rootfinding_algorithm() == other.rootfinding_algorithm())) def interpolation_algorithm(self): '\n Return the interpolation algorithm that will be used.\n\n Remember that its signature has to be:\n ``my_inter(interpolation_points, tau, s_and_l, wy)``.\n See :meth:`sage.coding.guruswami_sudan.interpolation.gs_interpolation_linalg`\n for an example.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = C.decoder("GuruswamiSudan", tau=97)\n sage: D.interpolation_algorithm()\n <function gs_interpolation_lee_osullivan at 0x...>\n ' return self._interpolation_alg def rootfinding_algorithm(self): '\n Return the rootfinding algorithm that will be used.\n\n Remember that its signature has to be:\n ``my_rootfinder(Q, maxd=default_value, precision=default_value)``.\n See :meth:`roth_ruckenstein_root_finder`\n for an example.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = C.decoder("GuruswamiSudan", tau=97)\n sage: D.rootfinding_algorithm()\n <function alekhnovich_root_finder at 0x...>\n ' return self._root_finder def parameters(self): '\n Return the multiplicity and list size parameters of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = C.decoder("GuruswamiSudan", tau=97)\n sage: D.parameters()\n (1, 2)\n ' return (self._s, self._ell) def multiplicity(self): '\n Return the multiplicity parameter of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = C.decoder("GuruswamiSudan", tau=97)\n sage: D.multiplicity()\n 1\n ' return self._s def list_size(self): '\n Return the list size parameter of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = C.decoder("GuruswamiSudan", tau=97)\n sage: D.list_size()\n 2\n ' return self._ell def decode_to_message(self, r): '\n Decode ``r`` to the list of polynomials whose encoding by\n :meth:`self.code()` is within Hamming distance\n :meth:`self.decoding_radius` of ``r``.\n\n INPUT:\n\n - ``r`` -- a received word, i.e. a vector in `F^n` where `F` and `n` are\n the base field respectively length of :meth:`self.code`.\n\n EXAMPLES::\n\n sage: GSD = codes.decoders.GRSGuruswamiSudanDecoder\n sage: C = codes.GeneralizedReedSolomonCode(GF(17).list()[:15], 6)\n sage: D = GSD(C, tau=5)\n sage: F.<x> = GF(17)[]\n sage: m = 13*x^4 + 7*x^3 + 10*x^2 + 14*x + 3\n sage: c = D.connected_encoder().encode(m)\n sage: r = vector(GF(17), [3,13,12,0,0,7,5,1,8,11,15,12,14,7,10])\n sage: (c-r).hamming_weight()\n 5\n sage: messages = D.decode_to_message(r)\n sage: len(messages)\n 2\n sage: m in messages\n True\n\n TESTS:\n\n If one has provided a method as a ``root_finder`` or a ``interpolation_alg`` which\n does not fit the allowed signature, an exception will be raised::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(17).list()[:15], 6)\n sage: D = GSD(C, tau=5, root_finder=next_prime)\n sage: F.<x> = GF(17)[]\n sage: m = 9*x^5 + 10*x^4 + 9*x^3 + 7*x^2 + 15*x + 2\n sage: c = D.connected_encoder().encode(m)\n sage: r = vector(GF(17), [3,1,4,2,14,1,0,4,13,12,1,16,1,13,15])\n sage: m in D.decode_to_message(r)\n Traceback (most recent call last):\n ...\n ValueError: The provided root-finding algorithm has a wrong signature.\n See the documentation of `...rootfinding_algorithm()` for details\n ' return [self.connected_encoder().unencode(c) for c in self.decode_to_code(r)] def decode_to_code(self, r): '\n Return the list of all codeword within radius :meth:`self.decoding_radius` of the received word `r`.\n\n INPUT:\n\n - ``r`` -- a received word, i.e. a vector in `F^n` where `F` and `n` are\n the base field respectively length of :meth:`self.code`.\n\n EXAMPLES::\n\n sage: GSD = codes.decoders.GRSGuruswamiSudanDecoder\n sage: C = codes.GeneralizedReedSolomonCode(GF(17).list()[:15], 6)\n sage: D = GSD(C, tau=5)\n sage: c = vector(GF(17), [3,13,12,0,0,7,5,1,8,11,1,9,4,12,14])\n sage: c in C\n True\n sage: r = vector(GF(17), [3,13,12,0,0,7,5,1,8,11,15,12,14,7,10])\n sage: r in C\n False\n sage: codewords = D.decode_to_code(r)\n sage: len(codewords)\n 2\n sage: c in codewords\n True\n\n TESTS:\n\n Check that :trac:`21347` is fixed::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(13).list()[:10], 3)\n sage: D = GSD(C, tau=4)\n sage: c = vector(GF(13), [6, 8, 2, 1, 5, 1, 2, 8, 6, 9])\n sage: e = vector(GF(13), [1, 0, 0, 1, 1, 0, 0, 1, 0, 1])\n sage: D.decode_to_code(c+e)\n []\n ' C = self.code() k = C.dimension() alphas = C.evaluation_points() colmults = C.column_multipliers() s = self.multiplicity() l = self.list_size() tau = self.decoding_radius() wy = (k - 1) points = [(alphas[i], (r[i] / colmults[i])) for i in range(0, len(alphas))] try: Q = self.interpolation_algorithm()(points, tau, (s, l), wy) except TypeError: raise ValueError('The provided interpolation algorithm has a wrong signature. See the documentation of `codes.decoders.GRSGuruswamiSudanDecoder.interpolation_algorithm()` for details') try: polynomials = self.rootfinding_algorithm()(Q, maxd=wy) except TypeError: raise ValueError('The provided root-finding algorithm has a wrong signature. See the documentation of `codes.decoders.GRSGuruswamiSudanDecoder.rootfinding_algorithm()` for details') if (not polynomials): return [] E = self.connected_encoder() codewords = [E.encode(f) for f in polynomials] return [c for c in codewords if ((r - c).hamming_weight() <= tau)] def decoding_radius(self): '\n Return the maximal number of errors that ``self`` is able to correct.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = C.decoder("GuruswamiSudan", tau=97)\n sage: D.decoding_radius()\n 97\n\n An example where tau is not one of the inputs to the constructor::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(251).list()[:250], 70)\n sage: D = C.decoder("GuruswamiSudan", parameters=(2,4))\n sage: D.decoding_radius()\n 105\n ' return self._tau
def _flatten_once(lstlst): "\n Flattens a list of list into a list, but only flattening one layer and\n returns a generator.\n\n This is similar to Python's ``flatten`` method, except that here, if you\n provide a list of lists of lists (and so on), it returns a list of lists\n (and so on) and not a list.\n\n INPUT:\n\n - ``lstlst`` -- a list of lists.\n\n EXAMPLES::\n\n sage: from sage.coding.guruswami_sudan.interpolation import _flatten_once\n sage: ll = [[1,2], [3,4], [5,6]]\n sage: list(_flatten_once(ll))\n [1, 2, 3, 4, 5, 6]\n " for lst in lstlst: (yield from lst)
def _monomial_list(maxdeg, l, wy): '\n Returns a list of all non-negative integer pairs `(i,j)` such that ``i + wy\n * j < maxdeg`` and ``j \\geq l``.\n\n INPUT:\n\n - ``maxdeg``, ``l``, ``wy`` -- integers.\n\n OUTPUT:\n\n - a list of pairs of integers.\n\n EXAMPLES::\n\n sage: from sage.coding.guruswami_sudan.interpolation import _monomial_list\n sage: list(_monomial_list(8, 1, 3))\n [(0, 0),\n (1, 0),\n (2, 0),\n (3, 0),\n (4, 0),\n (5, 0),\n (6, 0),\n (7, 0),\n (0, 1),\n (1, 1),\n (2, 1),\n (3, 1),\n (4, 1)]\n ' for y in range((l + 1)): for x in range((maxdeg - (y * wy))): (yield (x, y))
def _interpolation_matrix_given_monomials(points, s, monomials): '\n Returns a matrix whose nullspace is a basis for all interpolation\n polynomials, each polynomial having its coefficients laid out according to\n the given list of monomials.\n\n The output is an `S \\times T` matrix, where `T` is the length of\n ``monomials``, and `S = s(s+1)/2`. Its ``i``-th column will be the\n coefficients on the ``i``-th monomial in ``monomials``.\n\n INPUT:\n\n - ``points`` -- a list of pairs of field elements, the interpolation points.\n\n - ``s`` -- an integer, the multiplicity parameter from Guruswami-Sudan algorithm.\n\n - ``monomials`` -- a list of monomials, each represented by the powers as an integer pair `(i,j)`.\n\n EXAMPLES::\n\n sage: from sage.coding.guruswami_sudan.interpolation import _interpolation_matrix_given_monomials\n sage: F = GF(11)\n sage: points = [ (F(0), F(1)), (F(1), F(5)) ]\n sage: s = 2\n sage: monomials = [(0, 0), (1, 0), (1, 1), (0, 2) ]\n sage: _interpolation_matrix_given_monomials(points, s, monomials)\n [ 1 0 0 1]\n [ 0 0 0 2]\n [ 0 1 1 0]\n [ 1 1 5 3]\n [ 0 0 1 10]\n [ 0 1 5 0]\n ' def eqs_affine(x0, y0): '\n Make equation for the affine point x0, y0. Return a list of\n equations, each equation being a list of coefficients corresponding to\n the monomials in ``monomials``.\n ' eqs = [] for i in range(s): for j in range((s - i)): eq = {} for monomial in monomials: ihat = monomial[0] jhat = monomial[1] if ((ihat >= i) and (jhat >= j)): icoeff = ((binomial(ihat, i) * (x0 ** (ihat - i))) if (ihat > i) else 1) jcoeff = ((binomial(jhat, j) * (y0 ** (jhat - j))) if (jhat > j) else 1) eq[monomial] = (jcoeff * icoeff) eqs.append([eq.get(monomial, 0) for monomial in monomials]) return eqs return matrix(list(_flatten_once([eqs_affine(*point) for point in points])))
def _interpolation_max_weighted_deg(n, tau, s): 'Return the maximal weighted degree allowed for an interpolation\n polynomial over `n` points, correcting `tau` errors and with multiplicity\n `s`\n\n EXAMPLES::\n\n sage: from sage.coding.guruswami_sudan.interpolation import _interpolation_max_weighted_deg\n sage: _interpolation_max_weighted_deg(10, 3, 5)\n 35\n ' return ((n - tau) * s)
def _interpolation_matrix_problem(points, tau, parameters, wy): "\n Returns the linear system of equations which ``Q`` should be a solution to.\n\n This linear system is returned as a matrix ``M`` and a list of monomials ``monomials``,\n where a vector in the right nullspace of ``M`` corresponds to an\n interpolation polynomial `Q`, by mapping the `t`'th element of such a vector\n to the coefficient to `x^iy^j`, where `(i,j)` is the `t`'th element of ``monomials``.\n\n INPUT:\n\n - ``points`` -- a list of interpolation points, as pairs of field elements.\n\n - ``tau`` -- an integer, the number of errors one wants to decode.\n\n - ``parameters`` -- (default: ``None``) a pair of integers, where:\n\n - the first integer is the multiplicity parameter of Guruswami-Sudan algorithm and\n - the second integer is the list size parameter.\n\n - ``wy`` -- an integer specifying the `y`-weighted degree that is to be\n minimised in the interpolation polynomial. In Guruswami-Sudan, this is\n `k-1`, where `k` is the dimension of the GRS code.\n\n EXAMPLES:\n\n The following parameters arise from Guruswami-Sudan decoding of an [6,2,5]\n GRS code over F(11) with multiplicity 2 and list size 4. ::\n\n sage: from sage.coding.guruswami_sudan.interpolation import _interpolation_matrix_problem\n sage: F = GF(11)\n sage: points = [(F(x), F(y)) for (x,y) in [(0, 5), (1, 1), (2, 4), (3, 6), (4, 3), (5, 3)]]\n sage: tau = 3\n sage: params = (2, 4)\n sage: wy = 1\n sage: _interpolation_matrix_problem(points, tau, params, wy)\n (\n [ 1 0 0 0 0 0 5 0 0 0 0 3 0 0 0 4 0 0 9 0]\n [ 0 0 0 0 0 0 1 0 0 0 0 10 0 0 0 9 0 0 5 0]\n [ 0 1 0 0 0 0 0 5 0 0 0 0 3 0 0 0 4 0 0 9]\n [ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]\n [ 0 0 0 0 0 0 1 1 1 1 1 2 2 2 2 3 3 3 4 4]\n [ 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1]\n [ 1 2 4 8 5 10 4 8 5 10 9 5 10 9 7 9 7 3 3 6]\n [ 0 0 0 0 0 0 1 2 4 8 5 8 5 10 9 4 8 5 3 6]\n [ 0 1 4 1 10 3 0 4 5 4 7 0 5 9 5 0 9 3 0 3]\n [ 1 3 9 5 4 1 6 7 10 8 2 3 9 5 4 7 10 8 9 5]\n [ 0 0 0 0 0 0 1 3 9 5 4 1 3 9 5 9 5 4 6 7]\n [ 0 1 6 5 9 9 0 6 3 8 10 0 3 7 4 0 7 9 0 9]\n [ 1 4 5 9 3 1 3 1 4 5 9 9 3 1 4 5 9 3 4 5]\n [ 0 0 0 0 0 0 1 4 5 9 3 6 2 8 10 5 9 3 9 3]\n [ 0 1 8 4 3 4 0 3 2 1 9 0 9 6 3 0 5 7 0 4]\n [ 1 5 3 4 9 1 3 4 9 1 5 9 1 5 3 5 3 4 4 9]\n [ 0 0 0 0 0 0 1 5 3 4 9 6 8 7 2 5 3 4 9 1]\n [ 0 1 10 9 5 1 0 3 8 5 4 0 9 2 4 0 5 6 0 4], [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (0, 2), (1, 2), (2, 2), (3, 2), (0, 3), (1, 3), (2, 3), (0, 4), (1, 4)]\n )\n " (s, l) = (parameters[0], parameters[1]) monomials = list(_monomial_list(_interpolation_max_weighted_deg(len(points), tau, s), l, wy)) M = _interpolation_matrix_given_monomials(points, s, monomials) return (M, monomials)
def gs_interpolation_linalg(points, tau, parameters, wy): '\n Compute an interpolation polynomial `Q(x,y)` for the Guruswami-Sudan algorithm\n by solving a linear system of equations.\n\n `Q` is a bivariate polynomial over the field of the points, such that the\n polynomial has a zero of multiplicity at least `s` at each of the points,\n where `s` is the multiplicity parameter. Furthermore, its ``(1,\n wy)``-weighted degree should be less than\n ``_interpolation_max_weighted_deg(n, tau, wy)``, where ``n`` is the number\n of points\n\n INPUT:\n\n - ``points`` -- a list of tuples ``(xi, yi)`` such that we seek ``Q`` with\n ``(xi,yi)`` being a root of ``Q`` with multiplicity ``s``.\n\n - ``tau`` -- an integer, the number of errors one wants to decode.\n\n - ``parameters`` -- (default: ``None``) a pair of integers, where:\n\n - the first integer is the multiplicity parameter of Guruswami-Sudan\n algorithm and\n - the second integer is the list size parameter.\n\n - ``wy`` -- an integer, the `y`-weight, where we seek `Q` of low\n ``(1, wy)``-weighted degree.\n\n EXAMPLES:\n\n The following parameters arise from Guruswami-Sudan decoding of an [6,2,5]\n GRS code over F(11) with multiplicity 2 and list size 4::\n\n sage: from sage.coding.guruswami_sudan.interpolation import gs_interpolation_linalg\n sage: F = GF(11)\n sage: points = [(F(x), F(y))\n ....: for (x, y) in [(0, 5), (1, 1), (2, 4), (3, 6), (4, 3), (5, 3)]]\n sage: tau = 3\n sage: params = (2, 4)\n sage: wy = 1\n sage: Q = gs_interpolation_linalg(points, tau, params, wy); Q\n 4*x^5 - 4*x^4*y - 2*x^2*y^3 - x*y^4 + 3*x^4 - 4*x^2*y^2 + 5*y^4 - x^3 + x^2*y\n + 5*x*y^2 - 5*y^3 + 3*x*y - 2*y^2 + x - 4*y + 1\n\n We verify that the interpolation polynomial has a zero of multiplicity at least 2 in each point::\n\n sage: all( Q(x=a, y=b).is_zero() for (a,b) in points )\n True\n sage: x,y = Q.parent().gens()\n sage: dQdx = Q.derivative(x)\n sage: all( dQdx(x=a, y=b).is_zero() for (a,b) in points )\n True\n sage: dQdy = Q.derivative(y)\n sage: all( dQdy(x=a, y=b).is_zero() for (a,b) in points )\n True\n ' (M, monomials) = _interpolation_matrix_problem(points, tau, parameters, wy) Ker = M.right_kernel() sol = Ker.basis()[0] PF = M.base_ring()[('x', 'y')] (x, y) = PF.gens() Q = sum([(((x ** monomials[i][0]) * (y ** monomials[i][1])) * sol[i]) for i in range(0, len(monomials))]) return Q
def lee_osullivan_module(points, parameters, wy): "\n Return the analytically straight-forward basis for the `\\GF{q}[x]` module\n containing all interpolation polynomials, as according to Lee and\n O'Sullivan.\n\n The module is constructed in the following way: Let `R(x)` be the Lagrange\n interpolation polynomial through the sought interpolation points `(x_i,\n y_i)`, i.e. `R(x_i) = y_i`. Let `G(x) = \\prod_{i=1}^n (x-x_i)`. Then the\n `i`'th row of the basis matrix of the module is the coefficient-vector of\n the following polynomial in `\\GF{q}[x][y]`:\n\n `P_i(x,y) = G(x)^{[i-s]} (y - R(x))^{i - [i-s]} y^{[i-s]}` ,\n\n where `[a]` for real `a` is `a` when `a > 0` and 0 otherwise. It is easily\n seen that `P_i(x,y)` is an interpolation polynomial, i.e. it is zero with\n multiplicity at least `s` on each of the points `(x_i, y_i)`.\n\n\n INPUT:\n\n - ``points`` -- a list of tuples ``(xi, yi)`` such that we seek `Q` with\n ``(xi,yi)`` being a root of `Q` with multiplicity `s`.\n\n - ``parameters`` -- (default: ``None``) a pair of integers, where:\n\n - the first integer is the multiplicity parameter `s` of Guruswami-Sudan\n algorithm and\n - the second integer is the list size parameter.\n\n - ``wy`` -- an integer, the `y`-weight, where we seek `Q` of low\n ``(1,wy)`` weighted degree.\n\n EXAMPLES::\n\n sage: from sage.coding.guruswami_sudan.interpolation import lee_osullivan_module\n sage: F = GF(11)\n sage: points = [(F(0), F(2)), (F(1), F(5)), (F(2), F(0)), (F(3), F(4)),\n ....: (F(4), F(9)), (F(5), F(1)), (F(6), F(9)), (F(7), F(10))]\n sage: params = (1, 1)\n sage: wy = 1\n sage: lee_osullivan_module(points, params, wy)\n [x^8 + 5*x^7 + 3*x^6 + 9*x^5 + 4*x^4 + 2*x^3 + 9*x 0]\n [ 10*x^7 + 4*x^6 + 9*x^4 + 7*x^3 + 2*x^2 + 9*x + 9 1]\n " (s, l) = (parameters[0], parameters[1]) F = points[0][0].parent() PF = F['x'] x = PF.gens()[0] R = PF.lagrange_polynomial(points) G = prod(((x - points[i][0]) for i in range(0, len(points)))) PFy = PF['y'] y = PFy.gens()[0] ybasis = ([(((y - R) ** i) * (G ** (s - i))) for i in range(0, (s + 1))] + [((y ** (i - s)) * ((y - R) ** s)) for i in range((s + 1), (l + 1))]) def pad(lst): return (lst + ([0] * ((l + 1) - len(lst)))) modbasis = [pad(yb.coefficients(sparse=False)) for yb in ybasis] return matrix(PF, modbasis)
def gs_interpolation_lee_osullivan(points, tau, parameters, wy): "\n Returns an interpolation polynomial Q(x,y) for the given input using the\n module-based algorithm of Lee and O'Sullivan.\n\n This algorithm constructs an explicit `(\\ell+1) \\times (\\ell+1)` polynomial\n matrix whose rows span the `\\GF q[x]` module of all interpolation\n polynomials. It then runs a row reduction algorithm to find a low-shifted\n degree vector in this row space, corresponding to a low weighted-degree\n interpolation polynomial.\n\n INPUT:\n\n - ``points`` -- a list of tuples ``(xi, yi)`` such that we seek ``Q`` with\n ``(xi,yi)`` being a root of ``Q`` with multiplicity ``s``.\n\n - ``tau`` -- an integer, the number of errors one wants to decode.\n\n - ``parameters`` -- (default: ``None``) a pair of integers, where:\n\n - the first integer is the multiplicity parameter of Guruswami-Sudan\n algorithm and\n - the second integer is the list size parameter.\n\n - ``wy`` -- an integer, the `y`-weight, where we seek ``Q`` of low\n ``(1,wy)`` weighted degree.\n\n EXAMPLES::\n\n sage: from sage.coding.guruswami_sudan.interpolation import gs_interpolation_lee_osullivan\n sage: F = GF(11)\n sage: points = [(F(0), F(2)), (F(1), F(5)), (F(2), F(0)), (F(3), F(4)),\n ....: (F(4), F(9)), (F(5), F(1)), (F(6), F(9)), (F(7), F(10))]\n sage: tau = 1\n sage: params = (1, 1)\n sage: wy = 1\n sage: Q = gs_interpolation_lee_osullivan(points, tau, params, wy)\n sage: Q / Q.lc() # make monic\n x^3*y + 2*x^3 - x^2*y + 5*x^2 + 5*x*y - 5*x + 2*y - 4\n " from .utils import _degree_of_vector (s, l) = (parameters[0], parameters[1]) F = points[0][0].parent() M = lee_osullivan_module(points, (s, l), wy) shifts = [(i * wy) for i in range(0, (l + 1))] Mnew = M.reduced_form(shifts=shifts) Qlist = min(Mnew.rows(), key=(lambda r: _degree_of_vector(r, shifts))) PFxy = F['x,y'] (xx, yy) = PFxy.gens() Q = sum((((yy ** i) * PFxy(Qlist[i])) for i in range(0, (l + 1)))) return Q
def polynomial_to_list(p, len): '\n Returns ``p`` as a list of its coefficients of length ``len``.\n\n INPUT:\n\n - ``p`` -- a polynomial\n\n - ``len`` -- an integer. If ``len`` is smaller than the degree of ``p``, the\n returned list will be of size degree of ``p``, else it will be of size ``len``.\n\n EXAMPLES::\n\n sage: from sage.coding.guruswami_sudan.utils import polynomial_to_list\n sage: F.<x> = GF(41)[]\n sage: p = 9*x^2 + 8*x + 37\n sage: polynomial_to_list(p, 4)\n [37, 8, 9, 0]\n ' return (list(p) + ([0] * max(0, ((len - p.degree()) - 1))))
def johnson_radius(n, d): '\n Returns the Johnson-radius for the code length `n` and the minimum distance `d`.\n\n The Johnson radius is defined as `n - \\sqrt(n(n-d))`.\n\n INPUT:\n\n - ``n`` -- an integer, the length of the code\n - ``d`` -- an integer, the minimum distance of the code\n\n EXAMPLES::\n\n sage: sage.coding.guruswami_sudan.utils.johnson_radius(250, 181)\n -5*sqrt(690) + 250\n ' return (n - sqrt((n * (n - d))))
def ligt(x): '\n Returns the least integer greater than ``x``.\n\n EXAMPLES::\n\n sage: from sage.coding.guruswami_sudan.utils import ligt\n sage: ligt(41)\n 42\n\n It works with any type of numbers (not only integers)::\n\n sage: ligt(41.041)\n 42\n ' return floor((x + 1))
def gilt(x): '\n Returns the greatest integer smaller than ``x``.\n\n EXAMPLES::\n\n sage: from sage.coding.guruswami_sudan.utils import gilt\n sage: gilt(43)\n 42\n\n It works with any type of numbers (not only integers)::\n\n sage: gilt(43.041)\n 43\n ' if (x in ZZ): return Integer((x - 1)) else: return floor(x)
def solve_degree2_to_integer_range(a, b, c): '\n Returns the greatest integer range `[i_1, i_2]` such that\n `i_1 > x_1` and `i_2 < x_2` where `x_1, x_2` are the two zeroes of the equation in `x`:\n `ax^2+bx+c=0`.\n\n If there is no real solution to the equation, it returns an empty range with negative coefficients.\n\n INPUT:\n\n - ``a``, ``b`` and ``c`` -- coefficients of a second degree equation, ``a`` being the coefficient of\n the higher degree term.\n\n EXAMPLES::\n\n sage: from sage.coding.guruswami_sudan.utils import solve_degree2_to_integer_range\n sage: solve_degree2_to_integer_range(1, -5, 1)\n (1, 4)\n\n If there is no real solution::\n\n sage: solve_degree2_to_integer_range(50, 5, 42)\n (-2, -1)\n ' D = ((b ** 2) - ((4 * a) * c)) if (D < 0): return ((- 2), (- 1)) sD = float(sqrt(D)) (minx, maxx) = (((((- b) - sD) / 2.0) / a), ((((- b) + sD) / 2.0) / a)) (mini, maxi) = (ligt(minx), gilt(maxx)) if (mini > maxi): return ((- 2), (- 1)) else: return (mini, maxi)
def _degree_of_vector(v, shifts=None): '\n Returns the greatest degree among the entries of the polynomial vector `v`.\n\n INPUT:\n\n - ``v`` -- a vector of polynomials.\n\n - ``shifts`` -- (default: ``None``) a list of integer shifts to consider\n ``v`` under, i.e. compute `\\max(\\deg v_i + s_i)`, where `s_1,\\ldots, s_n`\n is the list of shifts.\n\n If ``None``, all shifts are considered as ``0``.\n\n EXAMPLES::\n\n sage: from sage.coding.guruswami_sudan.utils import _degree_of_vector\n sage: F.<x> = GF(7)[]\n sage: v = vector(F, [0, 1, x, x^2])\n sage: _degree_of_vector(v)\n 2\n sage: _degree_of_vector(v, shifts=[10, 1, 0, -3])\n 1\n ' if (not shifts): return max((vi.degree() for vi in v)) else: if v.is_zero(): return (- 1) return max(((degi + si) for (degi, si) in zip([vi.degree() for vi in v], shifts) if (degi > (- 1))))
def _format_decoding_interval(decoding_interval): "\n Format the decoding interval of an ISD decoder when calling ``_repr_`` or\n ``_latex_``.\n\n EXAMPLES::\n\n sage: from sage.coding.information_set_decoder import _format_decoding_interval\n sage: _format_decoding_interval((0,3))\n 'up to 3'\n sage: _format_decoding_interval((2,3))\n 'between 2 and 3'\n sage: _format_decoding_interval((3,3))\n 'exactly 3'\n " if (decoding_interval[0] == 0): return 'up to {0}'.format(decoding_interval[1]) if (decoding_interval[0] == decoding_interval[1]): return 'exactly {0}'.format(decoding_interval[0]) return 'between {0} and {1}'.format(decoding_interval[0], decoding_interval[1])
class InformationSetAlgorithm(SageObject): '\n Abstract class for algorithms for\n :class:`sage.coding.information_set_decoder.LinearCodeInformationSetDecoder`.\n\n To sub-class this class, override ``decode`` and ``calibrate``, and call the\n super constructor from ``__init__``.\n\n INPUT:\n\n - ``code`` -- A linear code for which to decode.\n\n - ``number_errors`` -- an integer, the maximal number of errors to accept as\n correct decoding. An interval can also be specified by giving a pair of\n integers, where both end values are taken to be in the interval.\n\n - ``algorithm_name`` -- A name for the specific ISD algorithm used (used for\n printing).\n\n - ``parameters`` -- (optional) A dictionary for setting the parameters of\n this ISD algorithm. Note that sanity checking this dictionary for the\n individual sub-classes should be done in the sub-class constructor.\n\n EXAMPLES::\n\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: LeeBrickellISDAlgorithm(codes.GolayCode(GF(2)), (0,4))\n ISD Algorithm (Lee-Brickell) for [24, 12, 8] Extended Golay code over GF(2)\n decoding up to 4 errors\n\n A minimal working example of how to sub-class::\n\n sage: from sage.coding.information_set_decoder import InformationSetAlgorithm\n sage: from sage.coding.decoder import DecodingError\n sage: class MinimalISD(InformationSetAlgorithm):\n ....: def __init__(self, code, decoding_interval):\n ....: super().__init__(code, decoding_interval, "MinimalISD")\n ....: def calibrate(self):\n ....: self._parameters = { } # calibrate parameters here\n ....: self._time_estimate = 10.0 # calibrated time estimate\n ....: def decode(self, r):\n ....: # decoding algorithm here\n ....: raise DecodingError("I failed")\n sage: MinimalISD(codes.GolayCode(GF(2)), (0,4))\n ISD Algorithm (MinimalISD) for [24, 12, 8] Extended Golay code over GF(2)\n decoding up to 4 errors\n ' def __init__(self, code, decoding_interval, algorithm_name, parameters=None): '\n TESTS::\n\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: LeeBrickellISDAlgorithm(codes.GolayCode(GF(2)), (0,4))\n ISD Algorithm (Lee-Brickell) for [24, 12, 8] Extended Golay code over GF(2) decoding up to 4 errors\n ' self._code = code self._decoding_interval = decoding_interval self._algorithm_name = algorithm_name if parameters: self._parameters = parameters self._parameters_specified = True else: self._parameters_specified = False def name(self): "\n Return the name of this ISD algorithm.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (0,2))\n sage: A.name()\n 'Lee-Brickell'\n " return self._algorithm_name def decode(self, r): '\n Decode a received word using this ISD decoding algorithm.\n\n Must be overridden by sub-classes.\n\n EXAMPLES::\n\n sage: M = matrix(GF(2), [[1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0],\\\n [0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1],\\\n [0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0],\\\n [0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1],\\\n [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1]])\n sage: C = codes.LinearCode(M)\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (2,2))\n sage: r = vector(GF(2), [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n sage: A.decode(r)\n (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)\n ' raise NotImplementedError def time_estimate(self): '\n Estimate for how long this ISD algorithm takes to perform a single decoding.\n\n The estimate is for a received word whose number of errors is within the\n decoding interval of this ISD algorithm.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (0,2))\n sage: A.time_estimate() #random\n 0.0008162108571427874\n ' if (not hasattr(self, '_time_estimate')): self.calibrate() return self._time_estimate def calibrate(self): "\n Uses test computations to estimate optimal values for any parameters\n this ISD algorithm may take.\n\n Must be overridden by sub-classes.\n\n If ``self._parameters_specified`` is ``False``, this method shall set\n ``self._parameters`` to the best parameters estimated. It shall always\n set ``self._time_estimate`` to the time estimate of using\n ``self._parameters``.\n\n EXAMPLES::\n\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: C = codes.GolayCode(GF(2))\n sage: A = LeeBrickellISDAlgorithm(C, (0,3))\n sage: A.calibrate()\n sage: A.parameters() #random\n {'search_size': 1}\n " raise NotImplementedError def code(self): '\n Return the code associated to this ISD algorithm.\n\n EXAMPLES::\n\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: C = codes.GolayCode(GF(2))\n sage: A = LeeBrickellISDAlgorithm(C, (0,3))\n sage: A.code()\n [24, 12, 8] Extended Golay code over GF(2)\n ' return self._code def decoding_interval(self): '\n A pair of integers specifying the interval of number of errors this\n ISD algorithm will attempt to correct.\n\n The interval includes both end values.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (0,2))\n sage: A.decoding_interval()\n (0, 2)\n ' return self._decoding_interval def parameters(self): "\n Return any parameters this ISD algorithm uses.\n\n If the parameters have not already been set, efficient values will first\n be calibrated and returned.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (0,4), search_size=3)\n sage: A.parameters()\n {'search_size': 3}\n\n If not set, calibration will determine a sensible value::\n\n sage: A = LeeBrickellISDAlgorithm(C, (0,4))\n sage: A.parameters() #random\n {'search_size': 1}\n " if (not hasattr(self, '_parameters')): self.calibrate() return self._parameters def __eq__(self, other): "\n Tests equality between ISD algorithm objects.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (0,4))\n sage: A == LeeBrickellISDAlgorithm(C, (0,4))\n True\n sage: A == LeeBrickellISDAlgorithm(C, (0,5))\n False\n sage: other_search = 1 if A.parameters()['search_size'] != 1 else 2\n sage: A == LeeBrickellISDAlgorithm(C, (0,4), search_size=other_search)\n False\n\n ISD Algorithm objects can be equal only if they have both calibrated\n the parameters, or if they both had it set and to the same value::\n\n sage: A2 = LeeBrickellISDAlgorithm(C, (0,4), search_size=A.parameters()['search_size'])\n sage: A == A2\n False\n sage: A2 == LeeBrickellISDAlgorithm(C, (0,4), search_size=A.parameters()['search_size'])\n True\n " return (isinstance(other, self.__class__) and (self.code() == other.code()) and (self.decoding_interval() == other.decoding_interval()) and (self._parameters_specified == other._parameters_specified) and ((not self._parameters_specified) or (self.parameters() == other.parameters()))) def __hash__(self): '\n Returns the hash value of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (0,4))\n sage: hash(A) #random\n 5884357732955478461\n sage: C2 = codes.GolayCode(GF(3))\n sage: A2 = LeeBrickellISDAlgorithm(C2, (0,4))\n sage: hash(A) != hash(A2)\n True\n ' return hash(str(self)) def _repr_(self): '\n Returns a string representation of this ISD algorithm.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (0,4))\n sage: A\n ISD Algorithm (Lee-Brickell) for [24, 12, 8] Extended Golay code over GF(2) decoding up to 4 errors\n ' return 'ISD Algorithm ({}) for {} decoding {} errors '.format(self._algorithm_name, self.code(), _format_decoding_interval(self.decoding_interval())) def _latex_(self): '\n Returns a latex representation of this ISD algorithm.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (0,4))\n sage: latex(A)\n \\textnormal{ISD Algorithm (Lee-Brickell) for }[24, 12, 8] \\textnormal{ Extended Golay Code over } \\Bold{F}_{2} \\textnormal{decoding up to 4 errors}\n ' return '\\textnormal{{ISD Algorithm ({}) for }}{} \\textnormal{{decoding {} errors}}'.format(self._algorithm_name, self.code()._latex_(), _format_decoding_interval(self.decoding_interval()))
class LeeBrickellISDAlgorithm(InformationSetAlgorithm): "\n The Lee-Brickell algorithm for information-set decoding.\n\n For a description of the information-set decoding paradigm (ISD), see\n :class:`sage.coding.information_set_decoder.LinearCodeInformationSetDecoder`.\n\n This implements the Lee-Brickell variant of ISD, see [LB1988]_ for the\n original binary case, and [Pet2010]_ for the `q`-ary extension.\n\n Let `C` be a `[n, k]`-linear code over `\\GF{q}`, and let `r \\in \\GF{q}^{n}` be\n a received word in a transmission. We seek the codeword whose Hamming\n distance from `r` is minimal. Let `p` and `w` be integers, such that `0\\leq\n p\\leq w`, Let `G` be a generator matrix of `C`, and for any set of indices\n `I`, we write `G_{I}` for the matrix formed by the columns of `G` indexed by\n `I`. The Lee-Brickell ISD loops the following until it is successful:\n\n 1. Choose an information set `I` of `C`.\n 2. Compute `r' = r - r_{I} G_I^{-1} G`\n 3. Consider every size-`p` subset of `I`, `\\{a_1, \\dots, a_p\\}`.\n For each `m = (m_1, \\dots, m_p) \\in \\GF{q}^{p}`, compute\n the error vector `e = r' - \\sum_{i=1}^{p} m_i g_{a_i}`,\n 4. If `e` has a Hamming weight at most `w`, return `r-e`.\n\n INPUT:\n\n - ``code`` -- A linear code for which to decode.\n\n - ``decoding_interval`` -- a pair of integers specifying an interval of\n number of errors to correct. Includes both end values.\n\n - ``search_size`` -- (optional) the size of subsets to use on step 3 of the\n algorithm as described above. Usually a small number. It has to be at most\n the largest allowed number of errors. A good choice will be approximated\n if this option is not set; see\n :meth:`sage.coding.LeeBrickellISDAlgorithm.calibrate`\n for details.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (0,4)); A\n ISD Algorithm (Lee-Brickell) for [24, 12, 8] Extended Golay code over GF(2)\n decoding up to 4 errors\n\n sage: C = codes.GolayCode(GF(2))\n sage: A = LeeBrickellISDAlgorithm(C, (2,3)); A\n ISD Algorithm (Lee-Brickell) for [24, 12, 8] Extended Golay code over GF(2)\n decoding between 2 and 3 errors\n " def __init__(self, code, decoding_interval, search_size=None): '\n TESTS:\n\n If ``search_size`` is not a positive integer, or is bigger than the\n decoding radius, an error will be raised::\n\n sage: C = codes.GolayCode(GF(2))\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: LeeBrickellISDAlgorithm(C, (1, 3), search_size=-1)\n Traceback (most recent call last):\n ...\n ValueError: The search size parameter has to be a positive integer\n\n sage: LeeBrickellISDAlgorithm(C, (1, 3), search_size=4)\n Traceback (most recent call last):\n ...\n ValueError: The search size parameter has to be at most the maximal number of allowed errors\n ' if (search_size is not None): if ((not isinstance(search_size, (Integer, int))) or (search_size < 0)): raise ValueError('The search size parameter has to be a positive integer') if (search_size > decoding_interval[1]): raise ValueError('The search size parameter has to be at most the maximal number of allowed errors') super().__init__(code, decoding_interval, 'Lee-Brickell', parameters={'search_size': search_size}) self._parameters_specified = True else: self._parameters_specified = False super().__init__(code, decoding_interval, 'Lee-Brickell') def decode(self, r): '\n The Lee-Brickell algorithm as described in the class doc.\n\n Note that either parameters must be given at construction time or\n :meth:`sage.coding.information_set_decoder.InformationSetAlgorithm.calibrate()`\n should be called before calling this method.\n\n INPUT:\n\n - `r` -- a received word, i.e. a vector in the ambient space of\n :meth:`decoder.Decoder.code`.\n\n OUTPUT: A codeword whose distance to `r` satisfies ``self.decoding_interval()``.\n\n EXAMPLES::\n\n sage: M = matrix(GF(2), [[1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0],\\\n [0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1],\\\n [0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0],\\\n [0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1],\\\n [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1]])\n sage: C = codes.LinearCode(M)\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (2,2))\n sage: c = C.random_element()\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(), 2)\n sage: r = Chan(c)\n sage: c_out = A.decode(r)\n sage: (r - c).hamming_weight() == 2\n True\n ' import itertools from sage.misc.prandom import sample C = self.code() (n, k) = (C.length(), C.dimension()) tau = self.decoding_interval() p = self.parameters()['search_size'] F = C.base_ring() G = C.generator_matrix() Fstar = F.list()[1:] while True: I = sample(range(n), k) Gi = G.matrix_from_columns(I) try: Gi_inv = Gi.inverse() except ZeroDivisionError: continue Gt = (Gi_inv * G) y = (r - (vector([r[i] for i in I]) * Gt)) g = Gt.rows() for pi in range((p + 1)): for A in itertools.combinations(range(k), pi): for m in itertools.product(Fstar, repeat=pi): e = (y - sum(((m[i] * g[A[i]]) for i in range(pi)))) errs = e.hamming_weight() if (tau[0] <= errs <= tau[1]): return (r - e) def calibrate(self): "\n Run some test computations to estimate the optimal search size.\n\n Let `p` be the search size. We should simply choose `p` such that the\n average expected time is minimal. The algorithm succeeds when it chooses\n an information set with at least `k - p` correct positions, where `k` is\n the dimension of the code and `p` the search size. The expected number\n of trials we need before this occurs is:\n\n .. MATH::\n\n \\binom{n}{k}/(\\rho \\sum_{i=0}^p \\binom{n-\\tau}{k-i} \\binom{\\tau}{i})\n\n Here `\\rho` is the fraction of `k` subsets of indices which are\n information sets. If `T` is the average time for steps 1 and 2\n (including selecting `I` until an information set is found), while `P(i)`\n is the time for the body of the ``for``-loop in step 3 for `m` of weight\n `i`, then each information set trial takes roughly time `T +\n \\sum_{i=0}^{p} P(i) \\binom{k}{i} (q-1)^i`, where `\\GF{q}` is the base\n field.\n\n The values `T` and `P` are here estimated by running a few test\n computations similar to those done by the decoding algorithm.\n We don't explicitly estimate `\\rho`.\n\n OUTPUT: Does not output anything but sets private fields used by\n :meth:`sage.coding.information_set_decoder.InformationSetAlgorithm.parameters()`\n and\n :meth:`sage.coding.information_set_decoder.InformationSetAlgorithm.time_estimate()``.\n\n EXAMPLES::\n\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: C = codes.GolayCode(GF(2))\n sage: A = LeeBrickellISDAlgorithm(C, (0,3)); A\n ISD Algorithm (Lee-Brickell) for [24, 12, 8] Extended Golay code over GF(2)\n decoding up to 3 errors\n sage: A.calibrate()\n sage: A.parameters() #random\n {'search_size': 1}\n sage: A.time_estimate() #random\n 0.0008162108571427874\n\n If we specify the parameter at construction time, calibrate does not override this choice::\n\n sage: A = LeeBrickellISDAlgorithm(C, (0,3), search_size=2); A\n ISD Algorithm (Lee-Brickell) for [24, 12, 8] Extended Golay code over GF(2)\n decoding up to 3 errors\n sage: A.parameters()\n {'search_size': 2}\n sage: A.calibrate()\n sage: A.parameters()\n {'search_size': 2}\n sage: A.time_estimate() #random\n 0.0008162108571427874\n " from sage.matrix.special import random_matrix from sage.misc.prandom import sample, randint from sage.modules.free_module_element import random_vector from time import process_time C = self.code() G = C.generator_matrix() (n, k) = (C.length(), C.dimension()) tau = self.decoding_interval()[1] F = C.base_ring() q = F.cardinality() Fstar = F.list()[1:] def time_information_set_steps(): before = process_time() while True: I = sample(range(n), k) Gi = G.matrix_from_columns(I) try: Gi_inv = Gi.inverse() except ZeroDivisionError: continue return (process_time() - before) def time_search_loop(p): y = random_vector(F, n) g = random_matrix(F, p, n).rows() scalars = [[Fstar[randint(0, (q - 2))] for i in range(p)] for s in range(100)] before = process_time() for m in scalars: e = (y - sum(((m[i] * g[i]) for i in range(p)))) return ((process_time() - before) / 100.0) T = (sum([time_information_set_steps() for s in range(5)]) / 5.0) P = [time_search_loop(p) for p in range((tau + 1))] def compute_estimate(p): iters = ((1.0 * binomial(n, k)) / sum(((binomial((n - tau), (k - i)) * binomial(tau, i)) for i in range((p + 1))))) estimate = (iters * (T + sum((((P[pi] * ((q - 1) ** pi)) * binomial(k, pi)) for pi in range((p + 1)))))) return estimate if self._parameters_specified: self._time_estimate = compute_estimate(self._parameters['search_size']) else: self._calibrate_select([compute_estimate(p) for p in range((tau + 1))]) def _calibrate_select(self, estimates): "\n Internal method used by ``self.calibrate()``.\n\n Given the timing estimates, select the best parameter and set the\n appropriate private fields.\n\n INPUT:\n\n - `estimates` - list of time estimates, for the search size set to the\n index of the list entry.\n\n OUTPUT: None, but sets the private fields `self._parameters` and\n `self._time_estimate`.\n\n TESTS::\n\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: C = codes.GolayCode(GF(2))\n sage: A = LeeBrickellISDAlgorithm(C, (0,3)); A\n ISD Algorithm (Lee-Brickell) for [24, 12, 8] Extended Golay code over GF(2) decoding up to 3 errors\n sage: A._calibrate_select([ 1.0, 2.0, 3.0, 0.5, 0.6, 1.0 ])\n sage: A._time_estimate\n 0.500000000000000\n sage: A._parameters\n {'search_size': 3}\n " search_size = 0 for p in range(1, len(estimates)): if (estimates[p] < estimates[search_size]): search_size = p self._parameters = {'search_size': search_size} self._time_estimate = estimates[search_size]
class LinearCodeInformationSetDecoder(Decoder): '\n Information-set decoder for any linear code.\n\n Information-set decoding is a probabilistic decoding strategy that\n essentially tries to guess `k` correct positions in the received word,\n where `k` is the dimension of the code. A codeword agreeing with the\n received word on the guessed position can easily be computed, and their\n difference is one possible error vector. A "correct" guess is assumed when\n this error vector has low Hamming weight.\n\n The ISD strategy requires choosing how many errors is deemed acceptable. One\n choice could be `d/2`, where `d` is the minimum distance of the code, but\n sometimes `d` is not known, or sometimes more errors are expected. If one\n chooses anything above `d/2`, the algorithm does not guarantee to return a\n nearest codeword.\n\n This simple algorithm is not very efficient in itself, but there are numerous\n refinements to the strategy. Specifying which strategy to use among those\n that Sage knows is done using the ``algorithm`` keyword. If this is not set,\n an efficient choice will be made for you.\n\n The various ISD algorithms all need to select a number of parameters. If you\n choose a specific algorithm to use, you can pass these parameters as named\n parameters directly to this class\' constructor. If you don\'t, efficient\n choices will be calibrated for you.\n\n .. WARNING::\n\n If there is no codeword within the specified decoding distance, then the\n decoder may never terminate, or it may raise a\n :exc:`sage.coding.decoder.DecodingError` exception, depending on the ISD\n algorithm used.\n\n INPUT:\n\n - ``code`` -- A linear code for which to decode.\n\n - ``number_errors`` -- an integer, the maximal number of errors to accept as\n correct decoding. An interval can also be specified by giving a pair of\n integers, where both end values are taken to be in the interval.\n\n - ``algorithm`` -- (optional) the string name of the ISD algorithm to\n employ. If this is not set, an appropriate one will be chosen.\n A constructed\n :class:`sage.coding.information_set_decoder.InformationSetAlgorithm`\n object may also be given. In this case ``number_errors`` must match that\n of the passed algorithm.\n\n - ``**kwargs`` -- (optional) any number of named arguments passed on to the\n ISD algorithm. Such are usually not required, and they can only be set if\n ``algorithm`` is set to a specific algorithm. See the documentation for\n each individual ISD algorithm class for information on any named arguments\n they may accept. The easiest way to access this documentation is to first\n construct the decoder without passing any named arguments, then accessing\n the ISD algorithm using\n :meth:`sage.coding.information_set_decoder.LinearCodeInformationSetDecoder.algorithm`,\n and then reading the `?` help on the constructed object.\n\n EXAMPLES:\n\n The principal way to access this class is through the\n :meth:`sage.code.linear_code.AbstractLinearCode.decoder` method::\n\n sage: C = codes.GolayCode(GF(3))\n sage: D = C.decoder("InformationSet", 2); D\n Information-set decoder (Lee-Brickell) for [12, 6, 6] Extended Golay code over GF(3)\n decoding up to 2 errors\n\n You can specify which algorithm you wish to use, and you should do so in\n order to pass special parameters to it::\n\n sage: C = codes.GolayCode(GF(3))\n sage: D2 = C.decoder("InformationSet", 2, algorithm="Lee-Brickell", search_size=2); D2\n Information-set decoder (Lee-Brickell) for [12, 6, 6] Extended Golay code over GF(3)\n decoding up to 2 errors\n sage: D2.algorithm()\n ISD Algorithm (Lee-Brickell) for [12, 6, 6] Extended Golay code over GF(3)\n decoding up to 2 errors\n sage: D2.algorithm().parameters()\n {\'search_size\': 2}\n\n If you specify an algorithm which is not known, you get a friendly error message::\n\n sage: C.decoder("InformationSet", 2, algorithm="NoSuchThing")\n Traceback (most recent call last):\n ...\n ValueError: Unknown ISD algorithm \'NoSuchThing\'.\n The known algorithms are [\'Lee-Brickell\'].\n\n You can also construct an ISD algorithm separately and pass that. This is\n mostly useful if you write your own ISD algorithms::\n\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (0, 2))\n sage: D = C.decoder("InformationSet", 2, algorithm=A); D\n Information-set decoder (Lee-Brickell) for [12, 6, 6] Extended Golay code over GF(3)\n decoding up to 2 errors\n\n When passing an already constructed ISD algorithm, you can\'t also pass\n parameters to the ISD algorithm when constructing the decoder::\n\n sage: C.decoder("InformationSet", 2, algorithm=A, search_size=2)\n Traceback (most recent call last):\n ...\n ValueError: ISD algorithm arguments are not allowed\n when supplying a constructed ISD algorithm\n\n We can also information-set decode non-binary codes::\n\n sage: C = codes.GolayCode(GF(3))\n sage: D = C.decoder("InformationSet", 2); D\n Information-set decoder (Lee-Brickell) for [12, 6, 6] Extended Golay code over GF(3)\n decoding up to 2 errors\n\n There are two other ways to access this class::\n\n sage: D = codes.decoders.LinearCodeInformationSetDecoder(C, 2); D\n Information-set decoder (Lee-Brickell) for [12, 6, 6] Extended Golay code over GF(3)\n decoding up to 2 errors\n\n sage: from sage.coding.information_set_decoder import LinearCodeInformationSetDecoder\n sage: D = LinearCodeInformationSetDecoder(C, 2); D\n Information-set decoder (Lee-Brickell) for [12, 6, 6] Extended Golay code over GF(3)\n decoding up to 2 errors\n ' def __init__(self, code, number_errors, algorithm=None, **kwargs): '\n TESTS:\n\n ``number_errors`` has to be either a list of Integers/ints, a tuple of Integers/ints,\n or an Integer/int::\n\n sage: C = codes.GolayCode(GF(2))\n sage: D = C.decoder("InformationSet", "aa")\n Traceback (most recent call last):\n ...\n ValueError: number_errors should be an integer or a pair of integers\n\n If ``number_errors`` is passed as a list/tuple, it has to contain only\n two values, the first one being at most the second one::\n\n sage: C = codes.GolayCode(GF(2))\n sage: D = C.decoder("InformationSet", (4, 2))\n Traceback (most recent call last):\n ...\n ValueError: number_errors should be a positive integer or a valid interval within the positive integers\n\n You cannot ask the decoder to correct more errors than the code length::\n\n sage: D = C.decoder("InformationSet", 25)\n Traceback (most recent call last):\n ...\n ValueError: The provided number of errors should be at most the code\'s length\n\n If ``algorithm`` is not set, additional parameters cannot be passed to\n the ISD algorithm::\n\n sage: D = C.decoder("InformationSet", 2, search_size=2)\n Traceback (most recent call last):\n ...\n ValueError: Additional arguments to an information-set decoder algorithm are only allowed if a specific algorithm is selected by setting the algorithm keyword\n\n If ``algorithm`` is set to a constructed ISD algorithm, additional\n parameters cannot be passed to the ISD algorithm::\n\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (0, 2))\n sage: D = C.decoder("InformationSet", 2, A, search_size=3)\n Traceback (most recent call last):\n ...\n ValueError: ISD algorithm arguments are not allowed when supplying a constructed ISD algorithm\n\n If ``algorithm`` is set to a constructed\n :class:`sage.coding.information_set_decoder.InformationSetAlgorithm`,\n then ``number_errors`` must match that of the algorithm::\n\n sage: C = codes.GolayCode(GF(2))\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: A = LeeBrickellISDAlgorithm(C, (0, 2))\n sage: D = C.decoder("InformationSet", 2, A); D\n Information-set decoder (Lee-Brickell) for [24, 12, 8] Extended Golay code over GF(2) decoding up to 2 errors\n sage: D = C.decoder("InformationSet", (0,2), A); D\n Information-set decoder (Lee-Brickell) for [24, 12, 8] Extended Golay code over GF(2) decoding up to 2 errors\n sage: D = C.decoder("InformationSet", 3, A); D\n Traceback (most recent call last):\n ...\n ValueError: number_errors must match that of the passed ISD algorithm\n ' if isinstance(number_errors, (Integer, int)): number_errors = (0, number_errors) if (isinstance(number_errors, (tuple, list)) and (len(number_errors) == 2) and (number_errors[0] in ZZ) and (number_errors[1] in ZZ)): if ((0 > number_errors[0]) or (number_errors[0] > number_errors[1])): raise ValueError('number_errors should be a positive integer or a valid interval within the positive integers') if (number_errors[1] > code.length()): raise ValueError("The provided number of errors should be at most the code's length") else: raise ValueError('number_errors should be an integer or a pair of integers') self._number_errors = number_errors super().__init__(code, code.ambient_space(), code._default_encoder_name) if (algorithm is None): if kwargs: raise ValueError('Additional arguments to an information-set decoder algorithm are only allowed if a specific algorithm is selected by setting the algorithm keyword') algorithm = 'Lee-Brickell' algorithm_names = LinearCodeInformationSetDecoder.known_algorithms(dictionary=True) if isinstance(algorithm, InformationSetAlgorithm): if kwargs: raise ValueError('ISD algorithm arguments are not allowed when supplying a constructed ISD algorithm') if (number_errors != algorithm.decoding_interval()): raise ValueError('number_errors must match that of the passed ISD algorithm') self._algorithm = algorithm elif (algorithm in algorithm_names): self._algorithm = algorithm_names[algorithm](code, number_errors, **kwargs) else: raise ValueError("Unknown ISD algorithm '{}'. The known algorithms are {}.".format(algorithm, sorted(algorithm_names))) _known_algorithms = {'Lee-Brickell': LeeBrickellISDAlgorithm} @staticmethod def known_algorithms(dictionary=False): "\n Return the list of ISD algorithms that Sage knows.\n\n Passing any of these to the constructor of\n :class:`sage.coding.information_set_decoder.LinearCodeInformationSetDecoder`\n will make the ISD decoder use that algorithm.\n\n INPUT:\n\n - ``dictionary`` - optional. If set to ``True``, return a ``dict``\n mapping decoding algorithm name to its class.\n\n OUTPUT: a list of strings or a ``dict`` from string to ISD algorithm class.\n\n EXAMPLES::\n\n sage: from sage.coding.information_set_decoder import LinearCodeInformationSetDecoder\n sage: sorted(LinearCodeInformationSetDecoder.known_algorithms())\n ['Lee-Brickell']\n " if dictionary: return LinearCodeInformationSetDecoder._known_algorithms else: return LinearCodeInformationSetDecoder._known_algorithms.keys() def algorithm(self): '\n Return the ISD algorithm used by this ISD decoder.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: D = C.decoder("InformationSet", (2,4), "Lee-Brickell")\n sage: D.algorithm()\n ISD Algorithm (Lee-Brickell) for [24, 12, 8] Extended Golay code over GF(2)\n decoding between 2 and 4 errors\n ' return self._algorithm def decode_to_code(self, r): "\n Decodes a received word with respect to the associated code of this decoder.\n\n .. WARNING::\n\n If there is no codeword within the decoding radius of this decoder, this\n method may never terminate, or it may raise a\n :exc:`sage.coding.decoder.DecodingError` exception, depending on the ISD\n algorithm used.\n\n INPUT:\n\n - ``r`` -- a vector in the ambient space of :meth:`decoder.Decoder.code`.\n\n OUTPUT: a codeword of :meth:`decoder.Decoder.code`.\n\n EXAMPLES::\n\n sage: M = matrix(GF(2), [[1,0,0,0,0,0,1,0,1,0,1,1,0,0,1],\\\n [0,1,0,0,0,1,1,1,1,0,0,0,0,1,1],\\\n [0,0,1,0,0,0,0,1,0,1,1,1,1,1,0],\\\n [0,0,0,1,0,0,1,0,1,0,0,0,1,1,0],\\\n [0,0,0,0,1,0,0,0,1,0,1,1,0,1,0]])\n sage: C = LinearCode(M)\n sage: c = C.random_element()\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(), 2)\n sage: r = Chan(c)\n sage: D = C.decoder('InformationSet', 2)\n sage: c == D.decode_to_code(r)\n True\n\n Information-set decoding a non-binary code::\n\n sage: C = codes.GolayCode(GF(3)); C\n [12, 6, 6] Extended Golay code over GF(3)\n sage: c = C.random_element()\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(), 2)\n sage: r = Chan(c)\n sage: D = C.decoder('InformationSet', 2)\n sage: c == D.decode_to_code(r)\n True\n\n Let's take a bigger example, for which syndrome decoding or\n nearest-neighbor decoding would be infeasible: the `[59, 30]` Quadratic\n Residue code over `\\GF{3}` has true minimum distance 17, so we can\n correct 8 errors::\n\n sage: C = codes.QuadraticResidueCode(59, GF(3))\n sage: c = C.random_element()\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(), 2)\n sage: r = Chan(c)\n sage: D = C.decoder('InformationSet', 8)\n sage: c == D.decode_to_code(r) # long time\n True\n " C = self.code() if (r in C): return r return self.algorithm().decode(r) def decoding_radius(self): '\n Return the maximal number of errors this decoder can decode.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: D = C.decoder("InformationSet", 2)\n sage: D.decoding_radius()\n 2\n ' return self._number_errors[1] def decoding_interval(self): '\n A pair of integers specifying the interval of number of errors this\n decoder will attempt to correct.\n\n The interval includes both end values.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: D = C.decoder("InformationSet", 2)\n sage: D.decoding_interval()\n (0, 2)\n ' return self._number_errors def _repr_(self): '\n Returns a string representation of this decoding algorithm.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: D = C.decoder("InformationSet", 2)\n sage: D\n Information-set decoder (Lee-Brickell) for [24, 12, 8] Extended Golay code over GF(2) decoding up to 2 errors\n ' return 'Information-set decoder ({}) for {} decoding {} errors '.format(self.algorithm().name(), self.code(), _format_decoding_interval(self.decoding_interval())) def _latex_(self): '\n Returns a latex representation of this decoding algorithm.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: from sage.coding.information_set_decoder import LeeBrickellISDAlgorithm\n sage: D = C.decoder("InformationSet", 2)\n sage: latex(D)\n \\textnormal{Information-set decoder (Lee-Brickell) for }[24, 12, 8] \\textnormal{ Extended Golay Code over } \\Bold{F}_{2} \\textnormal{decoding up to 2 errors}\n ' return '\\textnormal{{Information-set decoder ({}) for }}{} \\textnormal{{decoding {} errors}}'.format(self.algorithm().name(), self.code()._latex_(), _format_decoding_interval(self.decoding_interval()))
def _dump_code_in_leon_format(C): "\n Writes a file in Sage's temp directory representing the code C, returning\n the absolute path to the file.\n\n This is the Sage translation of the GuavaToLeon command in Guava's\n codefun.gi file.\n\n INPUT:\n\n - ``C`` - a linear code (over GF(p), p < 11)\n\n OUTPUT:\n\n - Absolute path to the file written\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3); C\n [7, 4] Hamming Code over GF(2)\n sage: file_loc = sage.coding.linear_code._dump_code_in_leon_format(C)\n sage: f = open(file_loc); print(f.read())\n LIBRARY code;\n code=seq(2,4,7,seq(\n 1,0,0,0,0,1,1,\n 0,1,0,0,1,0,1,\n 0,0,1,0,1,1,0,\n 0,0,0,1,1,1,1\n ));\n FINISH;\n sage: f.close()\n\n " from sage.misc.temporary_file import tmp_filename F = C.base_ring() p = F.order() s = ('LIBRARY code;\n' + ('code=seq(%s,%s,%s,seq(\n' % (p, C.dimension(), C.length()))) Gr = [str(r)[1:(- 1)].replace(' ', '') for r in C.generator_matrix().rows()] s += (',\n'.join(Gr) + '\n));\nFINISH;') file_loc = tmp_filename() f = open(file_loc, 'w') f.write(s) f.close() return file_loc
class AbstractLinearCode(AbstractLinearCodeNoMetric): '\n Abstract base class for linear codes.\n\n This class contains all methods that can be used on Linear Codes and on\n Linear Codes families. So, every Linear Code-related class should inherit\n from this abstract class.\n\n To implement a linear code, you need to:\n\n - inherit from :class:`AbstractLinearCode`\n\n - call :class:`AbstractLinearCode` ``__init__`` method in the subclass constructor. Example:\n ``super().__init__(base_field, length, "EncoderName", "DecoderName")``.\n By doing that, your subclass will have its ``length`` parameter\n initialized and will be properly set as a member of the category framework.\n You need of course to complete the constructor by adding any additional parameter\n needed to describe properly the code defined in the subclass.\n\n - Add the following two lines on the class level::\n\n _registered_encoders = {}\n _registered_decoders = {}\n\n\n - fill the dictionary of its encoders in ``sage.coding.__init__.py`` file. Example:\n I want to link the encoder ``MyEncoderClass`` to ``MyNewCodeClass``\n under the name ``MyEncoderName``.\n All I need to do is to write this line in the ``__init__.py`` file:\n ``MyNewCodeClass._registered_encoders["NameOfMyEncoder"] = MyEncoderClass`` and all instances of\n ``MyNewCodeClass`` will be able to use instances of ``MyEncoderClass``.\n\n - fill the dictionary of its decoders in ``sage.coding.__init__`` file. Example:\n I want to link the encoder ``MyDecoderClass`` to ``MyNewCodeClass``\n under the name ``MyDecoderName``.\n All I need to do is to write this line in the ``__init__.py`` file:\n ``MyNewCodeClass._registered_decoders["NameOfMyDecoder"] = MyDecoderClass`` and all instances of\n ``MyNewCodeClass`` will be able to use instances of ``MyDecoderClass``.\n\n\n As the class :class:`AbstractLinearCode` is not designed to be instantiated, it does not have any representation\n methods. You should implement ``_repr_`` and ``_latex_`` methods in the subclass.\n\n .. NOTE::\n\n :class:`AbstractLinearCode` has a generic implementation of the\n method ``__eq__`` which uses the generator matrix and is quite\n slow. In subclasses you are encouraged to override ``__eq__``\n and ``__hash__``.\n\n .. WARNING::\n\n The default encoder should always have `F^{k}` as message space, with `k` the dimension\n of the code and `F` is the base ring of the code.\n\n A lot of methods of the abstract class rely on the knowledge of a generator matrix.\n It is thus strongly recommended to set an encoder with a generator matrix implemented\n as a default encoder.\n\n ' _registered_encoders = {} _registered_decoders = {} def __init__(self, base_field, length, default_encoder_name, default_decoder_name): '\n Initializes mandatory parameters that any linear code shares.\n\n This method only exists for inheritance purposes as it initializes\n parameters that need to be known by every linear code. The class\n :class:`sage.coding.linear_code.AbstractLinearCode` should never be\n directly instantiated.\n\n INPUT:\n\n - ``base_field`` -- the base field of ``self``\n\n - ``length`` -- the length of ``self`` (a Python int or a Sage Integer, must be > 0)\n\n - ``default_encoder_name`` -- the name of the default encoder of ``self``\n\n - ``default_decoder_name`` -- the name of the default decoder of ``self``\n\n EXAMPLES:\n\n The following example demonstrates how to subclass `AbstractLinearCode`\n for representing a new family of codes. The example family is non-sensical::\n\n sage: class MyCodeFamily(sage.coding.linear_code.AbstractLinearCode):\n ....: def __init__(self, field, length, dimension, generator_matrix):\n ....: super().__init__(field, length,\n ....: "GeneratorMatrix", "Syndrome")\n ....: self._dimension = dimension\n ....: self._generator_matrix = generator_matrix\n ....: def generator_matrix(self):\n ....: return self._generator_matrix\n ....: def _repr_(self):\n ....: return "[%d, %d] dummy code over GF(%s)" % (self.length(), self.dimension(), self.base_field().cardinality())\n\n We now instantiate a member of our newly made code family::\n\n sage: generator_matrix = matrix(GF(17), 5, 10,\n ....: {(i,i):1 for i in range(5)})\n sage: C = MyCodeFamily(GF(17), 10, 5, generator_matrix)\n\n We can check its existence and parameters::\n\n sage: C\n [10, 5] dummy code over GF(17)\n\n We can check that it is truly a part of the framework category::\n\n sage: C.parent()\n <class \'__main__.MyCodeFamily_with_category\'>\n sage: C.category()\n Category of facade finite dimensional vector spaces with basis over Finite Field of size 17\n\n And any method that works on linear codes works for our new dummy code::\n\n sage: C.minimum_distance()\n 1\n sage: C.is_self_orthogonal()\n False\n sage: print(C.divisor()) #long time\n 1\n ' from sage.coding.information_set_decoder import LinearCodeInformationSetDecoder self._registered_decoders['Syndrome'] = LinearCodeSyndromeDecoder self._registered_decoders['NearestNeighbor'] = LinearCodeNearestNeighborDecoder self._registered_decoders['InformationSet'] = LinearCodeInformationSetDecoder self._generic_constructor = LinearCode super().__init__(base_field, length, default_encoder_name, default_decoder_name) def _an_element_(self): '\n Return an element of the linear code. Currently, it simply returns\n the first row of the generator matrix.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: C.an_element()\n (1, 0, 0, 0, 0, 1, 1)\n sage: C2 = C.cartesian_product(C)\n sage: C2.an_element()\n ((1, 0, 0, 0, 0, 1, 1), (1, 0, 0, 0, 0, 1, 1))\n ' return self.gens()[0] def automorphism_group_gens(self, equivalence='semilinear'): '\n Return generators of the automorphism group of ``self``.\n\n INPUT:\n\n - ``equivalence`` (optional) -- which defines the acting group, either\n\n * ``"permutational"``\n\n * ``"linear"``\n\n * ``"semilinear"``\n\n OUTPUT:\n\n - generators of the automorphism group of ``self``\n - the order of the automorphism group of ``self``\n\n EXAMPLES:\n\n Note, this result can depend on the PRNG state in libgap in a way that\n depends on which packages are loaded, so we must re-seed GAP to ensure\n a consistent result for this example::\n\n sage: libgap.set_seed(0) # optional - sage.libs.gap\n 0\n sage: C = codes.HammingCode(GF(4, \'z\'), 3)\n sage: C.automorphism_group_gens()\n ([((1, 1, 1, z, z + 1, 1, 1, 1, 1, z + 1, z, z, z + 1, z + 1,\n z + 1, 1, z + 1, z, z, 1, z);\n (1,13,14,20)(2,21,8,18,7,16,19,15)(3,10,5,12,17,9,6,4),\n Ring endomorphism of Finite Field in z of size 2^2\n Defn: z |--> z + 1),\n ((z, 1, z, z, z, z + 1, z, z, z, z, z, z, z + 1, z, z, z,\n z, z + 1, z, z, z);\n (1,11,5,12,3,19)(2,8)(6,18,13)(7,17,15)(9,10,14,16,20,21),\n Ring endomorphism of Finite Field in z of size 2^2\n Defn: z |--> z + 1),\n ((z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z);\n (),\n Ring endomorphism of Finite Field in z of size 2^2\n Defn: z |--> z)],\n 362880)\n sage: C.automorphism_group_gens(equivalence="linear")\n ([((z, 1, z + 1, z + 1, 1, z + 1, z, 1, z + 1, z + 1, 1, z, 1, z + 1,\n z, 1, z, 1, z + 1, 1, 1);\n (1,12,11,10,6,8,9,20,13,21,5,14,3,16,17,19,7,4,2,15,18),\n Ring endomorphism of Finite Field in z of size 2^2\n Defn: z |--> z),\n ((z + 1, z + 1, z + 1, z, 1, 1, z, z, 1, z + 1, z, 1, 1, z, 1, z + 1,\n z, z + 1, z + 1, 1, z);\n (1,3,18,2,17,6,19)(4,15,13,20,7,14,16)(5,11,8,21,12,9,10),\n Ring endomorphism of Finite Field in z of size 2^2\n Defn: z |--> z),\n ((z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1,\n z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1, z + 1);\n (),\n Ring endomorphism of Finite Field in z of size 2^2\n Defn: z |--> z)],\n 181440)\n sage: C.automorphism_group_gens(equivalence="permutational")\n ([((1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n (1,11)(3,10)(4,9)(5,7)(12,21)(14,20)(15,19)(16,17),\n Ring endomorphism of Finite Field in z of size 2^2\n Defn: z |--> z),\n ((1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n (2,18)(3,19)(4,10)(5,16)(8,13)(9,14)(11,21)(15,20),\n Ring endomorphism of Finite Field in z of size 2^2\n Defn: z |--> z),\n ((1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n (1,19)(3,17)(4,21)(5,20)(7,14)(9,12)(10,16)(11,15),\n Ring endomorphism of Finite Field in z of size 2^2\n Defn: z |--> z),\n ((1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n (2,13)(3,14)(4,20)(5,11)(8,18)(9,19)(10,15)(16,21),\n Ring endomorphism of Finite Field in z of size 2^2\n Defn: z |--> z)],\n 64)\n ' aut_group_can_label = self._canonize(equivalence) return (aut_group_can_label.get_autom_gens(), aut_group_can_label.get_autom_order()) def assmus_mattson_designs(self, t, mode=None): '\n Assmus and Mattson Theorem (section 8.4, page 303 of [HP2003]_): Let\n `A_0, A_1, ..., A_n` be the weights of the codewords in a binary\n linear `[n , k, d]` code `C`, and let `A_0^*, A_1^*, ..., A_n^*` be\n the weights of the codewords in its dual `[n, n-k, d^*]` code `C^*`.\n Fix a `t`, `0<t<d`, and let\n\n .. MATH::\n\n s = |\\{ i\\ |\\ A_i^* \\not= 0, 0< i \\leq n-t\\}|.\n\n Assume `s\\leq d-t`.\n\n 1. If `A_i\\not= 0` and `d\\leq i\\leq n`\n then `C_i = \\{ c \\in C\\ |\\ wt(c) = i\\}` holds a simple t-design.\n\n 2. If `A_i^*\\not= 0` and `d*\\leq i\\leq n-t` then\n `C_i^* = \\{ c \\in C^*\\ |\\ wt(c) = i\\}` holds a simple t-design.\n\n A block design is a pair `(X,B)`, where `X` is a non-empty finite set\n of `v>0` elements called points, and `B` is a non-empty finite\n multiset of size b whose elements are called blocks, such that each\n block is a non-empty finite multiset of `k` points. `A` design without\n repeated blocks is called a simple block design. If every subset of\n points of size `t` is contained in exactly `\\lambda` blocks the block\n design is called a `t-(v,k,\\lambda)` design (or simply a `t`-design\n when the parameters are not specified). When `\\lambda=1` then the\n block design is called a `S(t,k,v)` Steiner system.\n\n In the Assmus and Mattson Theorem (1), `X` is the set `\\{1,2,...,n\\}`\n of coordinate locations and `B = \\{supp(c)\\ |\\ c \\in C_i\\}` is the set\n of supports of the codewords of `C` of weight `i`. Therefore, the\n parameters of the `t`-design for `C_i` are\n\n ::\n\n t = given\n v = n\n k = i (k not to be confused with dim(C))\n b = Ai\n lambda = b*binomial(k,t)/binomial(v,t) (by Theorem 8.1.6,\n p 294, in [HP2003]_)\n\n Setting the ``mode="verbose"`` option prints out the values of the\n parameters.\n\n The first example below means that the binary [24,12,8]-code C has\n the property that the (support of the) codewords of weight 8 (resp.,\n 12, 16) form a 5-design. Similarly for its dual code `C^*` (of course\n `C=C^*` in this case, so this info is extraneous). The test fails to\n produce 6-designs (ie, the hypotheses of the theorem fail to hold,\n not that the 6-designs definitely don\'t exist). The command\n ``assmus_mattson_designs(C,5,mode="verbose")`` returns the same value\n but prints out more detailed information.\n\n The second example below illustrates the blocks of the 5-(24, 8, 1)\n design (i.e., the S(5,8,24) Steiner system).\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2)) # example 1\n sage: C.assmus_mattson_designs(5)\n [\'weights from C: \', [8, 12, 16, 24],\n \'designs from C: \', [[5, (24, 8, 1)], [5, (24, 12, 48)], [5, (24, 16, 78)],\n [5, (24, 24, 1)]],\n \'weights from C*: \', [8, 12, 16],\n \'designs from C*: \', [[5, (24, 8, 1)], [5, (24, 12, 48)], [5, (24, 16, 78)]]]\n sage: C.assmus_mattson_designs(6)\n 0\n sage: X = range(24) # example 2\n sage: blocks = [c.support() for c in C if c.hamming_weight()==8]; len(blocks) # long time computation\n 759\n ' C = self ans = [] G = C.generator_matrix() n = len(G.columns()) Cp = C.dual_code() wts = C.weight_distribution() d = min([i for i in range(1, len(wts)) if (wts[i] != 0)]) if (t >= d): return 0 nonzerowts = [i for i in range(len(wts)) if ((wts[i] != 0) and (i <= n) and (i >= d))] if (mode == 'verbose'): for w in nonzerowts: print('The weight w={} codewords of C* form a t-(v,k,lambda) design, where\n t={}, v={}, k={}, lambda={}. \nThere are {} block of this design.'.format(w, t, n, w, ((wts[w] * binomial(w, t)) // binomial(n, t)), wts[w])) wtsp = Cp.weight_distribution() dp = min([i for i in range(1, len(wtsp)) if (wtsp[i] != 0)]) nonzerowtsp = [i for i in range(len(wtsp)) if ((wtsp[i] != 0) and (i <= (n - t)) and (i >= dp))] s = len([i for i in range(1, n) if ((wtsp[i] != 0) and (i <= (n - t)) and (i > 0))]) if (mode == 'verbose'): for w in nonzerowtsp: print('The weight w={} codewords of C* form a t-(v,k,lambda) design, where\n t={}, v={}, k={}, lambda={}. \nThere are {} block of this design.'.format(w, t, n, w, ((wts[w] * binomial(w, t)) // binomial(n, t)), wts[w])) if (s <= (d - t)): des = [[t, (n, w, ((wts[w] * binomial(w, t)) // binomial(n, t)))] for w in nonzerowts] ans = (ans + ['weights from C: ', nonzerowts, 'designs from C: ', des]) desp = [[t, (n, w, ((wtsp[w] * binomial(w, t)) // binomial(n, t)))] for w in nonzerowtsp] ans = (ans + ['weights from C*: ', nonzerowtsp, 'designs from C*: ', desp]) return ans return 0 def binomial_moment(self, i): '\n Return the i-th binomial moment of the `[n,k,d]_q`-code `C`:\n\n .. MATH::\n\n B_i(C) = \\sum_{S, |S|=i} \\frac{q^{k_S}-1}{q-1}\n\n where `k_S` is the dimension of the shortened code `C_{J-S}`,\n `J=[1,2,...,n]`. (The normalized binomial moment is\n `b_i(C) = \\binom{n}{d+i})^{-1}B_{d+i}(C)`.) In other words, `C_{J-S}`\n is isomorphic to the subcode of C of codewords supported on S.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: C.binomial_moment(2)\n 0\n sage: C.binomial_moment(4) # long time\n 35\n\n .. warning::\n\n This is slow.\n\n REFERENCE:\n\n - [Du2004]_\n ' n = self.length() k = self.dimension() d = self.minimum_distance() F = self.base_ring() q = F.order() J = range(1, (n + 1)) Cp = self.dual_code() dp = Cp.minimum_distance() if (i < d): return 0 if ((i > (n - dp)) and (i <= n)): return ((binomial(n, i) * ((q ** ((i + k) - n)) - 1)) // (q - 1)) from sage.combinat.set_partition import SetPartitions P = SetPartitions(J, 2).list() b = QQ(0) for p in P: p = list(p) S = p[0] if (len(S) == (n - i)): C_S = self.shortened(S) k_S = C_S.dimension() b = (b + (((q ** k_S) - 1) // (q - 1))) return b @cached_method def _canonize(self, equivalence): '\n Compute a canonical representative and the automorphism group\n under the action of the semimonomial transformation group.\n\n INPUT:\n\n - ``equivalence`` -- which defines the acting group, either\n\n * ``permutational``\n\n * ``linear``\n\n * ``semilinear``\n\n EXAMPLES:\n\n Note, this result can depend on the PRNG state in libgap in a way that\n depends on which packages are loaded, so we must re-seed GAP to ensure\n a consistent result for this example::\n\n sage: libgap.set_seed(0)\n 0\n sage: C = codes.HammingCode(GF(4, \'z\'), 3)\n sage: aut_group_can_label = C._canonize("semilinear")\n sage: C_iso = LinearCode(aut_group_can_label.get_transporter()*C.generator_matrix())\n sage: C_iso == aut_group_can_label.get_canonical_form()\n True\n sage: aut_group_can_label.get_autom_gens()\n [((1, 1, 1, z, z + 1, 1, 1, 1, 1, z + 1, z, z, z + 1, z + 1, z + 1, 1, z + 1, z, z, 1, z); (1,13,14,20)(2,21,8,18,7,16,19,15)(3,10,5,12,17,9,6,4), Ring endomorphism of Finite Field in z of size 2^2\n Defn: z |--> z + 1),\n ((z, 1, z, z, z, z + 1, z, z, z, z, z, z, z + 1, z, z, z, z, z + 1, z, z, z); (1,11,5,12,3,19)(2,8)(6,18,13)(7,17,15)(9,10,14,16,20,21), Ring endomorphism of Finite Field in z of size 2^2\n Defn: z |--> z + 1),\n ((z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z, z); (), Ring endomorphism of Finite Field in z of size 2^2\n Defn: z |--> z)]\n ' from sage.coding.codecan.autgroup_can_label import LinearCodeAutGroupCanLabel return LinearCodeAutGroupCanLabel(self, algorithm_type=equivalence) def canonical_representative(self, equivalence='semilinear'): '\n Compute a canonical orbit representative under the action of the\n semimonomial transformation group.\n\n See :mod:`sage.coding.codecan.autgroup_can_label`\n for more details, for example if you would like to compute\n a canonical form under some more restrictive notion of equivalence,\n i.e. if you would like to restrict the permutation group\n to a Young subgroup.\n\n INPUT:\n\n - ``equivalence`` (optional) -- which defines the acting group, either\n\n * ``"permutational"``\n\n * ``"linear"``\n\n * ``"semilinear"``\n\n OUTPUT:\n\n - a canonical representative of ``self``\n - a semimonomial transformation mapping ``self`` onto its representative\n\n EXAMPLES::\n\n sage: F.<z> = GF(4)\n sage: C = codes.HammingCode(F, 3)\n sage: CanRep, transp = C.canonical_representative()\n\n Check that the transporter element is correct::\n\n sage: LinearCode(transp*C.generator_matrix()) == CanRep\n True\n\n Check if an equivalent code has the same canonical representative::\n\n sage: f = F.hom([z**2])\n sage: C_iso = LinearCode(C.generator_matrix().apply_map(f))\n sage: CanRep_iso, _ = C_iso.canonical_representative()\n sage: CanRep_iso == CanRep\n True\n\n Since applying the Frobenius automorphism could be extended to an\n automorphism of `C`, the following must also yield ``True``::\n\n sage: CanRep1, _ = C.canonical_representative("linear")\n sage: CanRep2, _ = C_iso.canonical_representative("linear")\n sage: CanRep2 == CanRep1\n True\n\n TESTS:\n\n Check that interrupting this does not segfault\n (see :trac:`21651`)::\n\n sage: C = LinearCode(random_matrix(GF(47), 25, 35))\n sage: alarm(0.5); C.canonical_representative()\n Traceback (most recent call last):\n ...\n AlarmInterrupt\n ' aut_group_can_label = self._canonize(equivalence) return (aut_group_can_label.get_canonical_form(), aut_group_can_label.get_transporter()) def characteristic(self): '\n Return the characteristic of the base ring of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: C.characteristic()\n 2\n ' return self.base_ring().characteristic() def characteristic_polynomial(self): '\n Return the characteristic polynomial of a linear code, as defined in\n [Lin1999]_.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: C.characteristic_polynomial()\n -4/3*x^3 + 64*x^2 - 2816/3*x + 4096\n ' R = PolynomialRing(QQ, 'x') x = R.gen() C = self Cd = C.dual_code() Sd = Cd.support() k = C.dimension() n = C.length() q = C.base_ring().order() return ((q ** (n - k)) * prod([(1 - (x / j)) for j in Sd if (j > 0)])) def chinen_polynomial(self): '\n Return the Chinen zeta polynomial of the code.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: C.chinen_polynomial() # long time\n 1/5*(2*sqrt(2)*t^3 + 2*sqrt(2)*t^2 + 2*t^2 + sqrt(2)*t + 2*t + 1)/(sqrt(2) + 1)\n sage: C = codes.GolayCode(GF(3), False)\n sage: C.chinen_polynomial() # long time\n 1/7*(3*sqrt(3)*t^3 + 3*sqrt(3)*t^2 + 3*t^2 + sqrt(3)*t + 3*t + 1)/(sqrt(3) + 1)\n\n This last output agrees with the corresponding example given in\n Chinen\'s paper below.\n\n REFERENCES:\n\n - Chinen, K. "An abundance of invariant polynomials satisfying the\n Riemann hypothesis", April 2007 preprint.\n ' from sage.misc.functional import sqrt C = self n = C.length() RT = PolynomialRing(QQ, 2, 'Ts') (T, s) = RT.fraction_field().gens() t = PolynomialRing(QQ, 't').gen() Cd = C.dual_code() k = C.dimension() q = C.base_ring().characteristic() d = C.minimum_distance() dperp = Cd.minimum_distance() if (dperp > d): P = RT(C.zeta_polynomial()) if is_even(n): Pd = (((q ** (k - (n // 2))) * RT(Cd.zeta_polynomial())) * (T ** (dperp - d))) else: Pd = (((s * (q ** (k - ((n + 1) // 2)))) * RT(Cd.zeta_polynomial())) * (T ** (dperp - d))) CP = (P + Pd) f = (CP / CP(1, s)) return f(t, sqrt(q)) if (dperp < d): P = (RT(C.zeta_polynomial()) * (T ** (d - dperp))) if is_even(n): Pd = ((q ** (k - (n / 2))) * RT(Cd.zeta_polynomial())) if (not is_even(n)): Pd = ((s * (q ** (k - ((n + 1) / 2)))) * RT(Cd.zeta_polynomial())) CP = (P + Pd) f = (CP / CP(1, s)) return f(t, sqrt(q)) if (dperp == d): P = RT(C.zeta_polynomial()) if is_even(n): Pd = ((q ** (k - (n / 2))) * RT(Cd.zeta_polynomial())) if (not is_even(n)): Pd = ((s * (q ** (k - ((n + 1) / 2)))) * RT(Cd.zeta_polynomial())) CP = (P + Pd) f = (CP / CP(1, s)) return f(t, sqrt(q)) @cached_method def covering_radius(self): '\n Return the minimal integer `r` such that any element in the ambient space of ``self`` has distance at most `r` to a codeword of ``self``.\n\n This method requires the optional GAP package Guava.\n\n If the covering radius a code equals its minimum distance, then the code is called perfect.\n\n .. NOTE::\n\n This method is currently not implemented on codes over base fields\n of cardinality greater than 256 due to limitations in the underlying\n algorithm of GAP.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 5)\n sage: C.covering_radius() # optional - gap_package_guava\n ...1\n\n sage: C = codes.random_linear_code(GF(263), 5, 1)\n sage: C.covering_radius() # optional - gap_package_guava\n Traceback (most recent call last):\n ...\n NotImplementedError: the GAP algorithm that Sage is using\n is limited to computing with fields of size at most 256\n ' from sage.libs.gap.libgap import libgap GapPackage('guava', spkg='gap_packages').require() libgap.LoadPackage('guava') F = self.base_ring() if (F.cardinality() > 256): raise NotImplementedError('the GAP algorithm that Sage is using is limited to computing with fields of size at most 256') gapG = libgap(self.generator_matrix()) C = gapG.GeneratorMatCode(libgap(F)) r = C.CoveringRadius() try: return ZZ(r) except TypeError: raise RuntimeError('the covering radius of this code cannot be computed by Guava') def divisor(self): '\n Return the greatest common divisor of the weights of the nonzero codewords.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2))\n sage: C.divisor() # Type II self-dual\n 4\n sage: C = codes.QuadraticResidueCodeEvenPair(17, GF(2))[0]\n sage: C.divisor()\n 2\n ' C = self A = C.weight_distribution() n = C.length() V = VectorSpace(QQ, (n + 1)) S = V(A).nonzero_positions() S0 = [S[i] for i in range(1, len(S))] if (len(S) > 1): return GCD(S0) return 1 def is_projective(self): '\n Test whether the code is projective.\n\n A linear code `C` over a field is called *projective* when its dual `Cd`\n has minimum weight `\\geq 3`, i.e. when no two coordinate positions of\n `C` are linearly independent (cf. definition 3 from [BS2011]_ or 9.8.1 from\n [BH2012]_).\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(2), False)\n sage: C.is_projective()\n True\n sage: C.dual_code().minimum_distance()\n 8\n\n A non-projective code::\n\n sage: C = codes.LinearCode(matrix(GF(2), [[1,0,1],[1,1,1]]))\n sage: C.is_projective()\n False\n ' M = self.generator_matrix().transpose() def projectivize(row): if (not row.is_zero()): for i in range(len(row)): if row[i]: break row = ((~ row[i]) * row) row.set_immutable() return row rows = set() for row in M.rows(): row = projectivize(row) if (row in rows): return False rows.add(row) return True def direct_sum(self, other): '\n Return the direct sum of the codes ``self`` and ``other``.\n\n This returns the code given by the direct sum of the codes ``self`` and\n ``other``, which must be linear codes defined over the same base ring.\n\n EXAMPLES::\n\n sage: C1 = codes.HammingCode(GF(2), 3)\n sage: C2 = C1.direct_sum(C1); C2\n [14, 8] linear code over GF(2)\n sage: C3 = C1.direct_sum(C2); C3\n [21, 12] linear code over GF(2)\n ' C1 = self C2 = other G1 = C1.generator_matrix() G2 = C2.generator_matrix() F = C1.base_ring() n1 = len(G1.columns()) k1 = len(G1.rows()) n2 = len(G2.columns()) k2 = len(G2.rows()) MS1 = MatrixSpace(F, k2, n1) MS2 = MatrixSpace(F, k1, n2) Z1 = MS1(0) Z2 = MS2(0) top = G1.augment(Z2) bottom = Z1.augment(G2) G = top.stack(bottom) return LinearCode(G) def juxtapose(self, other): '\n Juxtaposition of ``self`` and ``other``\n\n The two codes must have equal dimension.\n\n EXAMPLES::\n\n sage: C1 = codes.HammingCode(GF(2), 3)\n sage: C2 = C1.juxtapose(C1)\n sage: C2\n [14, 4] linear code over GF(2)\n ' G1 = self.generator_matrix() G2 = other.generator_matrix() G = G1.augment(G2) return LinearCode(G) def u_u_plus_v_code(self, other): '\n Return the `(u|u+v)`-construction with ``self=u`` and ``other=v``.\n\n This returns the code obtained through `(u|u+v)`-construction with ``self`` as `u`\n and ``other`` as `v`. Note that `u` and `v` must have equal lengths.\n For `u` a `[n, k_1, d_1]`-code and `v` a `[n, k_2, d_2]`-code this returns\n a `[2n, k_1+k_2, d]`-code, where `d=\\min(2d_1,d_2)`.\n\n EXAMPLES::\n\n sage: C1 = codes.HammingCode(GF(2), 3)\n sage: C2 = codes.HammingCode(GF(2), 3)\n sage: D = C1.u_u_plus_v_code(C2)\n sage: D\n [14, 8] linear code over GF(2)\n ' F = self.base_ring() G1 = self.generator_matrix() G2 = other.generator_matrix() k2 = len(G2.rows()) n2 = len(G2.columns()) MS = MatrixSpace(F, k2, n2) Z = MS(0) top = G1.augment(G1) bot = Z.augment(G2) G = top.stack(bot) return LinearCode(G) def product_code(self, other): '\n Combines ``self`` with ``other`` to give the tensor product code.\n\n If ``self`` is a `[n_1, k_1, d_1]`-code and ``other`` is\n a `[n_2, k_2, d_2]`-code, the product is a `[n_1n_2, k_1k_2, d_1d_2]`-code.\n\n Note that the two codes have to be over the same field.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: C\n [7, 4] Hamming Code over GF(2)\n sage: D = codes.ReedMullerCode(GF(2), 2, 2)\n sage: D\n Binary Reed-Muller Code of order 2 and number of variables 2\n sage: A = C.product_code(D)\n sage: A\n [28, 16] linear code over GF(2)\n sage: A.length() == C.length()*D.length()\n True\n sage: A.dimension() == C.dimension()*D.dimension()\n True\n sage: A.minimum_distance() == C.minimum_distance()*D.minimum_distance()\n True\n\n ' G1 = self.generator_matrix() G2 = other.generator_matrix() G = G1.tensor_product(G2) return LinearCode(G) def construction_x(self, other, aux): '\n Construction X applied to ``self=C_1``, ``other=C_2`` and ``aux=C_a``.\n\n ``other`` must be a subcode of ``self``.\n\n If `C_1` is a `[n, k_1, d_1]` linear code and `C_2` is\n a `[n, k_2, d_2]` linear code, then `k_1 > k_2` and `d_1 < d_2`. `C_a` must\n be a `[n_a, k_a, d_a]` linear code, such that `k_a + k_2 = k_1`\n and `d_a + d_1 \\leq d_2`.\n\n The method will then return a `[n+n_a, k_1, d_a+d_1]` linear code.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(2),15,7)\n sage: C\n [15, 5] BCH Code over GF(2) with designed distance 7\n sage: D = codes.BCHCode(GF(2),15,5)\n sage: D\n [15, 7] BCH Code over GF(2) with designed distance 5\n sage: C.is_subcode(D)\n True\n sage: C.minimum_distance()\n 7\n sage: D.minimum_distance()\n 5\n sage: aux = codes.HammingCode(GF(2),2)\n sage: aux = aux.dual_code()\n sage: aux.minimum_distance()\n 2\n sage: Cx = D.construction_x(C,aux)\n sage: Cx\n [18, 7] linear code over GF(2)\n sage: Cx.minimum_distance()\n 7\n ' if (not other.is_subcode(self)): raise ValueError(('%s is not a subcode of %s' % (self, other))) G2 = self.generator_matrix() left = other.generator_matrix() k = self.dimension() for r in G2.rows(): if (r not in left.row_space()): left = left.stack(r) Ga = aux.generator_matrix() na = aux.length() ka = aux.dimension() F = self.base_field() MS = MatrixSpace(F, (k - ka), na) Z = MS(0) right = Z.stack(Ga) G = left.augment(right) return LinearCode(G) def extended_code(self): "\n Return ``self`` as an extended code.\n\n See documentation of :class:`sage.coding.extended_code.ExtendedCode`\n for details.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(4,'a'), 3)\n sage: C\n [21, 18] Hamming Code over GF(4)\n sage: Cx = C.extended_code()\n sage: Cx\n Extension of [21, 18] Hamming Code over GF(4)\n " from .extended_code import ExtendedCode return ExtendedCode(self) def galois_closure(self, F0): "\n If ``self`` is a linear code defined over `F` and `F_0` is a subfield\n with Galois group `G = Gal(F/F_0)` then this returns the `G`-module\n `C^-` containing `C`.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(4,'a'), 3)\n sage: Cc = C.galois_closure(GF(2))\n sage: C; Cc\n [21, 18] Hamming Code over GF(4)\n [21, 20] linear code over GF(4)\n sage: c = C.basis()[2]\n sage: V = VectorSpace(GF(4,'a'),21)\n sage: c2 = V([x^2 for x in c.list()])\n sage: c2 in C\n False\n sage: c2 in Cc\n True\n " G = self.generator_matrix() F = self.base_ring() q = F.order() q0 = F0.order() a = q.log(q0) if (not isinstance(a, Integer)): raise ValueError(('Base field must be an extension of given field %s' % F0)) n = len(G.columns()) k = len(G.rows()) G0 = [[(x ** q0) for x in g.list()] for g in G.rows()] G1 = [list(g.list()) for g in G.rows()] G2 = (G0 + G1) MS = MatrixSpace(F, (2 * k), n) G3 = MS(G2) r = G3.rank() MS = MatrixSpace(F, r, n) Grref = G3.echelon_form() G = MS([Grref.row(i) for i in range(r)]) return LinearCode(G) def genus(self): '\n Return the "Duursma genus" of the code, `\\gamma_C = n+1-k-d`.\n\n EXAMPLES::\n\n sage: C1 = codes.HammingCode(GF(2), 3); C1\n [7, 4] Hamming Code over GF(2)\n sage: C1.genus()\n 1\n sage: C2 = codes.HammingCode(GF(4,"a"), 2); C2\n [5, 3] Hamming Code over GF(4)\n sage: C2.genus()\n 0\n\n Since all Hamming codes have minimum distance 3, these computations\n agree with the definition, `n+1-k-d`.\n ' d = self.minimum_distance() n = self.length() k = self.dimension() gammaC = (((n + 1) - k) - d) return gammaC def is_permutation_equivalent(self, other, algorithm=None): '\n Return ``True`` if ``self`` and ``other`` are permutation equivalent\n codes and ``False`` otherwise.\n\n The ``algorithm="verbose"`` option also returns a permutation (if\n ``True``) sending ``self`` to ``other``.\n\n Uses Robert Miller\'s double coset partition refinement work.\n\n EXAMPLES::\n\n sage: P.<x> = PolynomialRing(GF(2),"x")\n sage: g = x^3 + x + 1\n sage: C1 = codes.CyclicCode(length=7, generator_pol=g); C1\n [7, 4] Cyclic Code over GF(2)\n sage: C2 = codes.HammingCode(GF(2), 3); C2\n [7, 4] Hamming Code over GF(2)\n sage: C1.is_permutation_equivalent(C2)\n True\n sage: C1.is_permutation_equivalent(C2, algorithm="verbose")\n (True, (3,4)(5,7,6))\n sage: C1 = codes.random_linear_code(GF(2), 10, 5)\n sage: C2 = codes.random_linear_code(GF(3), 10, 5)\n sage: C1.is_permutation_equivalent(C2)\n False\n ' from sage.groups.perm_gps.partn_ref.refinement_binary import NonlinearBinaryCodeStruct F = self.base_ring() F_o = other.base_ring() q = F.order() G = self.generator_matrix() n = self.length() n_o = other.length() if ((F != F_o) or (n != n_o)): return False k = len(G.rows()) MS = MatrixSpace(F, (q ** k), n) CW1 = MS(self.list()) CW2 = MS(other.list()) B1 = NonlinearBinaryCodeStruct(CW1) B2 = NonlinearBinaryCodeStruct(CW2) ans = B1.is_isomorphic(B2) if (ans is not False): if (algorithm == 'verbose'): Sn = SymmetricGroup(n) return (True, (Sn([(i + 1) for i in ans]) ** (- 1))) return True return False def is_galois_closed(self): '\n Checks if ``self`` is equal to its Galois closure.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(4,"a"), 3)\n sage: C.is_galois_closed()\n False\n ' p = self.base_ring().characteristic() return (self == self.galois_closure(GF(p))) def _magma_init_(self, magma): '\n Return a string representation in Magma of this linear code.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: Cm = magma(C) # optional - magma, indirect doctest\n sage: Cm.MinimumWeight() # optional - magma\n 3\n ' G = magma(self.generator_matrix())._ref() return ('LinearCode(%s)' % G) @cached_method def minimum_distance(self, algorithm=None): '\n Return the minimum distance of ``self``.\n\n .. NOTE::\n\n When using GAP, this raises a :class:`NotImplementedError` if\n the base field of the code has size greater than 256 due\n to limitations in GAP.\n\n INPUT:\n\n - ``algorithm`` -- (default: ``None``) the name of the algorithm to use\n to perform minimum distance computation. ``algorithm`` can be:\n\n - ``None``, to use GAP methods (but not Guava)\n\n - ``"Guava"``, to use the optional GAP package Guava\n\n OUTPUT:\n\n - Integer, minimum distance of this code\n\n EXAMPLES::\n\n sage: MS = MatrixSpace(GF(3),4,7)\n sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: C.minimum_distance()\n 3\n\n If ``algorithm`` is provided, then the minimum distance will be\n recomputed even if there is a stored value from a previous run.::\n\n sage: C.minimum_distance(algorithm="gap") # optional - sage.libs.gap\n 3\n sage: libgap.SetAllInfoLevels(0) # to suppress extra info messages # optional - sage.libs.gap\n sage: C.minimum_distance(algorithm="guava") # optional - gap_package_guava\n ...3\n\n TESTS::\n\n sage: C = codes.random_linear_code(GF(4,"a"), 5, 2)\n sage: C.minimum_distance(algorithm=\'something\')\n Traceback (most recent call last):\n ...\n ValueError: The algorithm argument must be one of None, \'gap\' or \'guava\'; got \'something\'\n\n The field must be size at most 256::\n\n sage: C = codes.random_linear_code(GF(257,"a"), 5, 2)\n sage: C.minimum_distance()\n Traceback (most recent call last):\n ...\n NotImplementedError: the GAP algorithm that Sage is using\n is limited to computing with fields of size at most 256\n ' if (algorithm == 'guava'): GapPackage('guava', spkg='gap_packages').require() if (algorithm not in (None, 'gap', 'guava')): raise ValueError("The algorithm argument must be one of None, 'gap' or 'guava'; got '{0}'".format(algorithm)) F = self.base_ring() q = F.order() if (q > 256): raise NotImplementedError('the GAP algorithm that Sage is using is limited to computing with fields of size at most 256') G = self.generator_matrix() if (((q == 2) or (q == 3)) and (algorithm == 'guava')): from sage.libs.gap.libgap import libgap libgap.LoadPackage('guava') C = libgap(G).GeneratorMatCode(libgap(F)) d = C.MinimumWeight() return ZZ(d) return self._minimum_weight_codeword(algorithm).hamming_weight() def _minimum_weight_codeword(self, algorithm=None): '\n Return a minimum weight codeword of ``self``.\n\n INPUT:\n\n - ``algorithm`` -- (default: ``None``) the name of the algorithm to use\n to perform minimum weight codeword search. If set to ``None``,\n a search using GAP methods will be done. ``algorithm`` can be:\n - ``"Guava"``, which will use optional GAP package Guava\n\n REMARKS:\n\n - The code in the default case allows one (for free) to also compute the\n message vector `m` such that `m\\*G = v`, and the (minimum) distance, as\n a triple. however, this output is not implemented.\n - The binary case can presumably be done much faster using Robert Miller\'s\n code (see the docstring for the spectrum method). This is also not (yet)\n implemented.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: C._minimum_weight_codeword()\n (0, 1, 0, 1, 0, 1, 0)\n\n TESTS:\n\n We check that :trac:`18480` is fixed::\n\n sage: codes.HammingCode(GF(2), 2).minimum_distance()\n 3\n\n AUTHORS:\n\n - David Joyner (11-2005)\n ' from sage.libs.gap.libgap import libgap (n, k) = (self.length(), self.dimension()) F = self.base_field() Gmat = libgap(self.generator_matrix()) current_randstate().set_seed_gap() if (algorithm == 'guava'): GapPackage('guava', spkg='gap_packages').require() libgap.LoadPackage('guava') C = Gmat.GeneratorMatCode(F) cg = C.MinimumDistanceCodeword() c = [cg[j].sage(ring=F) for j in range(n)] return vector(F, c) q = F.order() ans = None dist_min = libgap((n + 1)) K = libgap.GF(q) v0 = (K ** n).Zero() for i in range(1, (k + 1)): v = Gmat.AClosestVectorCombinationsMatFFEVecFFECoords(K, v0, i, 1)[0] dist = v.WeightVecFFE() if (dist and (dist < dist_min)): dist_min = dist ans = list(v) if (ans is None): raise RuntimeError('Computation failed due to some GAP error') return vector(F, ans) def module_composition_factors(self, gp): '\n Print the GAP record of the Meataxe composition factors module.\n\n This is displayed in Meataxe notation.\n\n This uses GAP but not Guava.\n\n EXAMPLES::\n\n sage: MS = MatrixSpace(GF(2),4,8)\n sage: G = MS([[1,0,0,0,1,1,1,0], [0,1,1,1,0,0,0,0],\n ....: [0,0,0,0,0,0,0,1], [0,0,0,0,0,1,0,0]])\n sage: C = LinearCode(G)\n sage: gp = C.permutation_automorphism_group()\n sage: C.module_composition_factors(gp) # optional - sage.libs.gap\n [ rec(\n IsIrreducible := true,\n IsOverFiniteField := true,\n ...) ]\n ' from sage.libs.gap.libgap import libgap F = self.base_ring() gens = gp.gens() G = self.generator_matrix() n = G.ncols() MS = MatrixSpace(F, n, n) mats = [] Fn = VectorSpace(F, n) W = Fn.subspace_with_basis(G.rows()) for g in gens: p = MS(g.matrix()) m = [W.coordinate_vector((r * p)) for r in G.rows()] mats.append(m) mats_gap = libgap(mats) M_gap = mats_gap.GModuleByMats(F) return libgap.eval((('MTX.CompositionFactors(' + str(M_gap)) + ')')) def permutation_automorphism_group(self, algorithm='partition'): '\n If `C` is an `[n,k,d]` code over `F`, this function computes the\n subgroup `Aut(C) \\subset S_n` of all permutation automorphisms of `C`.\n The binary case always uses the (default) partition refinement\n algorithm of Robert Miller.\n\n Note that if the base ring of `C` is `GF(2)` then this is the full\n automorphism group. Otherwise, you could use\n :meth:`~sage.coding.linear_code.LinearCode.automorphism_group_gens`\n to compute generators of the full automorphism group.\n\n INPUT:\n\n - ``algorithm`` - If ``"gap"`` then GAP\'s MatrixAutomorphism function\n (written by Thomas Breuer) is used. The implementation combines an\n idea of mine with an improvement suggested by Cary Huffman. If\n ``"gap+verbose"`` then code-theoretic data is printed out at\n several stages of the computation. If ``"partition"`` then the\n (default) partition refinement algorithm of Robert Miller is used.\n Finally, if ``"codecan"`` then the partition refinement algorithm\n of Thomas Feulner is used, which also computes a canonical\n representative of ``self`` (call\n :meth:`~sage.coding.linear_code.LinearCode.canonical_representative`\n to access it).\n\n OUTPUT:\n\n - Permutation automorphism group\n\n EXAMPLES::\n\n sage: MS = MatrixSpace(GF(2),4,8)\n sage: G = MS([[1,0,0,0,1,1,1,0], [0,1,1,1,0,0,0,0],\n ....: [0,0,0,0,0,0,0,1], [0,0,0,0,0,1,0,0]])\n sage: C = LinearCode(G)\n sage: C\n [8, 4] linear code over GF(2)\n sage: G = C.permutation_automorphism_group() # optional - sage.groups\n sage: G.order() # optional - sage.groups\n 144\n sage: GG = C.permutation_automorphism_group("codecan") # optional - sage.groups\n sage: GG == G # optional - sage.groups\n True\n\n A less easy example involves showing that the permutation\n automorphism group of the extended ternary Golay code is the\n Mathieu group `M_{11}`.\n\n ::\n\n sage: C = codes.GolayCode(GF(3))\n sage: M11 = MathieuGroup(11) # optional - sage.groups\n sage: M11.order() # optional - sage.groups\n 7920\n sage: G = C.permutation_automorphism_group() # long time (6s on sage.math, 2011) # optional - sage.groups\n sage: G.is_isomorphic(M11) # long time # optional - sage.groups\n True\n sage: GG = C.permutation_automorphism_group("codecan") # long time # optional - sage.groups\n sage: GG == G # long time # optional - sage.groups\n True\n\n Other examples::\n\n sage: C = codes.GolayCode(GF(2))\n sage: G = C.permutation_automorphism_group() # optional - sage.groups\n sage: G.order() # optional - sage.groups\n 244823040\n sage: C = codes.HammingCode(GF(2), 5)\n sage: G = C.permutation_automorphism_group() # optional - sage.groups\n sage: G.order() # optional - sage.groups\n 9999360\n sage: C = codes.HammingCode(GF(3), 2); C\n [4, 2] Hamming Code over GF(3)\n sage: C.permutation_automorphism_group(algorithm="partition") # optional - sage.groups\n Permutation Group with generators [(1,3,4)]\n sage: C = codes.HammingCode(GF(4,"z"), 2); C\n [5, 3] Hamming Code over GF(4)\n sage: G = C.permutation_automorphism_group(algorithm="partition"); G # optional - sage.groups\n Permutation Group with generators [(1,3)(4,5), (1,4)(3,5)]\n sage: GG = C.permutation_automorphism_group(algorithm="codecan") # long time, optional - sage.groups\n sage: GG == G # long time, optional - sage.groups\n True\n sage: C.permutation_automorphism_group(algorithm="gap") # optional - gap_package_guava sage.groups\n Permutation Group with generators [(1,3)(4,5), (1,4)(3,5)]\n sage: C = codes.GolayCode(GF(3), True)\n sage: C.permutation_automorphism_group(algorithm="gap") # optional - gap_package_guava sage.groups\n Permutation Group with generators\n [(5,7)(6,11)(8,9)(10,12), (4,6,11)(5,8,12)(7,10,9), (3,4)(6,8)(9,11)(10,12),\n (2,3)(6,11)(8,12)(9,10), (1,2)(5,10)(7,12)(8,9)]\n\n However, the option ``algorithm="gap+verbose"``, will print out::\n\n Minimum distance: 5 Weight distribution: [1, 0, 0, 0, 0, 132, 132,\n 0, 330, 110, 0, 24]\n\n Using the 132 codewords of weight 5 Supergroup size: 39916800\n\n in addition to the output of\n ``C.permutation_automorphism_group(algorithm="gap")``.\n ' F = self.base_ring() q = F.order() G = (self.generator_matrix() if ((2 * self.dimension()) <= self.length()) else self.dual_code().generator_matrix()) n = len(G.columns()) if ('gap' in algorithm): from sage.libs.gap.libgap import libgap GapPackage('guava', spkg='gap_packages').require() libgap.LoadPackage('guava') wts = self.weight_distribution() nonzerowts = [i for i in range(len(wts)) if (wts[i] != 0)] Sn = libgap.SymmetricGroup(n) Sn_sage = SymmetricGroup(n) Gp = Sn C = libgap(G).GeneratorMatCode(libgap.GF(q)) eltsC = C.Elements() if (algorithm == 'gap+verbose'): print(('\n Minimum distance: %s \n Weight distribution: \n %s' % (nonzerowts[1], wts))) stop = 0 for i in range(1, len(nonzerowts)): if (stop == 1): break wt = nonzerowts[i] if (algorithm == 'gap+verbose'): size = Gp.Size() print(('\n Using the %s codewords of weight %s \n Supergroup size: \n %s\n ' % (wts[wt], wt, size))) Cwt = filter((lambda c: (c.WeightCodeword() == wt)), eltsC) matCwt = [c.VectorCodeword() for c in Cwt] if (len(matCwt) > 0): A = libgap(matCwt).MatrixAutomorphisms() Gp = A.Intersection2(Gp) if (Gp.Size() == 1): return PermutationGroup([()]) gens = Gp.GeneratorsOfGroup() stop = 1 for x in gens: if (not self.is_permutation_automorphism(Sn_sage(x))): stop = 0 break G = PermutationGroup(list(map(Sn_sage, gens))) return G if (algorithm == 'partition'): if (q == 2): from sage.groups.perm_gps.partn_ref.refinement_binary import LinearBinaryCodeStruct B = LinearBinaryCodeStruct(G) autgp = B.automorphism_group() L = [[(j + 1) for j in gen] for gen in autgp[0]] AutGp = PermutationGroup(L) else: from sage.groups.perm_gps.partn_ref.refinement_matrices import MatrixStruct from sage.matrix.constructor import matrix weights = {} for c in self: wt = c.hamming_weight() if (wt not in weights): weights[wt] = [c] else: weights[wt].append(c) weights.pop(0) AutGps = [] for (wt, words) in weights.items(): M = MatrixStruct(matrix(words)) autgp = M.automorphism_group() L = [[(j + 1) for j in gen] for gen in autgp[0]] G = PermutationGroup(L) AutGps.append(G) if (len(AutGps) > 0): AutGp = AutGps[0] for G in AutGps[1:]: AutGp = AutGp.intersection(G) else: return PermutationGroup([]) return AutGp if (algorithm == 'codecan'): (gens, _) = self.automorphism_group_gens('permutational') return PermutationGroup([x.get_perm() for x in gens]) raise NotImplementedError("The only algorithms implemented currently are 'gap', 'gap+verbose', and 'partition'.") def punctured(self, L): '\n Return a :class:`sage.coding.punctured_code` object from ``L``.\n\n INPUT:\n\n - ``L`` -- List of positions to puncture\n\n OUTPUT:\n\n - an instance of :class:`sage.coding.punctured_code`\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: C.punctured([1,2])\n Puncturing of [7, 4] Hamming Code over GF(2) on position(s) [1, 2]\n ' from .punctured_code import PuncturedCode return PuncturedCode(self, set(L)) def _punctured_form(self, points): '\n Return a representation of self as a :class:`LinearCode` punctured in ``points``.\n\n INPUT:\n\n - ``points`` -- a set of positions where to puncture ``self``\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 4)\n sage: C._punctured_form({3})\n [10, 4] linear code over GF(7)\n ' if (not isinstance(points, (Integer, int, set))): raise TypeError('points must be either a Sage Integer, a Python int, or a set') M = self.generator_matrix() G = M.delete_columns(list(points)) G = G.echelon_form() k = G.rank() return LinearCode(G[:k]) def relative_distance(self): '\n Return the ratio of the minimum distance to the code length.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2),3)\n sage: C.relative_distance()\n 3/7\n ' return (self.minimum_distance() / self.length()) def shortened(self, L): '\n Return the code shortened at the positions ``L``, where\n `L \\subset \\{1,2,...,n\\}`.\n\n Consider the subcode `C(L)` consisting of all codewords `c\\in C` which\n satisfy `c_i=0` for all `i\\in L`. The punctured code `C(L)^L` is\n called the shortened code on `L` and is denoted `C_L`. The code\n constructed is actually only isomorphic to the shortened code defined\n in this way.\n\n By Theorem 1.5.7 in [HP2003]_, `C_L` is `((C^\\perp)^L)^\\perp`. This is used\n in the construction below.\n\n INPUT:\n\n - ``L`` -- Subset of `\\{1,...,n\\}`, where `n` is the length of this code\n\n OUTPUT:\n\n - Linear code, the shortened code described above\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: C.shortened([1,2])\n [5, 2] linear code over GF(2)\n ' Cd = self.dual_code() Cdp = Cd.punctured(set(L)) return Cdp.dual_code() @cached_method def weight_distribution(self, algorithm=None): '\n Return the weight distribution, or spectrum, of ``self`` as a list.\n\n The weight distribution a code of length `n` is the sequence `A_0,\n A_1,..., A_n` where `A_i` is the number of codewords of weight `i`.\n\n INPUT:\n\n - ``algorithm`` -- (optional, default: ``None``) If set to ``"gap"``,\n call GAP. If set to ``"leon"``, call the option GAP package GUAVA and\n call a function therein by Jeffrey Leon (see warning below). If set to\n ``"binary"``, use an algorithm optimized for binary codes. The default\n is to use ``"binary"`` for binary codes and ``"gap"`` otherwise.\n\n OUTPUT:\n\n - A list of non-negative integers: the weight distribution.\n\n .. WARNING::\n\n Specifying ``algorithm="leon"`` sometimes prints a traceback\n related to a stack smashing error in the C library. The result\n appears to be computed correctly, however. It appears to run much\n faster than the GAP algorithm in small examples and much slower than\n the GAP algorithm in larger examples.\n\n EXAMPLES::\n\n sage: MS = MatrixSpace(GF(2),4,7)\n sage: G = MS([[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: C.weight_distribution()\n [1, 0, 0, 7, 7, 0, 0, 1]\n sage: F.<z> = GF(2^2,"z")\n sage: C = codes.HammingCode(F, 2); C\n [5, 3] Hamming Code over GF(4)\n sage: C.weight_distribution()\n [1, 0, 0, 30, 15, 18]\n sage: C = codes.HammingCode(GF(2), 3); C\n [7, 4] Hamming Code over GF(2)\n sage: C.weight_distribution(algorithm="leon") # optional - gap_package_guava\n [1, 0, 0, 7, 7, 0, 0, 1]\n sage: C.weight_distribution(algorithm="gap") # optional - sage.libs.gap\n [1, 0, 0, 7, 7, 0, 0, 1]\n sage: C.weight_distribution(algorithm="binary")\n [1, 0, 0, 7, 7, 0, 0, 1]\n\n sage: # optional - gap_package_guava\n sage: C = codes.HammingCode(GF(3), 3); C\n [13, 10] Hamming Code over GF(3)\n sage: C.weight_distribution() == C.weight_distribution(algorithm="leon")\n True\n sage: C = codes.HammingCode(GF(5), 2); C\n [6, 4] Hamming Code over GF(5)\n sage: C.weight_distribution() == C.weight_distribution(algorithm="leon")\n True\n sage: C = codes.HammingCode(GF(7), 2); C\n [8, 6] Hamming Code over GF(7)\n sage: C.weight_distribution() == C.weight_distribution(algorithm="leon")\n True\n\n ' if (algorithm is None): if (self.base_ring().order() == 2): algorithm = 'binary' else: algorithm = 'gap' F = self.base_ring() n = self.length() if (algorithm == 'gap'): from sage.libs.gap.libgap import libgap Gmat = self.generator_matrix() q = self.base_ring().order() z = ((0 * libgap.Z(q)) * ([0] * self.length())) w = libgap(Gmat).DistancesDistributionMatFFEVecFFE(libgap.GF(q), z) return w.sage() elif (algorithm == 'binary'): from sage.coding.binary_code import weight_dist return weight_dist(self.generator_matrix()) elif (algorithm == 'leon'): if (not (F.order() in [2, 3, 5, 7])): raise NotImplementedError("The algorithm 'leon' is only implemented for q = 2,3,5,7.") from sage.libs.gap.libgap import libgap guava_bin_dir = libgap.DirectoriesPackagePrograms('guava')[0].Filename('').sage() input = (_dump_code_in_leon_format(self) + '::code') lines = subprocess.check_output([os.path.join(guava_bin_dir, 'wtdist'), input]) wts = ([0] * (n + 1)) for L in StringIO(bytes_to_str(lines)).readlines(): L = L.strip() if L: o = ord(L[0]) if ((o >= 48) and (o <= 57)): (wt, num) = L.split() wts[eval(wt)] = eval(num) return wts else: raise NotImplementedError("The only algorithms implemented currently are 'gap', 'leon' and 'binary'.") spectrum = weight_distribution def support(self): '\n Return the set of indices `j` where `A_j` is nonzero, where\n `A_j` is the number of codewords in ``self`` of Hamming weight `j`.\n\n OUTPUT:\n\n - List of integers\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: C.weight_distribution()\n [1, 0, 0, 7, 7, 0, 0, 1]\n sage: C.support()\n [0, 3, 4, 7]\n ' n = self.length() F = self.base_ring() V = VectorSpace(F, (n + 1)) return V(self.weight_distribution()).support() def weight_enumerator(self, names=None, bivariate=True): '\n Return the weight enumerator polynomial of ``self``.\n\n This is the bivariate, homogeneous polynomial in `x` and `y` whose\n coefficient to `x^i y^{n-i}` is the number of codewords of ``self`` of\n Hamming weight `i`. Here, `n` is the length of ``self``.\n\n INPUT:\n\n - ``names`` -- (default: ``"xy"``) The names of the variables in the\n homogeneous polynomial. Can be given as a single string of length 2,\n or a single string with a comma, or as a tuple or list of two strings.\n\n - ``bivariate`` -- (default: ``True``) Whether to return a bivariate,\n homogeneous polynomial or just a univariate polynomial. If set to\n ``False``, then ``names`` will be interpreted as a single variable\n name and default to ``"x"``.\n\n OUTPUT:\n\n - The weight enumerator polynomial over `\\ZZ`.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: C.weight_enumerator()\n x^7 + 7*x^4*y^3 + 7*x^3*y^4 + y^7\n sage: C.weight_enumerator(names="st")\n s^7 + 7*s^4*t^3 + 7*s^3*t^4 + t^7\n sage: C.weight_enumerator(names="var1, var2")\n var1^7 + 7*var1^4*var2^3 + 7*var1^3*var2^4 + var2^7\n sage: C.weight_enumerator(names=(\'var1\', \'var2\'))\n var1^7 + 7*var1^4*var2^3 + 7*var1^3*var2^4 + var2^7\n sage: C.weight_enumerator(bivariate=False)\n x^7 + 7*x^4 + 7*x^3 + 1\n\n An example of a code with a non-symmetrical weight enumerator::\n\n sage: C = codes.GolayCode(GF(3), extended=False)\n sage: C.weight_enumerator()\n 24*x^11 + 110*x^9*y^2 + 330*x^8*y^3 + 132*x^6*y^5 + 132*x^5*y^6 + y^11\n ' if (names is None): if bivariate: names = 'xy' else: names = 'x' spec = self.weight_distribution() n = self.length() if bivariate: R = PolynomialRing(ZZ, 2, names) (x, y) = R.gens() return sum((((spec[i] * (x ** i)) * (y ** (n - i))) for i in range((n + 1)))) else: R = PolynomialRing(ZZ, names) (x,) = R.gens() return sum(((spec[i] * (x ** i)) for i in range((n + 1)))) def zeta_polynomial(self, name='T'): '\n Return the Duursma zeta polynomial of this code.\n\n Assumes that the minimum distances of this code and its dual are\n greater than 1. Prints a warning to ``stdout`` otherwise.\n\n INPUT:\n\n - ``name`` -- String, variable name (default: ``"T"``)\n\n OUTPUT:\n\n - Polynomial over `\\QQ`\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: C.zeta_polynomial()\n 2/5*T^2 + 2/5*T + 1/5\n\n sage: C = codes.databases.best_linear_code_in_guava(6, 3, GF(2)) # optional - gap_package_guava\n sage: C.minimum_distance() # optional - gap_package_guava\n 3\n sage: C.zeta_polynomial() # optional - gap_package_guava\n 2/5*T^2 + 2/5*T + 1/5\n\n sage: C = codes.HammingCode(GF(2), 4)\n sage: C.zeta_polynomial()\n 16/429*T^6 + 16/143*T^5 + 80/429*T^4 + 32/143*T^3 + 30/143*T^2 + 2/13*T + 1/13\n\n sage: F.<z> = GF(4,"z")\n sage: MS = MatrixSpace(F, 3, 6)\n sage: G = MS([[1,0,0,1,z,z],[0,1,0,z,1,z],[0,0,1,z,z,1]])\n sage: C = LinearCode(G) # the "hexacode"\n sage: C.zeta_polynomial()\n 1\n\n REFERENCES:\n\n - [Du2001]_\n ' n = self.length() q = self.base_ring().order() d = self.minimum_distance() dperp = self.dual_code().minimum_distance() if ((d == 1) or (dperp == 1)): print('\n WARNING: There is no guarantee this function works when the minimum distance') print(' of the code or of the dual code equals 1.\n') RT = PolynomialRing(QQ, ('%s' % name)) R = PolynomialRing(QQ, 3, ('xy%s' % name)) (x, y, T) = R.gens() we = self.weight_enumerator() A = R(we) B = (A(x, (x + y), T) - ((x + y) ** n)) Bs = B.coefficients() Bs.reverse() b = [(Bs[i] / binomial(n, (i + d))) for i in range(len(Bs))] r = (((n - d) - dperp) + 2) P_coeffs = [] for i in range(len(b)): if (i == 0): P_coeffs.append(b[0]) if (i == 1): P_coeffs.append((b[1] - ((q + 1) * b[0]))) if (i > 1): P_coeffs.append(((b[i] - ((q + 1) * b[(i - 1)])) + (q * b[(i - 2)]))) P = sum([(P_coeffs[i] * (T ** i)) for i in range((r + 1))]) return (RT(P) / RT(P)(1)) def zeta_function(self, name='T'): '\n Return the Duursma zeta function of the code.\n\n INPUT:\n\n - ``name`` -- String, variable name (default: ``"T"``)\n\n OUTPUT:\n\n Element of `\\QQ(T)`\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: C.zeta_function()\n (1/5*T^2 + 1/5*T + 1/10)/(T^2 - 3/2*T + 1/2)\n ' P = self.zeta_polynomial() q = self.base_ring().characteristic() RT = PolynomialRing(QQ, name) T = RT.gen() return (P / ((1 - T) * (1 - (q * T)))) def cosetGraph(self): '\n Return the coset graph of this linear code.\n\n The coset graph of a linear code `C` is the graph whose vertices\n are the cosets of `C`, considered as a subgroup of the additive\n group of the ambient vector space, and two cosets are adjacent\n if they have representatives that differ in exactly one coordinate.\n\n EXAMPLES::\n\n sage: C = codes.GolayCode(GF(3))\n sage: G = C.cosetGraph()\n sage: G.is_distance_regular()\n True\n sage: C = codes.KasamiCode(8,2)\n sage: G = C.cosetGraph()\n sage: G.is_distance_regular()\n True\n\n ALGORITHM:\n\n Instead of working with cosets we compute a (direct sum) complement\n of `C`. Let `P` be the projection of the cosets to the newly found\n subspace. Then two vectors are adjacent if they differ by\n `\\lambda P(e_i)` for some `i`.\n\n TESTS::\n\n sage: C = codes.KasamiCode(4,2)\n sage: C.cosetGraph()\n Hamming Graph with parameters 4,2: Graph on 16 vertices\n sage: M = matrix.identity(GF(3), 7)\n sage: C = LinearCode(M)\n sage: G = C.cosetGraph()\n sage: G.vertices(sort=False)\n [0]\n sage: G.edges(sort=False)\n []\n ' from sage.matrix.constructor import matrix from sage.graphs.graph import Graph F = self.base_field() def e(i): v = ([0] * self.length()) v[(i - 1)] = 1 return vector(F, v, immutable=True) if (len(self.basis()) == self.length()): G = Graph(1) G.name(f'coset graph of {self.__repr__()}') return G if (len(self.basis()) == 0): from sage.graphs.graph_generators import GraphGenerators return GraphGenerators.HammingGraph(self.length(), F.order()) M = matrix(F, self.basis()) M.echelonize() C_basis = M.rows() U_basis = list(range(self.length())) for v in C_basis: i = v.support()[0] U_basis.remove(i) U_basis = [e((i + 1)) for i in U_basis] V = VectorSpace(F, self.length()) U = V.span(U_basis) vertices = list(U) A = matrix(F, U_basis) A = A.stack(matrix(F, C_basis)) A = A.transpose() Ainv = A.inverse() Pei = [] for i in range(1, (self.length() + 1)): ei = e(i) if (ei in U): Pei.append(ei) else: a = (Ainv * ei) v = vector(F, ([0] * self.length())) for (ai, Ui) in zip(a, U_basis): v += (ai * Ui) if (not v.is_zero()): v.set_immutable() Pei.append(v) lPei = [(l * u) for l in F for u in Pei if (not l.is_zero())] edges = [] for v in vertices: v.set_immutable() for u in lPei: w = (v + u) w.set_immutable() edges.append((v, w)) G = Graph(edges, format='list_of_edges') G.name(f'coset graph of {self.__repr__()}') return G
class LinearCode(AbstractLinearCode): '\n Linear codes over a finite field or finite ring, represented using a\n generator matrix.\n\n This class should be used for arbitrary and unstructured linear codes. This\n means that basic operations on the code, such as the computation of the\n minimum distance, will use generic, slow algorithms.\n\n If you are looking for constructing a code from a more specific family, see\n if the family has been implemented by investigating ``codes.<tab>``. These\n more specific classes use properties particular to that family to allow\n faster algorithms, and could also have family-specific methods.\n\n See :wikipedia:`Linear_code` for more information on unstructured linear codes.\n\n INPUT:\n\n - ``generator`` -- a generator matrix over a finite field (``G`` can be\n defined over a finite ring but the matrices over that ring must have\n certain attributes, such as ``rank``); or a code over a finite field\n\n - ``d`` -- (optional, default: ``None``) the minimum distance of the code\n\n .. NOTE::\n\n The veracity of the minimum distance ``d``, if provided, is not\n checked.\n\n EXAMPLES::\n\n sage: MS = MatrixSpace(GF(2),4,7)\n sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: C\n [7, 4] linear code over GF(2)\n sage: C.base_ring()\n Finite Field of size 2\n sage: C.dimension()\n 4\n sage: C.length()\n 7\n sage: C.minimum_distance()\n 3\n sage: C.spectrum()\n [1, 0, 0, 7, 7, 0, 0, 1]\n sage: C.weight_distribution()\n [1, 0, 0, 7, 7, 0, 0, 1]\n\n The minimum distance of the code, if known, can be provided as an\n optional parameter.::\n\n sage: C = LinearCode(G, d=3)\n sage: C.minimum_distance()\n 3\n\n Another example.::\n\n sage: MS = MatrixSpace(GF(5),4,7)\n sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: C\n [7, 4] linear code over GF(5)\n\n Providing a code as the parameter in order to "forget" its structure (see\n :trac:`20198`)::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(23).list(), 12)\n sage: LinearCode(C)\n [23, 12] linear code over GF(23)\n\n Another example::\n\n sage: C = codes.HammingCode(GF(7), 3)\n sage: C\n [57, 54] Hamming Code over GF(7)\n sage: LinearCode(C)\n [57, 54] linear code over GF(7)\n\n AUTHORS:\n\n - David Joyner (11-2005)\n - Charles Prior (03-2016): :trac:`20198`, LinearCode from a code\n ' def __init__(self, generator, d=None): '\n See the docstring for :meth:`LinearCode`.\n\n EXAMPLES::\n\n sage: MS = MatrixSpace(GF(2),4,7)\n sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G) # indirect doctest\n sage: C\n [7, 4] linear code over GF(2)\n\n The minimum distance of the code, if known, can be provided as an\n optional parameter.::\n\n sage: C = LinearCode(G, d=3)\n sage: C.minimum_distance()\n 3\n\n TESTS::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: TestSuite(C).run()\n\n Check that it works even with input matrix with non full rank (see\n :trac:`17452`)::\n\n sage: K.<a> = GF(4)\n sage: G = matrix([[a, a + 1, 1, a + 1, 1, 0, 0],\n ....: [0, a, a + 1, 1, a + 1, 1, 0],\n ....: [0, 0, a, a + 1, 1, a + 1, 1],\n ....: [a + 1, 0, 1, 0, a + 1, 1, a + 1],\n ....: [a, a + 1, a + 1, 0, 0, a + 1, 1],\n ....: [a + 1, a, a, 1, 0, 0, a + 1],\n ....: [a, a + 1, 1, a + 1, 1, 0, 0]])\n sage: C = LinearCode(G)\n sage: C.basis()\n [\n (1, 0, 0, a + 1, 0, 1, 0),\n (0, 1, 0, 0, a + 1, 0, 1),\n (0, 0, 1, a, a + 1, a, a + 1)\n ]\n sage: C.minimum_distance()\n 3\n\n We can construct a linear code directly from a vector space::\n\n sage: VS = matrix(GF(2), [[1,0,1],\n ....: [1,0,1]]).row_space()\n sage: C = LinearCode(VS); C\n [3, 1] linear code over GF(2)\n\n Forbid the zero vector space (see :trac:`17452` and :trac:`6486`)::\n\n sage: G = matrix(GF(2), [[0,0,0]])\n sage: C = LinearCode(G)\n Traceback (most recent call last):\n ...\n ValueError: this linear code contains no non-zero vector\n ' base_ring = generator.base_ring() if (not base_ring.is_field()): raise ValueError("'generator' must be defined on a field (not a ring)") try: basis = None if hasattr(generator, 'nrows'): if (generator.rank() < generator.nrows()): basis = generator.row_space().basis() else: basis = generator.basis() if (basis is not None): from sage.matrix.constructor import matrix generator = matrix(base_ring, basis) if (generator.nrows() == 0): raise ValueError('this linear code contains no non-zero vector') except AttributeError: generator = generator.generator_matrix() super().__init__(base_ring, generator.ncols(), 'GeneratorMatrix', 'Syndrome') self._generator_matrix = generator self._dimension = generator.rank() self._minimum_distance = d def __hash__(self): Str = str(self) G = self.generator_matrix() return hash((Str, G)) def _repr_(self): '\n See the docstring for :meth:`LinearCode`.\n\n EXAMPLES::\n\n sage: MS = MatrixSpace(GF(2),4,7)\n sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: C # indirect doctest\n [7, 4] linear code over GF(2)\n ' R = self.base_ring() if (R in Fields()): return ('[%s, %s] linear code over GF(%s)' % (self.length(), self.dimension(), R.cardinality())) else: return ('[%s, %s] linear code over %s' % (self.length(), self.dimension(), R)) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: MS = MatrixSpace(GF(2),4,7)\n sage: G = MS([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: latex(C)\n [7, 4]\\textnormal{ Linear code over }\\Bold{F}_{2}\n ' return ('[%s, %s]\\textnormal{ Linear code over }%s' % (self.length(), self.dimension(), self.base_ring()._latex_())) def generator_matrix(self, encoder_name=None, **kwargs): '\n Return a generator matrix of ``self``.\n\n INPUT:\n\n - ``encoder_name`` -- (default: ``None``) name of the encoder which will be\n used to compute the generator matrix. ``self._generator_matrix``\n will be returned if default value is kept.\n\n - ``kwargs`` -- all additional arguments are forwarded to the construction of the\n encoder that is used.\n\n EXAMPLES::\n\n sage: G = matrix(GF(3),2,[1,-1,1,-1,1,1])\n sage: code = LinearCode(G)\n sage: code.generator_matrix()\n [1 2 1]\n [2 1 1]\n ' if ((encoder_name is None) or (encoder_name == 'GeneratorMatrix')): g = self._generator_matrix else: g = super().generator_matrix(encoder_name, **kwargs) g.set_immutable() return g
class LinearCodeGeneratorMatrixEncoder(Encoder): '\n Encoder based on generator_matrix for Linear codes.\n\n This is the default encoder of a generic linear code, and should never be used for other codes than\n :class:`LinearCode`.\n\n INPUT:\n\n - ``code`` -- The associated :class:`LinearCode` of this encoder.\n ' def __init__(self, code): '\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C)\n sage: E\n Generator matrix-based encoder for [7, 4] linear code over GF(2)\n ' super().__init__(code) def __eq__(self, other): '\n Tests equality between LinearCodeGeneratorMatrixEncoder objects.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: E1 = LinearCode(G).encoder()\n sage: E2 = LinearCode(G).encoder()\n sage: E1 == E2\n True\n ' return (isinstance(other, LinearCodeGeneratorMatrixEncoder) and (self.code() == other.code())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C)\n sage: E\n Generator matrix-based encoder for [7, 4] linear code over GF(2)\n ' return ('Generator matrix-based encoder for %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C)\n sage: latex(E)\n \\textnormal{Generator matrix-based encoder for }[7, 4]\\textnormal{ Linear code over }\\Bold{F}_{2}\n ' return ('\\textnormal{Generator matrix-based encoder for }%s' % self.code()._latex_()) @cached_method def generator_matrix(self): '\n Return a generator matrix of the associated code of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C)\n sage: E.generator_matrix()\n [1 1 1 0 0 0 0]\n [1 0 0 1 1 0 0]\n [0 1 0 1 0 1 0]\n [1 1 0 1 0 0 1]\n ' g = self.code().generator_matrix() g.set_immutable() return g
class LinearCodeSyndromeDecoder(Decoder): '\n Constructs a decoder for Linear Codes based on syndrome lookup table.\n\n The decoding algorithm works as follows:\n\n - First, a lookup table is built by computing the syndrome of every error\n pattern of weight up to ``maximum_error_weight``.\n - Then, whenever one tries to decode a word ``r``, the syndrome of ``r`` is\n computed. The corresponding error pattern is recovered from the\n pre-computed lookup table.\n - Finally, the recovered error pattern is subtracted from ``r`` to recover\n the original word.\n\n ``maximum_error_weight`` need never exceed the covering radius of the code,\n since there are then always lower-weight errors with the same syndrome. If\n one sets ``maximum_error_weight`` to a value greater than the covering\n radius, then the covering radius will be determined while building the\n lookup-table. This lower value is then returned if you query\n ``decoding_radius`` after construction.\n\n If ``maximum_error_weight`` is left unspecified or set to a number at least\n the covering radius of the code, this decoder is complete, i.e. it decodes\n every vector in the ambient space.\n\n .. NOTE::\n\n Constructing the lookup table takes time exponential in the length of the\n code and the size of the code\'s base field. Afterwards, the individual\n decodings are fast.\n\n INPUT:\n\n - ``code`` -- A code associated to this decoder\n\n - ``maximum_error_weight`` -- (default: ``None``) the maximum number of\n errors to look for when building the table. An error is raised if it is\n set greater than `n-k`, since this is an upper bound on the covering\n radius on any linear code. If ``maximum_error_weight`` is kept\n unspecified, it will be set to `n - k`, where `n` is the length of\n ``code`` and `k` its dimension.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],\n ....: [0,1,0,2,2,0,1,1,0],\n ....: [0,0,1,0,2,2,2,1,2]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeSyndromeDecoder(C)\n sage: D\n Syndrome decoder for [9, 3] linear code over GF(3) handling errors of weight up to 4\n\n If one wants to correct up to a lower number of errors, one can do as follows::\n\n sage: D = codes.decoders.LinearCodeSyndromeDecoder(C, maximum_error_weight=2)\n sage: D\n Syndrome decoder for [9, 3] linear code over GF(3) handling errors of weight up to 2\n\n If one checks the list of types of this decoder before constructing it,\n one will notice it contains the keyword ``dynamic``.\n Indeed, the behaviour of the syndrome decoder depends on the maximum\n error weight one wants to handle, and how it compares to the minimum\n distance and the covering radius of ``code``.\n In the following examples, we illustrate this property by computing\n different instances of syndrome decoder for the same code.\n\n We choose the following linear code, whose covering radius equals to 4\n and minimum distance to 5 (half the minimum distance is 2)::\n\n sage: G = matrix(GF(5), [[1, 0, 0, 0, 0, 4, 3, 0, 3, 1, 0],\n ....: [0, 1, 0, 0, 0, 3, 2, 2, 3, 2, 1],\n ....: [0, 0, 1, 0, 0, 1, 3, 0, 1, 4, 1],\n ....: [0, 0, 0, 1, 0, 3, 4, 2, 2, 3, 3],\n ....: [0, 0, 0, 0, 1, 4, 2, 3, 2, 2, 1]])\n sage: C = LinearCode(G)\n\n In the following examples, we illustrate how the choice of\n ``maximum_error_weight`` influences the types of the instance of\n syndrome decoder, alongside with its decoding radius.\n\n We build a first syndrome decoder, and pick a ``maximum_error_weight``\n smaller than both the covering radius and half the minimum distance::\n\n sage: D = C.decoder("Syndrome", maximum_error_weight=1)\n sage: D.decoder_type()\n {\'always-succeed\', \'bounded_distance\', \'hard-decision\'}\n sage: D.decoding_radius()\n 1\n\n In that case, we are sure the decoder will always succeed. It is also\n a bounded distance decoder.\n\n We now build another syndrome decoder, and this time,\n ``maximum_error_weight`` is chosen to be bigger than half the minimum distance,\n but lower than the covering radius::\n\n sage: D = C.decoder("Syndrome", maximum_error_weight=3)\n sage: D.decoder_type()\n {\'bounded_distance\', \'hard-decision\', \'might-error\'}\n sage: D.decoding_radius()\n 3\n\n Here, we still get a bounded distance decoder.\n But because we have a maximum error weight bigger than half the\n minimum distance, we know it might return a codeword which was not\n the original codeword.\n\n And now, we build a third syndrome decoder, whose ``maximum_error_weight``\n is bigger than both the covering radius and half the minimum distance::\n\n sage: D = C.decoder("Syndrome", maximum_error_weight=5) # long time\n sage: D.decoder_type() # long time\n {\'complete\', \'hard-decision\', \'might-error\'}\n sage: D.decoding_radius() # long time\n 4\n\n In that case, the decoder might still return an unexpected codeword, but\n it is now complete. Note the decoding radius is equal to 4: it was\n determined while building the syndrome lookup table that any error with\n weight more than 4 will be decoded incorrectly. That is because the covering\n radius for the code is 4.\n\n The minimum distance and the covering radius are both determined while\n computing the syndrome lookup table. They user did not explicitly ask to\n compute these on the code ``C``. The dynamic typing of the syndrome decoder\n might therefore seem slightly surprising, but in the end is quite\n informative.\n ' def __init__(self, code, maximum_error_weight=None): '\n TESTS:\n\n If ``maximum_error_weight`` is greater or equal than `n-k`, where `n`\n is ``code``\'s length, and `k` is ``code``\'s dimension,\n an error is raised::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeSyndromeDecoder(C, 42)\n Traceback (most recent call last):\n ...\n ValueError: maximum_error_weight has to be less than code\'s length minus its dimension\n\n The Syndrome Decoder of a Hamming code should have types\n ``minimum-distance`` and ``always-succeed`` (see :trac:`20898`)::\n\n sage: C = codes.HammingCode(GF(5), 3)\n sage: D = C.decoder("Syndrome")\n sage: C.minimum_distance()\n 3\n sage: D.maximum_error_weight()\n 1\n sage: D.decoder_type()\n {\'always-succeed\', \'complete\', \'hard-decision\', \'minimum-distance\'}\n ' n_minus_k = (code.length() - code.dimension()) if (maximum_error_weight is None): self._maximum_error_weight = n_minus_k elif (not isinstance(maximum_error_weight, (Integer, int))): raise ValueError('maximum_error_weight has to be a Sage integer or a Python int') elif (maximum_error_weight > n_minus_k): raise ValueError("maximum_error_weight has to be less than code's length minus its dimension") else: self._maximum_error_weight = maximum_error_weight super().__init__(code, code.ambient_space(), code._default_encoder_name) self._lookup_table = self._build_lookup_table() def __eq__(self, other): '\n Tests equality between LinearCodeSyndromeDecoder objects.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],[0,1,0,2,2,0,1,1,0],[0,0,1,0,2,2,2,1,2]])\n sage: D1 = codes.decoders.LinearCodeSyndromeDecoder(LinearCode(G))\n sage: D2 = codes.decoders.LinearCodeSyndromeDecoder(LinearCode(G))\n sage: D1 == D2\n True\n ' return (isinstance(other, LinearCodeSyndromeDecoder) and (self.code() == other.code()) and (self.maximum_error_weight() == other.maximum_error_weight())) def __hash__(self): '\n Return the hash of self.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],[0,1,0,2,2,0,1,1,0],[0,0,1,0,2,2,2,1,2]])\n sage: D1 = codes.decoders.LinearCodeSyndromeDecoder(LinearCode(G))\n sage: D2 = codes.decoders.LinearCodeSyndromeDecoder(LinearCode(G))\n sage: hash(D1) == hash(D2)\n True\n ' return hash((self.code(), self.maximum_error_weight())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],[0,1,0,2,2,0,1,1,0],[0,0,1,0,2,2,2,1,2]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeSyndromeDecoder(C)\n sage: D\n Syndrome decoder for [9, 3] linear code over GF(3) handling errors of weight up to 4\n ' return ('Syndrome decoder for %s handling errors of weight up to %s' % (self.code(), self.maximum_error_weight())) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],[0,1,0,2,2,0,1,1,0],[0,0,1,0,2,2,2,1,2]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeSyndromeDecoder(C)\n sage: latex(D)\n \\textnormal{Syndrome decoder for [9, 3]\\textnormal{ Linear code over }\\Bold{F}_{3} handling errors of weight up to 4}\n ' return ('\\textnormal{Syndrome decoder for %s handling errors of weight up to %s}' % (self.code()._latex_(), self.maximum_error_weight())) @cached_method def _build_lookup_table(self): '\n Builds lookup table for all possible error patterns of weight up to :meth:`maximum_error_weight`.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(3),[\n ....: [1, 0, 0, 0, 2, 2, 1, 1],\n ....: [0, 1, 0, 0, 0, 0, 1, 1],\n ....: [0, 0, 1, 0, 2, 0, 0, 2],\n ....: [0, 0, 0, 1, 0, 2, 0, 1]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeSyndromeDecoder(C, maximum_error_weight = 1)\n sage: D._build_lookup_table()\n {(0, 0, 0, 0): (0, 0, 0, 0, 0, 0, 0, 0),\n (0, 0, 0, 1): (0, 0, 0, 0, 1, 0, 0, 0),\n (0, 0, 0, 2): (0, 0, 0, 0, 2, 0, 0, 0),\n (0, 0, 1, 0): (0, 0, 1, 0, 0, 0, 0, 0),\n (0, 0, 1, 2): (0, 0, 0, 0, 0, 0, 0, 1),\n (0, 0, 2, 0): (0, 0, 2, 0, 0, 0, 0, 0),\n (0, 0, 2, 1): (0, 0, 0, 0, 0, 0, 0, 2),\n (0, 1, 0, 0): (0, 1, 0, 0, 0, 0, 0, 0),\n (0, 1, 1, 2): (0, 0, 0, 0, 0, 0, 2, 0),\n (0, 2, 0, 0): (0, 2, 0, 0, 0, 0, 0, 0),\n (0, 2, 2, 1): (0, 0, 0, 0, 0, 0, 1, 0),\n (1, 0, 0, 0): (1, 0, 0, 0, 0, 0, 0, 0),\n (1, 2, 0, 2): (0, 0, 0, 0, 0, 1, 0, 0),\n (1, 2, 2, 0): (0, 0, 0, 1, 0, 0, 0, 0),\n (2, 0, 0, 0): (2, 0, 0, 0, 0, 0, 0, 0),\n (2, 1, 0, 1): (0, 0, 0, 0, 0, 2, 0, 0),\n (2, 1, 1, 0): (0, 0, 0, 2, 0, 0, 0, 0)}\n\n TESTS:\n\n Check that :trac:`24114` is fixed::\n\n sage: R.<x> = PolynomialRing(GF(3))\n sage: f = x^2 + x + 2\n sage: K.<a> = f.root_field()\n sage: H = Matrix(K,[[1,2,1],[2*a+1,a,1]])\n sage: C = codes.from_parity_check_matrix(H)\n sage: D = codes.decoders.LinearCodeSyndromeDecoder(C)\n sage: D.syndrome_table()\n {(0, 0): (0, 0, 0),\n (0, 1): (0, 1, 0),\n (0, 2): (0, 2, 0),\n (0, a): (0, a, 0),\n ...\n (2*a + 2, 2*a): (0, 0, 2),\n (2*a + 2, 2*a + 1): (2*a + 2, 2*a + 1, 0),\n (2*a + 2, 2*a + 2): (2*a + 2, 2*a + 2, 0)}\n ' t = self._maximum_error_weight self._code_covering_radius = None self._code_minimum_distance = None self._decoder_type = copy(self._decoder_type) self._decoder_type.remove('dynamic') C = self.code() n = C.length() k = C.dimension() H = C.parity_check_matrix() F = C.base_ring() l = list(F) zero = F.zero() if (zero in l): l.remove(zero) zero_syndrome = vector(F, ([F.zero()] * (n - k))) zero_syndrome.set_immutable() lookup = {zero_syndrome: vector(F, ([F.zero()] * n))} error_position_tables = [cartesian_product(([l] * i)) for i in range(1, (t + 1))] first_collision = True for i in range(1, (t + 1)): stop = True patterns = Subsets(range(n), i) basic = vector(F, n) for p in patterns: for error in error_position_tables[(i - 1)]: ind = 0 e = copy(basic) for pos in p: e[pos] = error[ind] ind += 1 s = (H * e) s.set_immutable() try: e_cur = lookup[s] if first_collision: self._code_minimum_distance = (e.hamming_weight() + e_cur.hamming_weight()) first_collision = False except KeyError: stop = False lookup[s] = copy(e) if stop: self._code_covering_radius = (i - 1) self._maximum_error_weight = self._code_covering_radius break if self._code_covering_radius: self._decoder_type.add('complete') else: self._decoder_type.add('bounded_distance') if self._code_minimum_distance: if (self._maximum_error_weight == ((self._code_minimum_distance - 1) // 2)): self._decoder_type.update({'minimum-distance', 'always-succeed'}) else: self._decoder_type.add('might-error') else: self._decoder_type.add('always-succeed') return lookup def decode_to_code(self, r): "\n Correct the errors in ``word`` and return a codeword.\n\n INPUT:\n\n - ``r`` -- a codeword of ``self``\n\n OUTPUT:\n\n - a vector of ``self``'s message space\n\n EXAMPLES::\n\n sage: G = Matrix(GF(3),[\n ....: [1, 0, 0, 0, 2, 2, 1, 1],\n ....: [0, 1, 0, 0, 0, 0, 1, 1],\n ....: [0, 0, 1, 0, 2, 0, 0, 2],\n ....: [0, 0, 0, 1, 0, 2, 0, 1]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeSyndromeDecoder(C, maximum_error_weight = 1)\n sage: Chan = channels.StaticErrorRateChannel(C.ambient_space(), 1)\n sage: c = C.random_element()\n sage: r = Chan(c)\n sage: c == D.decode_to_code(r)\n True\n " lookup_table = self.syndrome_table() s = (self.code().parity_check_matrix() * r) s.set_immutable() if s.is_zero(): return r err = lookup_table[s] r_corr = copy(r) for i in range(self.code().length()): r_corr[i] = (r[i] - err[i]) return r_corr def maximum_error_weight(self): '\n Return the maximal number of errors a received word can have\n and for which ``self`` is guaranteed to return a most likely codeword.\n\n Same as :meth:`decoding_radius`.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],\n ....: [0,1,0,2,2,0,1,1,0],\n ....: [0,0,1,0,2,2,2,1,2]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeSyndromeDecoder(C)\n sage: D.maximum_error_weight()\n 4\n ' return self._maximum_error_weight def decoding_radius(self): '\n Return the maximal number of errors a received word can have\n and for which ``self`` is guaranteed to return a most likely codeword.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(3), [[1,0,0,1,0,1,0,1,2],\n ....: [0,1,0,2,2,0,1,1,0],\n ....: [0,0,1,0,2,2,2,1,2]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeSyndromeDecoder(C)\n sage: D.decoding_radius()\n 4\n ' return self._maximum_error_weight def syndrome_table(self): '\n Return the syndrome lookup table of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeSyndromeDecoder(C)\n sage: D.syndrome_table()\n {(0, 0, 0): (0, 0, 0, 0, 0, 0, 0),\n (1, 0, 0): (1, 0, 0, 0, 0, 0, 0),\n (0, 1, 0): (0, 1, 0, 0, 0, 0, 0),\n (1, 1, 0): (0, 0, 1, 0, 0, 0, 0),\n (0, 0, 1): (0, 0, 0, 1, 0, 0, 0),\n (1, 0, 1): (0, 0, 0, 0, 1, 0, 0),\n (0, 1, 1): (0, 0, 0, 0, 0, 1, 0),\n (1, 1, 1): (0, 0, 0, 0, 0, 0, 1)}\n ' return self._lookup_table
class LinearCodeNearestNeighborDecoder(Decoder): '\n Construct a decoder for Linear Codes. This decoder will decode to the\n nearest codeword found.\n\n INPUT:\n\n - ``code`` -- A code associated to this decoder\n ' def __init__(self, code): '\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeNearestNeighborDecoder(C)\n sage: D\n Nearest neighbor decoder for [7, 4] linear code over GF(2)\n ' super().__init__(code, code.ambient_space(), code._default_encoder_name) def __eq__(self, other): '\n Tests equality between LinearCodeNearestNeighborDecoder objects.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: D1 = codes.decoders.LinearCodeNearestNeighborDecoder(LinearCode(G))\n sage: D2 = codes.decoders.LinearCodeNearestNeighborDecoder(LinearCode(G))\n sage: D1 == D2\n True\n ' return (isinstance(other, LinearCodeNearestNeighborDecoder) and (self.code() == other.code())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeNearestNeighborDecoder(C)\n sage: D\n Nearest neighbor decoder for [7, 4] linear code over GF(2)\n ' return ('Nearest neighbor decoder for %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeNearestNeighborDecoder(C)\n sage: latex(D)\n \\textnormal{Nearest neighbor decoder for }[7, 4]\\textnormal{ Linear code over }\\Bold{F}_{2}\n ' return ('\\textnormal{Nearest neighbor decoder for }%s' % self.code()._latex_()) def decode_to_code(self, r): "\n Corrects the errors in ``word`` and returns a codeword.\n\n INPUT:\n\n - ``r`` -- a codeword of ``self``\n\n OUTPUT:\n\n - a vector of ``self``'s message space\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeNearestNeighborDecoder(C)\n sage: word = vector(GF(2), (1, 1, 0, 0, 1, 1, 0))\n sage: w_err = word + vector(GF(2), (1, 0, 0, 0, 0, 0, 0))\n sage: D.decode_to_code(w_err)\n (1, 1, 0, 0, 1, 1, 0)\n " c_min = self.code().zero() h_min = r.hamming_weight() for c in self.code(): if ((c - r).hamming_weight() < h_min): h_min = (c - r).hamming_weight() c_min = c c_min.set_immutable() return c_min def decoding_radius(self): '\n Return maximal number of errors ``self`` can decode.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeNearestNeighborDecoder(C)\n sage: D.decoding_radius()\n 1\n ' return ((self.code().minimum_distance() - 1) // 2)
def to_matrix_representation(v, sub_field=None, basis=None): '\n Return a matrix representation of ``v`` over ``sub_field`` in terms of\n ``basis``.\n\n Let `(b_1, b_2, \\ldots, b_m)`, `b_i \\in GF(q^m)`, be a basis of `\\GF{q^m}` as\n a vector space over `\\GF{q}`. Take an element `x \\in \\GF{q^m}`. We can write\n `x` as `x = u_1 b_1 + u_2 b_2 + \\ldots u_m b_m`, where `u_i \\in GF(q)`. This\n way we can represent an element from `\\GF{q^m}` as a vector of length `m`\n over `\\GF{q}`.\n\n Given a vector ``v`` of length `n` over some field `\\GF{q^m}`, we can\n represent each entry as a vector of length `m`, yielding an `m \\times n`\n matrix over ``sub_field``. In case ``sub_field`` is not given, we take the\n prime subfield `\\GF{p}` of `\\GF{q^m}`.\n\n INPUT:\n\n - ``v`` -- a vector over some field `\\GF{q^m}`\n\n - ``sub_field`` -- (default: ``None``) a sub field of `\\GF{q^m}`. If not\n specified, it is the prime subfield `\\GF{p}` of `\\GF{q^m}`.\n\n - ``basis`` -- (default: ``None``) a basis of `\\GF{q^m}` as a vector space over\n ``sub_field``. If not specified, given that `q = p^s`, let\n `1,\\beta,\\ldots,\\beta^{sm}` be the power basis that SageMath uses to\n represent `\\GF{q^m}`. The default basis is then `1,\\beta,\\ldots,\\beta^{m-1}`.\n\n EXAMPLES::\n\n sage: from sage.coding.linear_rank_metric import to_matrix_representation\n sage: x = GF(64).gen()\n sage: a = vector(GF(64), (x + 1, x + 1, 1))\n sage: to_matrix_representation(a, GF(4))\n [1 1 1]\n [1 1 0]\n [0 0 0]\n\n sage: m = Matrix(GF(4), [[1, 1, 1], [1, 1, 0], [0, 0, 0]])\n sage: to_matrix_representation(m)\n Traceback (most recent call last):\n ...\n TypeError: Input must be a vector\n ' if (not is_Vector(v)): raise TypeError('Input must be a vector') base_field = v.base_ring() if (not sub_field): sub_field = base_field.prime_subfield() n = v.length() m = (base_field.degree() // sub_field.degree()) (extension, to_big_field, from_big_field) = base_field.vector_space(sub_field, basis, map=True) return Matrix(sub_field, m, n, (lambda i, j: from_big_field(v[j])[i]))
def from_matrix_representation(w, base_field=None, basis=None): '\n Return a vector representation of a matrix ``w`` over ``base_field`` in terms\n of ``basis``.\n\n Given an `m \\times n` matrix over `\\GF{q}` and some ``basis`` of `\\GF{q^m}`\n over `\\GF{q}`, we can represent each of its columns as an element of `\\GF{q^m}`,\n yielding a vector of length `n` over `\\GF{q}`.\n\n In case ``base_field`` is not given, we take `\\GF{q^m}`, the field extension of\n `\\GF{q}` of degree `m`, the number of rows of ``w``.\n\n INPUT:\n\n - ``w`` -- a matrix over some field `\\GF{q}`\n\n - ``base_field`` -- (default: ``None``) an extension field of `\\GF{q}`. If not\n specified, it is the field `\\GF{q^m}`, where `m` is the number of rows of\n ``w``.\n\n - ``basis`` -- (default: ``None``) a basis of `\\GF{q^m}` as a vector space over\n `\\GF{q}`. If not specified, given that `q = p^s`, let\n `1,\\beta,\\ldots,\\beta^{sm}` be the power basis that SageMath uses to\n represent `\\GF{q^m}`. The default basis is then `1,\\beta,\\ldots,\\beta^{m-1}`.\n\n EXAMPLES::\n\n sage: from sage.coding.linear_rank_metric import from_matrix_representation\n sage: m = Matrix(GF(4), [[1, 1, 1], [1, 1, 0], [0, 0, 0]])\n sage: from_matrix_representation(m)\n (z6 + 1, z6 + 1, 1)\n\n sage: v = vector(GF(4), (1, 0, 0))\n sage: from_matrix_representation(v)\n Traceback (most recent call last):\n ...\n TypeError: Input must be a matrix\n ' if (not is_Matrix(w)): raise TypeError('Input must be a matrix') sub_field = w.base_ring() if (not base_field): base_field = sub_field.extension(w.nrows()) v = [] (extension, to_big_field, from_big_field) = base_field.vector_space(sub_field, basis, map=True) for i in range(w.ncols()): v.append(to_big_field(w.column(i))) return vector(v)
def rank_weight(c, sub_field=None, basis=None): '\n Return the rank of ``c`` as a matrix over ``sub_field``.\n\n If ``c`` is a vector over some field `\\GF{q^m}`, the function converts it\n into a matrix over `\\GF{q}`.\n\n INPUT:\n\n - ``c`` -- a vector over some field `\\GF{q^m}`; or a matrix over `\\GF{q}`\n\n - ``sub_field`` -- (default: ``None``) a sub field of `\\GF{q^m}`. If not\n specified, it is the prime subfield `\\GF{p}` of `\\GF{q^m}`.\n\n - ``basis`` -- (default: ``None``) a basis of `\\GF{q^m}` as a vector space over\n ``sub_field``. If not specified, given that `q = p^s`, let\n `1,\\beta,\\ldots,\\beta^{sm}` be the power basis that SageMath uses to\n represent `\\GF{q^m}`. The default basis is then `1,\\beta,\\ldots,\\beta^{m-1}`.\n\n EXAMPLES::\n\n sage: from sage.coding.linear_rank_metric import rank_weight\n sage: x = GF(64).gen()\n sage: a = vector(GF(64), (x + 1, x + 1, 1))\n sage: rank_weight(a, GF(4))\n 2\n ' if is_Vector(c): c = to_matrix_representation(c, sub_field, basis) return c.rank()
def rank_distance(a, b, sub_field=None, basis=None): '\n Return the rank of ``a`` - ``b`` as a matrix over ``sub_field``.\n\n Take two vectors ``a``, ``b`` over some field `\\GF{q^m}`. This function\n converts them to matrices over `\\GF{q}` and calculates the rank of their\n difference.\n\n If ``sub_field`` is not specified, we take the prime subfield `\\GF{q}` of\n `\\GF{q^m}`.\n\n INPUT:\n\n - ``a`` -- a vector over some field `\\GF{q^m}`\n\n - ``b`` -- a vector over some field `\\GF{q^m}`\n\n - ``sub_field`` -- (default: ``None``) a sub field of `\\GF{q^m}`. If not\n specified, it is the prime subfield `\\GF{p}` of `\\GF{q^m}`.\n\n - ``basis`` -- (default: ``None``) a basis of `\\GF{q^m}` as a vector space over\n ``sub_field``. If not specified, given that `q = p^s`, let\n `1,\\beta,\\ldots,\\beta^{sm}` be the power basis that SageMath uses to\n represent `\\GF{q^m}`. The default basis is then `1,\\beta,\\ldots,\\beta^{m-1}`.\n\n EXAMPLES::\n\n sage: from sage.coding.linear_rank_metric import rank_distance\n sage: x = GF(64).gen()\n sage: a = vector(GF(64), (x + 1, x + 1, 1))\n sage: b = vector(GF(64), (1, 0, 0))\n sage: rank_distance(a, b, GF(4))\n 2\n\n sage: c = vector(GF(4), (1, 0, 0))\n sage: rank_distance(a, c, GF(4))\n Traceback (most recent call last):\n ...\n ValueError: The base field of (z6 + 1, z6 + 1, 1) and (1, 0, 0) has to be the same\n\n sage: d = Matrix(GF(64), (1, 0, 0))\n sage: rank_distance(a, d, GF(64))\n Traceback (most recent call last):\n ...\n TypeError: Both inputs have to be vectors\n\n sage: e = vector(GF(64), (1, 0))\n sage: rank_distance(a, e, GF(64))\n Traceback (most recent call last):\n ...\n ValueError: The length of (z6 + 1, z6 + 1, 1) and (1, 0) has to be the same\n ' if (not (a.base_ring() == b.base_ring())): raise ValueError('The base field of {} and {} has to be the same'.format(a, b)) if (not (is_Vector(a) and is_Vector(b))): raise TypeError('Both inputs have to be vectors') if (not (len(a) == len(b))): raise ValueError('The length of {} and {} has to be the same'.format(a, b)) a = to_matrix_representation(a, sub_field, basis) b = to_matrix_representation(b, sub_field, basis) return (a - b).rank()
class AbstractLinearRankMetricCode(AbstractLinearCodeNoMetric): '\n Abstract class for linear rank metric codes.\n\n This class contains methods that can be used on families of linear rank\n metric codes. Every linear rank metric code class should inherit from this\n abstract class.\n\n This class is intended for codes which are linear over the ``base_field``.\n\n Codewords of rank metric codes have two representations. They can either be\n written as a vector of length `n` over `\\GF{q^m}`, or an `m \\times n` matrix\n over `\\GF{q}`. This implementation principally uses the vector representation.\n However, one can always get the matrix representation using the\n :meth:`sage.coding.linear_rank_metric.AbstractLinearRankMetricCode.to_matrix`\n method. To go back to a vector, use the\n :meth:`sage.coding.linear_rank_metric.AbstractLinearRankMetricCode.from_matrix`\n method.\n\n Instructions on how to make a new family of rank metric codes is analogous\n to making a new family of linear codes over the Hamming metric, instructions\n for which are in :class:`sage.coding.linear_code.AbstractLinearCode`. For an\n example on, see\n :meth:`sage.coding.linear_rank_metric.AbstractLinearRankMetricCode.__init__`\n\n .. WARNING::\n\n A lot of methods of the abstract class rely on the knowledge of a generator matrix.\n It is thus strongly recommended to set an encoder with a generator matrix implemented\n as a default encoder.\n ' _registered_encoders = {} _registered_decoders = {} def __init__(self, base_field, sub_field, length, default_encoder_name, default_decoder_name, basis=None): '\n Initialize mandatory parameters that every linear rank metric code has.\n\n This method only exists for inheritance purposes as it initializes\n parameters that need to be known by every linear rank metric code.\n The class :class:`sage.coding.linear_rank_metric.AbstractLinearRankMetricCode`\n should never be directly instantiated.\n\n INPUT:\n\n - ``base_field`` -- the base field of ``self``\n\n - ``sub_field`` -- the sub field of ``self``\n\n - ``length`` -- the length of ``self`` (a Python int or a Sage Integer),\n must be > 0 and at most the degree of the field extension\n\n - ``default_encoder_name`` -- the name of the default encoder of ``self``\n\n - ``default_decoder_name`` -- the name of the default decoder of ``self``\n\n - ``basis`` -- (default: ``None``) a basis of `\\GF{q^m}` as a vector space over\n ``sub_field``. If not specified, given that `q = p^s`, let\n `1,\\beta,\\ldots,\\beta^{sm}` be the power basis that SageMath uses to\n represent `\\GF{q^m}`. The default basis is then `1,\\beta,\\ldots,\\beta^{m-1}`.\n\n EXAMPLES:\n\n The following example demonstrates how to use subclass\n `AbstractLinearRankMetricCode` for representing a new family of rank\n metric codes. The example is a rank repetition code::\n\n sage: from sage.coding.linear_rank_metric import AbstractLinearRankMetricCode\n sage: class RankRepetitionCode(AbstractLinearRankMetricCode):\n ....: def __init__(self, base_field, sub_field, length):\n ....: super().__init__(base_field, sub_field, length,\n ....: "GeneratorMatrix", "NearestNeighbor")\n ....: beta = base_field.gen()\n ....: self._generator_matrix = matrix(base_field,\n ....: [[beta^i for i in range(length)]])\n ....: def generator_matrix(self):\n ....: return self._generator_matrix\n ....: def _repr_(self):\n ....: return "[%d, %d] rank-metric repetition code over GF(%s)" % (self.length(), self.dimension(), self.base_field().cardinality())\n\n We now instantiate a member of our newly made code family::\n\n sage: C = RankRepetitionCode(GF(8), GF(2), 3)\n\n We can check its existence and parameters::\n\n sage: C\n [3, 1] rank-metric repetition code over GF(8)\n\n We can encode a vector::\n\n sage: word = vector(C.base_field(), [1])\n sage: E = codes.encoders.LinearCodeSystematicEncoder(C)\n sage: codeword = E(word)\n sage: codeword\n (1, z3, z3^2)\n\n We can get the matrix representation of the codeword::\n\n sage: C.matrix_form_of_vector(codeword)\n [1 0 0]\n [0 1 0]\n [0 0 1]\n\n We can decode the vector representation of the codeword::\n\n sage: D = codes.decoders.LinearRankMetricCodeNearestNeighborDecoder(C)\n sage: D.decode_to_code(codeword)\n (1, z3, z3^2)\n sage: D.decode_to_message(codeword)\n (1)\n\n We can check that it is truly a part of the framework category::\n\n sage: C.parent()\n <class \'__main__.RankRepetitionCode_with_category\'>\n sage: C.category()\n Category of facade finite dimensional vector spaces with basis\n over Finite Field in z3 of size 2^3\n\n And any method that works on rank metric linear codes works for our new dummy code::\n\n sage: C.minimum_distance()\n 3\n sage: C.metric()\n \'rank\'\n\n TESTS:\n\n If ``sub_field`` is not a field, an error is raised::\n\n sage: C = RankRepetitionCode(GF(8), ZZ, 3)\n Traceback (most recent call last):\n ...\n ValueError: \'sub_field\' must be a field (and Integer Ring is not one)\n\n If ``sub_field`` is not a subfield of ``base_field``, an error is raised::\n\n sage: C = RankRepetitionCode(GF(8), GF(3), 2)\n Traceback (most recent call last):\n ...\n ValueError: \'sub_field\' has to be a subfield of \'base_field\'\n ' self._registered_decoders['NearestNeighbor'] = LinearRankMetricCodeNearestNeighborDecoder if (not sub_field.is_field()): raise ValueError("'sub_field' must be a field (and {} is not one)".format(sub_field)) if (not (sub_field.degree().divides(base_field.degree()) and (sub_field.prime_subfield() == base_field.prime_subfield()))): raise ValueError("'sub_field' has to be a subfield of 'base_field'") m = (base_field.degree() // sub_field.degree()) self._extension_degree = m self._sub_field = sub_field self._generic_constructor = LinearRankMetricCode super().__init__(base_field, length, default_encoder_name, default_decoder_name, 'rank') def sub_field(self): '\n Return the sub field of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: C.sub_field()\n Finite Field in z2 of size 2^2\n ' return self._sub_field def extension_degree(self): '\n Return `m`, the degree of the field extension of ``self``.\n\n Let ``base_field`` be `\\GF{q^m}` and ``sub_field`` be `\\GF{q}`. Then this\n function returns `m`.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: C.extension_degree()\n 3\n ' return self._extension_degree def field_extension(self): '\n Return the field extension of ``self``.\n\n Let ``base_field`` be some field `\\GF{q^m}` and ``sub_field`` `\\GF{q}`.\n This function returns the vector space of dimension `m` over `\\GF{q}`.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: C.field_extension()\n Vector space of dimension 3 over Finite Field in z2 of size 2^2\n ' return self.base_field().vector_space(self.sub_field(), map=False) def rank_distance_between_vectors(self, left, right): '\n Return the rank of the matrix of ``left`` - ``right``.\n\n INPUT:\n\n - ``left`` -- a vector over the ``base_field`` of ``self``\n\n - ``right`` -- a vector over the ``base_field`` of ``self``\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: x = GF(64).gen()\n sage: a = vector(GF(64), (x + 1, x + 1, 1))\n sage: b = vector(GF(64), (1, 0, 0))\n sage: C.rank_distance_between_vectors(a, b)\n 2\n ' return rank_distance(left, right, self.sub_field()) def minimum_distance(self): '\n Return the minimum distance of ``self``.\n\n This algorithm simply iterates over all the elements of the code and\n returns the minimum weight.\n\n EXAMPLES::\n\n sage: F.<a> = GF(8)\n sage: G = Matrix(F, [[1,a,a^2,0]])\n sage: C = codes.LinearRankMetricCode(G, GF(2))\n sage: C.minimum_distance()\n 3\n ' d = Infinity for c in self: if (c == self.zero()): continue d = min(self.rank_weight_of_vector(c), d) return d def rank_weight_of_vector(self, word): '\n Return the weight of the word, i.e. its rank.\n\n INPUT:\n\n - ``word`` -- a vector over the ``base_field`` of ``self``\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: x = GF(64).gen()\n sage: a = vector(GF(64), (x + 1, x + 1, 1))\n sage: C.rank_weight_of_vector(a)\n 2\n ' return rank_weight(word, self.sub_field()) def matrix_form_of_vector(self, word): '\n Return the matrix representation of a word.\n\n INPUT:\n\n - ``word`` -- a vector over the ``base_field`` of ``self``\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: x = GF(64).gen()\n sage: a = vector(GF(64), (x + 1, x + 1, 1))\n sage: C.matrix_form_of_vector(a)\n [1 1 1]\n [1 1 0]\n [0 0 0]\n ' return to_matrix_representation(word, self.sub_field()) def vector_form_of_matrix(self, word): '\n Return the vector representation of a word.\n\n INPUT:\n\n - ``word`` -- a matrix over the ``sub_field`` of ``self``\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: x = GF(64).gen()\n sage: m = Matrix(GF(4), [[1, 1, 1], [1, 1, 0], [0, 0, 0]])\n sage: C.vector_form_of_matrix(m)\n (z6 + 1, z6 + 1, 1)\n ' return from_matrix_representation(word, self.base_field())
class LinearRankMetricCode(AbstractLinearRankMetricCode): '\n Linear rank metric codes over a finite field, represented using a\n generator matrix.\n\n This class should be used for arbitrary and unstructured linear rank metric\n codes. This means that basic operations on the code, such as the computation\n of the minimum distance, will use generic, slow algorithms.\n\n If you are looking for constructing a code from a more specific family, see\n if the family has been implemented by investigating ``codes.<tab>``. These\n more specific classes use properties particular to that family to allow\n faster algorithms, and could also have family-specific methods.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: C\n [3, 2] linear rank metric code over GF(64)/GF(4)\n sage: C.base_field()\n Finite Field in z6 of size 2^6\n sage: C.sub_field()\n Finite Field in z2 of size 2^2\n sage: C.length()\n 3\n sage: C.dimension()\n 2\n sage: C[2]\n (z6, z6, 0)\n sage: E = codes.encoders.LinearCodeGeneratorMatrixEncoder(C)\n sage: word = vector(C.base_field(), [1, 0])\n sage: E(word)\n (1, 1, 0)\n ' def __init__(self, generator, sub_field=None, basis=None): '\n See the docstring for :meth:`LinearRankMetricCode`.\n\n INPUT:\n\n - ``generator`` -- a generator matrix over the ``base_field`` with\n dimension `k \\times n`, where `k` is the dimension of the code and\n `n` its length; or a code over a finite field\n\n - ``sub_field`` -- (default: ``None``) the sub field of ``self``, if not\n specified, it is the prime field of ``base_field``\n\n - ``basis`` -- (default: ``None``) a basis of `\\GF{q^m}` as a vector space over\n ``sub_field``. If not specified, given that `q = p^s`, let\n `1,\\beta,\\ldots,\\beta^{sm}` be the power basis that SageMath uses to\n represent `\\GF{q^m}`. The default basis is then `1,\\beta,\\ldots,\\beta^{m-1}`.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4)) # indirect doctest\n sage: C\n [3, 2] linear rank metric code over GF(64)/GF(4)\n ' base_field = generator.base_ring() if (not base_field.is_field()): raise ValueError("'generator' must be defined on a field (not a ring)") if (not sub_field): sub_field = base_field.prime_subfield() try: gen_basis = None if hasattr(generator, 'nrows'): if (generator.rank() < generator.nrows()): gen_basis = generator.row_space().basis() else: gen_basis = generator.basis() if (gen_basis is not None): from sage.matrix.constructor import matrix generator = matrix(base_field, gen_basis) if (generator.nrows() == 0): raise ValueError('this linear code contains no non-zero vector') except AttributeError: generator = generator.generator_matrix() self._generator_matrix = generator self._length = generator.ncols() super().__init__(base_field, sub_field, self._length, 'GeneratorMatrix', 'NearestNeighbor', basis) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: C\n [3, 2] linear rank metric code over GF(64)/GF(4)\n ' R = self.base_field() S = self.sub_field() if (R and (S in Fields())): return ('[%s, %s] linear rank metric code over GF(%s)/GF(%s)' % (self.length(), self.dimension(), R.cardinality(), S.cardinality())) else: return ('[%s, %s] linear rank metric code over %s/%s' % (self.length(), self.dimension(), R, S)) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: latex(C)\n [3, 2]\\textnormal{ Linear rank metric code over }\\Bold{F}_{2^{6}}/\\Bold{F}_{2^{2}}\n ' return ('[%s, %s]\\textnormal{ Linear rank metric code over }%s/%s' % (self.length(), self.dimension(), self.base_field()._latex_(), self.sub_field()._latex_())) def generator_matrix(self, encoder_name=None, **kwargs): '\n Return a generator matrix of ``self``.\n\n INPUT:\n\n - ``encoder_name`` -- (default: ``None``) name of the encoder which will be\n used to compute the generator matrix. ``self._generator_matrix``\n will be returned if default value is kept.\n\n - ``kwargs`` -- all additional arguments are forwarded to the construction of the\n encoder that is used.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: C.generator_matrix()\n [1 1 0]\n [0 0 1]\n ' if ((encoder_name is None) or (encoder_name == 'GeneratorMatrix')): g = self._generator_matrix else: g = super().generator_matrix(encoder_name, **kwargs) g.set_immutable() return g
class LinearRankMetricCodeNearestNeighborDecoder(Decoder): '\n Construct a decoder for Linear Rank Metric Codes.\n\n This decoder will decode to the nearest codeword found.\n ' def __init__(self, code): '\n\n INPUT:\n\n - ``code`` -- A code associated to this decoder\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: D = codes.decoders.LinearRankMetricCodeNearestNeighborDecoder(C)\n sage: D\n Nearest neighbor decoder for [3, 2] linear rank metric code over GF(64)/GF(4)\n ' super().__init__(code, code.ambient_space(), code._default_encoder_name) def __eq__(self, other): '\n Test equality between LinearRankMetricCodeNearestNeighborDecoder objects.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: D1 = codes.decoders.LinearRankMetricCodeNearestNeighborDecoder(C)\n sage: D2 = codes.decoders.LinearRankMetricCodeNearestNeighborDecoder(C)\n sage: D1 == D2\n True\n ' return (isinstance(other, LinearRankMetricCodeNearestNeighborDecoder) and (self.code() == other.code())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: D = codes.decoders.LinearRankMetricCodeNearestNeighborDecoder(C)\n sage: D\n Nearest neighbor decoder for [3, 2] linear rank metric code over GF(64)/GF(4)\n ' return ('Nearest neighbor decoder for %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(64), [[1,1,0], [0,0,1]])\n sage: C = codes.LinearRankMetricCode(G, GF(4))\n sage: D = codes.decoders.LinearRankMetricCodeNearestNeighborDecoder(C)\n sage: latex(D)\n \\textnormal{Nearest neighbor decoder for }[3, 2]\\textnormal{ Linear rank metric code over }\\Bold{F}_{2^{6}}/\\Bold{F}_{2^{2}}\n ' return ('\\textnormal{Nearest neighbor decoder for }%s' % self.code()._latex_()) def decode_to_code(self, r): "\n Corrects the errors in ``word`` and returns a codeword.\n\n INPUT:\n\n - ``r`` -- a codeword of ``self``\n\n OUTPUT:\n\n - a vector of ``self``'s message space\n\n EXAMPLES::\n\n sage: F.<a> = GF(4)\n sage: G = Matrix(F, [[1,1,0]])\n sage: C = codes.LinearRankMetricCode(G, GF(2))\n sage: D = codes.decoders.LinearRankMetricCodeNearestNeighborDecoder(C)\n sage: D.decode_to_code(vector(F, [a, a, 1]))\n (a, a, 0)\n " C = self.code() c_min = C.zero() h_min = C.rank_weight_of_vector(r) for c in C: if (C.rank_weight_of_vector((c - r)) < h_min): h_min = C.rank_weight_of_vector((c - r)) c_min = c c_min.set_immutable() return c_min def decoding_radius(self): '\n Return maximal number of errors ``self`` can decode.\n\n EXAMPLES::\n\n sage: F.<a> = GF(8)\n sage: G = Matrix(F, [[1,a,a^2,0]])\n sage: C = codes.LinearRankMetricCode(G, GF(2))\n sage: D = codes.decoders.LinearRankMetricCodeNearestNeighborDecoder(C)\n sage: D.decoding_radius()\n 1\n ' return ((self.code().minimum_distance() - 1) // 2)
class ParityCheckCode(AbstractLinearCode): '\n Representation of a parity-check code.\n\n INPUT:\n\n - ``base_field`` -- the base field over which ``self`` is defined.\n\n - ``dimension`` -- the dimension of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.ParityCheckCode(GF(5), 7)\n sage: C\n [8, 7] parity-check code over GF(5)\n ' _registered_encoders = {} _registered_decoders = {} def __init__(self, base_field=GF(2), dimension=7): '\n Initialize mandatory parameters for a parity-check code object.\n\n INPUT:\n\n - ``base_field`` -- the base field over which ``self`` is defined\n or GF(2) if no base_field.\n\n - ``dimension`` -- the dimension of ``self`` or 7 if no dimension.\n\n EXAMPLES::\n\n sage: C = codes.ParityCheckCode(GF(5), 7)\n sage: C\n [8, 7] parity-check code over GF(5)\n ' if (not base_field.is_finite()): raise ValueError('base_field has to be a finite field') if (not isinstance(dimension, (Integer, int))): raise ValueError('dimension must be an integer') self._dimension = dimension super().__init__(base_field, (dimension + 1), 'ParityCheckCodeGeneratorMatrixEncoder', 'Syndrome') def __eq__(self, other): '\n Test equality of parity-check code objects.\n\n EXAMPLES::\n\n sage: C1 = codes.ParityCheckCode(GF(5), 7)\n sage: C2 = codes.ParityCheckCode(GF(5), 7)\n sage: C1 == C2\n True\n ' return (isinstance(other, ParityCheckCode) and (self.base_field() == other.base_field()) and (self.dimension() == other.dimension())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.ParityCheckCode(GF(5), 7)\n sage: C\n [8, 7] parity-check code over GF(5)\n ' return ('[%s, %s] parity-check code over GF(%s)' % (self.length(), self.dimension(), self.base_field().cardinality())) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.ParityCheckCode(GF(5), 7)\n sage: latex(C)\n [8, 7] \\textnormal{parity-check code over } \\Bold{F}_{5}\n ' return ('[%s, %s] \\textnormal{parity-check code over } %s' % (self.length(), self.dimension(), self.base_field()._latex_())) def minimum_distance(self): '\n Return the minimum distance of ``self``.\n\n It is always 2 as ``self`` is a parity-check code.\n\n EXAMPLES::\n\n sage: C = codes.ParityCheckCode(GF(5), 7)\n sage: C.minimum_distance()\n 2\n ' return 2
class ParityCheckCodeGeneratorMatrixEncoder(LinearCodeGeneratorMatrixEncoder): '\n Encoder for parity-check codes which uses a generator matrix to obtain\n codewords.\n\n INPUT:\n\n - ``code`` -- the associated code of this encoder.\n\n EXAMPLES::\n\n sage: C = codes.ParityCheckCode(GF(5), 7)\n sage: E = codes.encoders.ParityCheckCodeGeneratorMatrixEncoder(C)\n sage: E\n Generator matrix-based encoder for [8, 7] parity-check code over GF(5)\n\n Actually, we can construct the encoder from ``C`` directly::\n\n sage: E = C.encoder("ParityCheckCodeGeneratorMatrixEncoder")\n sage: E\n Generator matrix-based encoder for [8, 7] parity-check code over GF(5)\n ' def __init__(self, code): '\n TESTS:\n\n If ``code`` is not a parity-check code, an error is raised::\n\n sage: C = codes.random_linear_code(GF(11), 10, 4)\n sage: codes.encoders.ParityCheckCodeGeneratorMatrixEncoder(C)\n Traceback (most recent call last):\n ...\n ValueError: code has to be a parity-check code\n ' if (not isinstance(code, ParityCheckCode)): raise ValueError('code has to be a parity-check code') super().__init__(code) def generator_matrix(self): '\n Return a generator matrix of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.ParityCheckCode(GF(5),7)\n sage: E = codes.encoders.ParityCheckCodeGeneratorMatrixEncoder(C)\n sage: E.generator_matrix()\n [1 0 0 0 0 0 0 4]\n [0 1 0 0 0 0 0 4]\n [0 0 1 0 0 0 0 4]\n [0 0 0 1 0 0 0 4]\n [0 0 0 0 1 0 0 4]\n [0 0 0 0 0 1 0 4]\n [0 0 0 0 0 0 1 4]\n ' k = self.code().dimension() field = self.code().base_field() G = identity_matrix(field, k) G = G.augment(vector(field, ([(- field.one())] * k))) G.set_immutable() return G
class ParityCheckCodeStraightforwardEncoder(Encoder): '\n Encoder for parity-check codes which computes the sum of message symbols\n and appends its opposite to the message to obtain codewords.\n\n INPUT:\n\n - ``code`` -- the associated code of this encoder.\n\n EXAMPLES::\n\n sage: C = codes.ParityCheckCode(GF(5), 7)\n sage: E = codes.encoders.ParityCheckCodeStraightforwardEncoder(C)\n sage: E\n Parity-check encoder for the [8, 7] parity-check code over GF(5)\n\n Actually, we can construct the encoder from ``C`` directly::\n\n sage: E = C.encoder("ParityCheckCodeStraightforwardEncoder")\n sage: E\n Parity-check encoder for the [8, 7] parity-check code over GF(5)\n ' def __init__(self, code): '\n TESTS:\n\n If ``code`` is not a parity-check code, an error is raised::\n\n sage: C = codes.random_linear_code(GF(11), 10, 4)\n sage: codes.encoders.ParityCheckCodeStraightforwardEncoder(C)\n Traceback (most recent call last):\n ...\n ValueError: code has to be a parity-check code\n ' if (not isinstance(code, ParityCheckCode)): raise ValueError('code has to be a parity-check code') super().__init__(code) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.ParityCheckCode(GF(5), 7)\n sage: codes.encoders.ParityCheckCodeStraightforwardEncoder(C)\n Parity-check encoder for the [8, 7] parity-check code over GF(5)\n ' return ('Parity-check encoder for the %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.ParityCheckCode(GF(5), 7)\n sage: E = codes.encoders.ParityCheckCodeStraightforwardEncoder(C)\n sage: latex(E)\n \\textnormal{Parity-check encoder for the } [8, 7] \\textnormal{parity-check code over } \\Bold{F}_{5}\n ' return ('\\textnormal{Parity-check encoder for the } %s' % self.code()._latex_()) def __eq__(self, other): '\n Test equality of parity-check code objects.\n\n EXAMPLES::\n\n sage: C1 = codes.ParityCheckCode(GF(5), 7)\n sage: C2 = codes.ParityCheckCode(GF(5), 7)\n sage: C1 == C2\n True\n ' return (isinstance(other, ParityCheckCodeStraightforwardEncoder) and (self.code() == other.code())) def encode(self, message): '\n Transform the vector ``message`` into a codeword of :meth:`code`.\n\n INPUT:\n\n - ``message`` -- A ``self.code().dimension()``-vector from the message\n space of ``self``.\n\n OUTPUT:\n\n - A codeword in associated code of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.ParityCheckCode(GF(5),7)\n sage: message = vector(C.base_field(),[1,0,4,2,0,3,2])\n sage: C.encode(message)\n (1, 0, 4, 2, 0, 3, 2, 3)\n ' parity = self.code().base_field().zero() for i in message.list(): parity += i return vector(self.code().base_field(), (message.list() + [(- parity)])) def unencode_nocheck(self, word): '\n Return the message corresponding to the vector ``word``.\n\n Use this method with caution: it does not check if ``word``\n belongs to the code.\n\n INPUT:\n\n - ``word`` -- A ``self.code().length()``-vector from the ambiant space\n of ``self``.\n\n OUTPUT:\n\n - A vector corresponding to the ``self.code().dimension()``-first\n symbols in ``word``.\n\n EXAMPLES::\n\n sage: C = codes.ParityCheckCode(GF(5), 7)\n sage: word = vector(C.base_field(), [1, 0, 4, 2, 0, 3, 2, 3])\n sage: E = codes.encoders.ParityCheckCodeStraightforwardEncoder(C)\n sage: E.unencode_nocheck(word)\n (1, 0, 4, 2, 0, 3, 2)\n ' return word[:(- 1)] def message_space(self): '\n Return the message space of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.ParityCheckCode(GF(5),7)\n sage: E = codes.encoders.ParityCheckCodeStraightforwardEncoder(C)\n sage: E.message_space()\n Vector space of dimension 7 over Finite Field of size 5\n ' return VectorSpace(self.code().base_field(), self.code().dimension())
def _puncture(v, points): '\n Return v punctured as the positions listed in ``points``.\n\n INPUT:\n\n - ``v`` -- a vector or a list of vectors\n\n - ``points`` -- a set of integers, or an integer\n\n EXAMPLES::\n\n sage: v = vector(GF(7), (2,3,0,2,1,5,1,5,6,5,3))\n sage: from sage.coding.punctured_code import _puncture\n sage: _puncture(v, {4, 3})\n (2, 3, 0, 5, 1, 5, 6, 5, 3)\n ' if (not isinstance(points, (Integer, int, set))): raise TypeError('points must be either a Sage Integer, a Python int, or a set') if isinstance(v, list): size = len(v[0]) S = VectorSpace(v[0].base_ring(), (size - len(points))) l = [] for i in v: new_v = [i[j] for j in range(size) if (j not in points)] l.append(S(new_v)) return l S = VectorSpace(v.base_ring(), (len(v) - len(points))) new_v = [v[i] for i in range(len(v)) if (i not in points)] return S(new_v)
def _insert_punctured_positions(l, punctured_points, value=None): '\n Return ``l`` with ``value`` inserted in the corresponding\n position from ``punctured_points``.\n\n INPUT:\n\n - ``l`` -- a list\n\n - ``punctured_points`` -- a set of integers\n\n - ``value`` -- (default: ``None``) an element to insert in every position\n given in``punctured_points``. If it is let to ``None``, a random value\n will be chosen for each insertion.\n\n EXAMPLES::\n\n sage: from sage.coding.punctured_code import _insert_punctured_positions\n sage: _insert_punctured_positions([1,2,3,4], {2,4,5}, 1)\n [1, 2, 1, 3, 1, 1, 4]\n ' F = l[0].base_ring() final = ([None] * (len(l) + len(punctured_points))) for i in punctured_points: if (value is None): final[i] = F.random_element() else: final[i] = value index = 0 for i in range(len(final)): if (final[i] is None): final[i] = l[index] index += 1 return final
class PuncturedCode(AbstractLinearCode): '\n Representation of a punctured code.\n\n - ``C`` -- A linear code\n\n - ``positions`` -- the positions where ``C`` will be punctured. It can be either an integer\n if one need to puncture only one position, a list or a set of positions to puncture.\n If the same position is passed several times, it will be considered only once.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: Cp\n Puncturing of [11, 5] linear code over GF(7) on position(s) [3]\n\n sage: Cp = codes.PuncturedCode(C, {3, 5})\n sage: Cp\n Puncturing of [11, 5] linear code over GF(7) on position(s) [3, 5]\n ' _registered_encoders = {} _registered_decoders = {} def __init__(self, C, positions): '\n TESTS:\n\n If one of the positions to puncture is bigger than the length of ``C``,\n an exception will be raised::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp = codes.PuncturedCode(C, {4,8,15})\n Traceback (most recent call last):\n ...\n ValueError: Positions to puncture must be positive integers smaller\n than the length of the provided code\n ' if (not isinstance(positions, (Integer, int, set, list))): raise TypeError('positions must be either a Sage Integer, a Python int, a set or a list') if (isinstance(positions, (list, set)) and (not all((isinstance(i, (int, Integer)) for i in positions)))): raise TypeError('if positions is a list or a set, it has to contain only Python ints or Sage Integers') if isinstance(positions, (Integer, int)): positions = {positions} if isinstance(positions, list): positions = set(positions) if (not isinstance(C, AbstractLinearCode)): raise ValueError('Provided code must be a linear code') if (not all(((i in range(C.length())) for i in positions))): raise ValueError('Positions to puncture must be positive integers smaller than the length of the provided code') super().__init__(C.base_ring(), (C.length() - len(positions)), 'PuncturedMatrix', 'OriginalCode') self._original_code = C self._positions = positions def __eq__(self, other): '\n Tests equality between two Punctured codes.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp1 = codes.PuncturedCode(C, 2)\n sage: Cp2 = codes.PuncturedCode(C, 2)\n sage: Cp1 == Cp2\n True\n ' return (isinstance(other, PuncturedCode) and (self.punctured_positions() == other.punctured_positions()) and (self.original_code() == other.original_code())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: Cp\n Puncturing of [11, 5] linear code over GF(7) on position(s) [3]\n ' return ('Puncturing of %s on position(s) %s' % (self.original_code(), list(self.punctured_positions()))) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: latex(Cp)\n \\textnormal{Puncturing of [11, 5] linear code over GF(7) on position(s) } [3]\n ' return ('\\textnormal{Puncturing of %s on position(s) } %s' % (self.original_code(), list(self.punctured_positions()))) def punctured_positions(self): '\n Return the list of positions which were punctured on the original code.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: Cp.punctured_positions()\n {3}\n ' return self._positions def original_code(self): '\n Return the linear code which was punctured to get ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: Cp.original_code()\n [11, 5] linear code over GF(7)\n ' return self._original_code def dimension(self): '\n Return the dimension of ``self``.\n\n EXAMPLES::\n\n sage: set_random_seed(42)\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: Cp.dimension()\n 5\n ' if hasattr(self, '_dimension'): return self._dimension self._dimension = self.generator_matrix().rank() return self._dimension def random_element(self, *args, **kwds): "\n Return a random codeword of ``self``.\n\n This method does not trigger the computation of\n ``self``'s :meth:`sage.coding.linear_code_no_metric.generator_matrix`.\n\n INPUT:\n\n - ``agrs``, ``kwds`` - extra positional arguments passed to\n :meth:`sage.modules.free_module.random_element`.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: Cp.random_element() in Cp\n True\n " C_original = self.original_code() m = (C_original.base_ring() ** C_original.dimension()).random_element() c = C_original.encode(m) return _puncture(c, self.punctured_positions()) def encode(self, m, original_encode=False, encoder_name=None, **kwargs): "\n Transforms an element of the message space into an element of the code.\n\n INPUT:\n\n - ``m`` -- a vector of the message space of the code.\n\n - ``original_encode`` -- (default: ``False``) if this is set to ``True``,\n ``m`` will be encoded using an Encoder of ``self``'s :meth:`original_code`.\n This allow to avoid the computation of a generator matrix for ``self``.\n\n - ``encoder_name`` -- (default: ``None``) Name of the encoder which will be used\n to encode ``word``. The default encoder of ``self`` will be used if\n default value is kept\n\n OUTPUT:\n\n - an element of ``self``\n\n EXAMPLES::\n\n sage: M = matrix(GF(7), [[1, 0, 0, 0, 3, 4, 6],\n ....: [0, 1, 0, 6, 1, 6, 4],\n ....: [0, 0, 1, 5, 2, 2, 4]])\n sage: C_original = LinearCode(M)\n sage: Cp = codes.PuncturedCode(C_original, 2)\n sage: m = vector(GF(7), [1, 3, 5])\n sage: Cp.encode(m)\n (1, 3, 5, 5, 0, 2)\n " if original_encode: c = self.original_code().encode(m, encoder_name, **kwargs) return _puncture(c, self.punctured_positions, self) return self.encoder(encoder_name, **kwargs).encode(m) @cached_method def structured_representation(self): '\n Return ``self`` as a structured code object.\n\n If ``self`` has a specific structured representation (e.g. a punctured GRS code is\n a GRS code too), it will return this representation, else it returns a\n :class:`sage.coding.linear_code.LinearCode`.\n\n EXAMPLES:\n\n We consider a GRS code::\n\n sage: C_grs = codes.GeneralizedReedSolomonCode(GF(59).list()[:40], 12)\n\n A punctured GRS code is still a GRS code::\n\n sage: Cp_grs = codes.PuncturedCode(C_grs, 3)\n sage: Cp_grs.structured_representation()\n [39, 12, 28] Reed-Solomon Code over GF(59)\n\n Another example with structureless linear codes::\n\n sage: set_random_seed(42)\n sage: C_lin = codes.random_linear_code(GF(2), 10, 5)\n sage: Cp_lin = codes.PuncturedCode(C_lin, 2)\n sage: Cp_lin.structured_representation()\n [9, 5] linear code over GF(2)\n ' C = self.original_code() pts = copy(self.punctured_positions()) list_pts = list(pts) while isinstance(C, PuncturedCode): cur_pts = list(C.punctured_positions()) list_len = len(list_pts) for p in cur_pts: for i in range(list_len): if (p <= list_pts[i]): list_pts[i] += 1 list_pts += cur_pts C = C.original_code() return C._punctured_form(set(list_pts))
class PuncturedCodePuncturedMatrixEncoder(Encoder): "\n Encoder using original code generator matrix to compute the punctured code's one.\n\n INPUT:\n\n - ``code`` -- The associated code of this encoder.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: E = codes.encoders.PuncturedCodePuncturedMatrixEncoder(Cp)\n sage: E\n Punctured matrix-based encoder for the\n Puncturing of [11, 5] linear code over GF(7) on position(s) [3]\n " def __init__(self, code): '\n TESTS:\n\n If ``code`` is not a ``PuncturedCode``, an exception is raised::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: codes.encoders.PuncturedCodePuncturedMatrixEncoder(C)\n Traceback (most recent call last):\n ...\n TypeError: code has to be an instance of PuncturedCode class\n ' if (not isinstance(code, PuncturedCode)): raise TypeError('code has to be an instance of PuncturedCode class') super().__init__(code) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: E = codes.encoders.PuncturedCodePuncturedMatrixEncoder(Cp)\n sage: E\n Punctured matrix-based encoder for the Puncturing of [11, 5] linear code over GF(7) on position(s) [3]\n ' return ('Punctured matrix-based encoder for the %s' % self.code()) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: E = codes.encoders.PuncturedCodePuncturedMatrixEncoder(Cp)\n sage: latex(E)\n \\textnormal{Punctured matrix-based encoder for the }\\textnormal{Puncturing of [11, 5] linear code over GF(7) on position(s) } [3]\n ' return ('\\textnormal{Punctured matrix-based encoder for the }%s' % self.code()._latex_()) @cached_method def generator_matrix(self): '\n Return a generator matrix of the associated code of ``self``.\n\n EXAMPLES::\n\n sage: set_random_seed(10)\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: E = codes.encoders.PuncturedCodePuncturedMatrixEncoder(Cp)\n sage: E.generator_matrix()\n [1 0 0 0 0 5 2 6 0 6]\n [0 1 0 0 0 5 2 2 1 1]\n [0 0 1 0 0 6 2 4 0 4]\n [0 0 0 1 0 0 6 3 3 3]\n [0 0 0 0 1 0 1 3 4 3]\n ' C = self.code().original_code() pos = self.code().punctured_positions() M = C.generator_matrix() G = M.delete_columns(list(pos)) G = G.echelon_form() k = G.rank() M = G[:k] M.set_immutable() return M
class PuncturedCodeOriginalCodeDecoder(Decoder): '\n Decoder decoding through a decoder over the original code of its punctured code.\n\n INPUT:\n\n - ``code`` -- The associated code of this encoder\n\n - ``strategy`` -- (default: ``None``) the strategy used to decode.\n The available strategies are:\n\n * ``\'error-erasure\'`` -- uses an error-erasure decoder over the original\n code if available, fails otherwise.\n\n * ``\'random-values\'`` -- fills the punctured positions with random elements\n in ``code``\'s base field and tries to decode using\n the default decoder of the original code\n\n * ``\'try-all\'`` -- fills the punctured positions with every possible\n combination of symbols until decoding succeeds, or until every\n combination have been tried\n\n * ``None`` -- uses ``error-erasure`` if an error-erasure decoder is\n available, switch to ``random-values`` behaviour otherwise\n\n - ``original_decoder`` -- (default: ``None``) the decoder that will be used over the original code.\n It has to be a decoder object over the original code.\n This argument takes precedence over ``strategy``: if both ``original_decoder`` and ``strategy``\n are filled, ``self`` will use the ``original_decoder`` to decode over the original code.\n If ``original_decoder`` is set to ``None``, it will use the decoder picked by ``strategy``.\n\n - ``**kwargs`` -- all extra arguments are forwarded to original code\'s decoder\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, \'a\').list()[:15], 7)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: codes.decoders.PuncturedCodeOriginalCodeDecoder(Cp)\n Decoder of Puncturing of [15, 7, 9] Reed-Solomon Code over GF(16) on position(s) [3]\n through Error-Erasure decoder for [15, 7, 9] Reed-Solomon Code over GF(16)\n\n As seen above, if all optional are left blank, and if an error-erasure\n decoder is available, it will be chosen as the original decoder. Now, if\n one forces ``strategy`` to ``\'try-all\'`` or ``\'random-values\'``, the default\n decoder of the original code will be chosen, even if an error-erasure is\n available::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, \'a\').list()[:15], 7)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: D = codes.decoders.PuncturedCodeOriginalCodeDecoder(Cp, strategy="try-all")\n sage: "error-erasure" in D.decoder_type()\n False\n\n And if one fills ``original_decoder`` and ``strategy`` fields with\n contradictory elements, the ``original_decoder`` takes precedence::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, \'a\').list()[:15], 7)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: Dor = C.decoder("Gao")\n sage: D = codes.decoders.PuncturedCodeOriginalCodeDecoder(Cp, original_decoder=Dor,\n ....: strategy="error-erasure")\n sage: D.original_decoder() == Dor\n True\n ' def __init__(self, code, strategy=None, original_decoder=None, **kwargs): "\n TESTS:\n\n If ``code`` is not a ``PuncturedCode``, an exception is raised::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: codes.decoders.PuncturedCodeOriginalCodeDecoder(C)\n Traceback (most recent call last):\n ...\n TypeError: code has to be an instance of PuncturedCode class\n\n If one tries to pass an original_decoder whose associated code is not the original\n code of ``self``, it returns an error::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: C2 = codes.GeneralizedReedSolomonCode(GF(7).list()[:6], 3)\n sage: D = Cp.decoder(original_decoder = C2.decoder())\n Traceback (most recent call last):\n ...\n ValueError: Original decoder must have the original code of its associated punctured code as associated code\n\n If one tries to use ``'error-erasure'`` strategy when the original code has no such\n decoder, it returns an error::\n\n sage: C = codes.random_linear_code(GF(7), 11, 5)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: D = codes.decoders.PuncturedCodeOriginalCodeDecoder(Cp, strategy = 'error-erasure')\n Traceback (most recent call last):\n ...\n ValueError: Original code has no error-erasure decoder\n " if (not isinstance(code, PuncturedCode)): raise TypeError('code has to be an instance of PuncturedCode class') original_code = code.original_code() if (original_decoder is not None): if (not isinstance(original_decoder, Decoder)): raise TypeError('original_decoder must be a decoder object') if (not (original_decoder.code() == original_code)): raise ValueError('Original decoder must have the original code of its associated punctured code as associated code') if ('error-erasure' in original_decoder.decoder_type()): strategy = 'error-erasure' self._original_decoder = original_decoder elif (strategy == 'error-erasure'): error_erasure = False for D in original_code._registered_decoders.values(): if ('error-erasure' in D._decoder_type): error_erasure = True self._original_decoder = D(original_code, **kwargs) break if (not error_erasure): raise ValueError('Original code has no error-erasure decoder') elif ((strategy == 'random-values') or (strategy == 'try-all')): self._original_decoder = code.original_code().decoder(**kwargs) else: error_erasure = False for D in original_code._registered_decoders.values(): if ('error-erasure' in D._decoder_type): error_erasure = True self._original_decoder = D(original_code, **kwargs) break if (not error_erasure): self._original_decoder = original_code.decoder(**kwargs) self._strategy = strategy self._decoder_type = copy(self._decoder_type) self._decoder_type.remove('dynamic') self._decoder_type = self._original_decoder.decoder_type() super().__init__(code, code.ambient_space(), self._original_decoder.connected_encoder()) def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: D = codes.decoders.PuncturedCodeOriginalCodeDecoder(Cp)\n sage: D\n Decoder of Puncturing of [15, 7, 9] Reed-Solomon Code over GF(16) on position(s) [3] through Error-Erasure decoder for [15, 7, 9] Reed-Solomon Code over GF(16)\n\n " return ('Decoder of %s through %s' % (self.code(), self.original_decoder())) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: D = codes.decoders.PuncturedCodeOriginalCodeDecoder(Cp)\n sage: latex(D)\n \\textnormal{Decoder of } Puncturing of [15, 7, 9] Reed-Solomon Code over GF(16) on position(s) [3] \\textnormal{ through } Error-Erasure decoder for [15, 7, 9] Reed-Solomon Code over GF(16)\n " return ('\\textnormal{Decoder of } %s \\textnormal{ through } %s' % (self.code(), self.original_decoder())) def original_decoder(self): "\n Return the decoder over the original code that will be used to decode words of\n :meth:`sage.coding.decoder.Decoder.code`.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: D = codes.decoders.PuncturedCodeOriginalCodeDecoder(Cp)\n sage: D.original_decoder()\n Error-Erasure decoder for [15, 7, 9] Reed-Solomon Code over GF(16)\n " return self._original_decoder def decode_to_code(self, y): "\n Decode ``y`` to an element in :meth:`sage.coding.decoder.Decoder.code`.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: D = codes.decoders.PuncturedCodeOriginalCodeDecoder(Cp)\n sage: c = Cp.random_element()\n sage: Chan = channels.StaticErrorRateChannel(Cp.ambient_space(), 3)\n sage: y = Chan(c)\n sage: y in Cp\n False\n sage: D.decode_to_code(y) == c\n True\n " D = self.original_decoder() C = self.code() A = C.original_code().ambient_space() Cor = C.original_code() pts = C.punctured_positions() F = self.code().base_field() (zero, one) = (F.zero(), F.one()) if ('error-erasure' in D.decoder_type()): if isinstance(y, (tuple, list)): (y, e) = (y[0], y[1]) e_list = e.list() e_list = _insert_punctured_positions(e_list, pts, one) else: e_list = [(one if (i in pts) else zero) for i in range(Cor.length())] e = vector(GF(2), e_list) yl = y.list() yl = _insert_punctured_positions(yl, pts, zero) y = A(yl) return _puncture(D.decode_to_code((y, e)), pts) elif (self._strategy == 'try-all'): end = False yl = y.list() I = iter(VectorSpace(F, len(pts))) list_pts = list(pts) list_pts.sort() shift = 0 for i in list_pts: yl.insert((i + shift), zero) shift += 1 values = next(I) while (not end): try: shift = 0 for i in list_pts: yl[(i + shift)] = values[shift] shift += 1 y = A(yl) values = next(I) try: c_or = self.original_decoder().decode_to_code(y) end = True break except Exception: pass except StopIteration: raise DecodingError return _puncture(c_or, pts) A = Cor.ambient_space() yl = y.list() yl = _insert_punctured_positions(yl, pts) y = A(yl) return _puncture(D.decode_to_code(y), pts) def decoding_radius(self, number_erasures=None): "\n Return the maximal number of errors that ``self`` can decode.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'a').list()[:15], 7)\n sage: Cp = codes.PuncturedCode(C, 3)\n sage: D = codes.decoders.PuncturedCodeOriginalCodeDecoder(Cp)\n sage: D.decoding_radius(2)\n 2\n " punctured = len(self.code().punctured_positions()) D = self.original_decoder() if ((self._strategy != 'try-all') and ('error-erasure' not in D.decoder_type())): if ((D.decoding_radius() - punctured) >= 0): return (D.decoding_radius() - punctured) else: return 0 elif (('error-erasure' in D.decoder_type()) and (number_erasures is not None)): diff = (((self.code().original_code().minimum_distance() - number_erasures) - punctured) - 1) if (diff <= 0): raise ValueError('The number of erasures exceeds decoding capability') return (diff // 2) elif (('error-erasure' in D.decoder_type()) and (number_erasures is None)): raise ValueError('You must provide the number of erasures')
def _binomial_sum(n, k): '\n Return the sum of all binomials `\\binom{n}{i}`,\n with `i` ranging from `0` to `k` and including `k`.\n\n INPUT:\n\n - ``n, k`` - integers\n\n EXAMPLES::\n\n sage: from sage.coding.reed_muller_code import _binomial_sum\n sage: _binomial_sum(4, 2)\n 11\n ' s = 1 nCi = 1 for i in range(k): nCi = (((n - i) * nCi) // (i + 1)) s = (nCi + s) return s
def _multivariate_polynomial_interpolation(evaluation, order, polynomial_ring): '\n Return `f \\in \\GF{q}[X_1,...,X_m]` such that `f(\\mathbf a) = v[i(\\mathbf a)]`\n for all `\\mathbf a \\in \\GF{q^m}`, where `v \\in \\GF{q}^{q^m}` is a given\n vector of evaluations, and `i(a)` is a specific ordering of `\\GF{q^m}` (see below for details)\n\n The ordering `i(a)` is the one used by Sage when listing the elements\n of a Finite Field with a call to the method ``list``.\n\n In case the polynomial `f` does not exist, this method returns an arbitrary polynomial.\n\n INPUT:\n\n - ``evaluation`` -- A vector or a list of evaluation of the polynomial at all the points.\n\n - ``num_of_var`` -- The number of variables used in the polynomial to interpolate\n\n - ``order`` -- The degree of the polynomial to interpolate\n\n - ``polynomial_ring`` -- The Polynomial Ring the polynomial in question is from\n\n EXAMPLES::\n\n sage: from sage.coding.reed_muller_code import _multivariate_polynomial_interpolation\n sage: F = GF(3)\n sage: R.<x,y> = F[]\n sage: v = vector(F, [1, 2, 0, 0, 2, 1, 1, 1, 1])\n sage: _multivariate_polynomial_interpolation(v, 2, R)\n x*y + y^2 + x + y + 1\n\n If there does not exist\n ' def _interpolate(evaluation, num_of_var, order): if ((num_of_var == 0) or (order == 0)): return evaluation[0] base_field = polynomial_ring.base_ring() q = base_field.cardinality() n_by_q = (q ** (num_of_var - 1)) d = min((order + 1), q) multipoint_evaluation_list = [] uni_poly_ring = PolynomialRing(base_field, 'x') base_field_zero = base_field.zero() for k in range(n_by_q): iterator = iter(base_field) points = [] for i in range(d): xcoordinate = next(iterator) points.append((xcoordinate, evaluation[(k + (i * n_by_q))])) polyVector = uni_poly_ring.lagrange_polynomial(points).coefficients(sparse=False) if (len(polyVector) < d): polyVector += ([base_field_zero] * (d - len(polyVector))) multipoint_evaluation_list.append(polyVector) poly = polynomial_ring.zero() z = 1 x = polynomial_ring.gen((num_of_var - 1)) for k in range(d): poly = (poly + (z * _interpolate([multipoint_evaluation_list[i][k] for i in range(n_by_q)], (num_of_var - 1), (order - k)))) z *= x return poly return _interpolate(evaluation, polynomial_ring.ngens(), order)
def ReedMullerCode(base_field, order, num_of_var): '\n Return a Reed-Muller code.\n\n A Reed-Muller Code of order `r` and number of variables `m` over a finite field `F` is the set:\n\n .. MATH::\n\n \\{ (f(\\alpha_i)\\mid \\alpha_i \\in F^m) \\mid f \\in F[x_1,x_2,\\ldots,x_m], \\deg f \\leq r \\}\n\n INPUT:\n\n - ``base_field`` -- The finite field `F` over which the code is built.\n\n - ``order`` -- The order of the Reed-Muller Code, which is the maximum\n degree of the polynomial to be used in the code.\n\n - ``num_of_var`` -- The number of variables used in polynomial.\n\n .. WARNING::\n\n For now, this implementation only supports Reed-Muller codes whose order is less than q.\n Binary Reed-Muller codes must have their order less than or\n equal to their number of variables.\n\n EXAMPLES:\n\n We build a Reed-Muller code::\n\n sage: F = GF(3)\n sage: C = codes.ReedMullerCode(F, 2, 2)\n sage: C\n Reed-Muller Code of order 2 and 2 variables over Finite Field of size 3\n\n We ask for its parameters::\n\n sage: C.length()\n 9\n sage: C.dimension()\n 6\n sage: C.minimum_distance()\n 3\n\n If one provides a finite field of size 2, a Binary Reed-Muller code is built::\n\n sage: F = GF(2)\n sage: C = codes.ReedMullerCode(F, 2, 2)\n sage: C\n Binary Reed-Muller Code of order 2 and number of variables 2\n ' if (base_field not in FiniteFields()): raise ValueError('The parameter `base_field` must be a finite field') q = base_field.cardinality() if (q == 2): return BinaryReedMullerCode(order, num_of_var) else: return QAryReedMullerCode(base_field, order, num_of_var)
class QAryReedMullerCode(AbstractLinearCode): '\n Representation of a `q`-ary Reed-Muller code.\n\n For details on the definition of Reed-Muller codes, refer to\n :meth:`ReedMullerCode`.\n\n .. NOTE::\n\n It is better to use the aforementioned method rather than calling this\n class directly, as :meth:`ReedMullerCode` creates either a binary or a\n `q`-ary Reed-Muller code according to the arguments it receives.\n\n INPUT:\n\n - ``base_field`` -- A finite field, which is the base field of the code.\n\n - ``order`` -- The order of the Reed-Muller Code, i.e., the maximum degree\n of the polynomial to be used in the code.\n\n - ``num_of_var`` -- The number of variables used in polynomial.\n\n .. WARNING::\n\n For now, this implementation only supports Reed-Muller codes whose order\n is less than q.\n\n EXAMPLES::\n\n sage: from sage.coding.reed_muller_code import QAryReedMullerCode\n sage: F = GF(3)\n sage: C = QAryReedMullerCode(F, 2, 2)\n sage: C\n Reed-Muller Code of order 2 and 2 variables over Finite Field of size 3\n ' _registered_encoders = {} _registered_decoders = {} def __init__(self, base_field, order, num_of_var): '\n TESTS:\n\n Note that the order given cannot be greater than (q-1). An error is raised if that happens::\n\n sage: from sage.coding.reed_muller_code import QAryReedMullerCode\n sage: C = QAryReedMullerCode(GF(3), 4, 4)\n Traceback (most recent call last):\n ...\n ValueError: The order must be less than 3\n\n The order and the number of variable must be integers::\n\n sage: C = QAryReedMullerCode(GF(3),1.1,4)\n Traceback (most recent call last):\n ...\n ValueError: The order of the code must be an integer\n\n The base_field parameter must be a finite field::\n\n sage: C = QAryReedMullerCode(QQ,1,4)\n Traceback (most recent call last):\n ...\n ValueError: the input `base_field` must be a FiniteField\n ' if (base_field not in FiniteFields()): raise ValueError('the input `base_field` must be a FiniteField') if (not isinstance(order, (Integer, int))): raise ValueError('The order of the code must be an integer') if (not isinstance(num_of_var, (Integer, int))): raise ValueError('The number of variables must be an integer') q = base_field.cardinality() if (order >= q): raise ValueError(('The order must be less than %s' % q)) super().__init__(base_field, (q ** num_of_var), 'EvaluationVector', 'Syndrome') self._order = order self._num_of_var = num_of_var self._dimension = binomial((num_of_var + order), order) def order(self): '\n Return the order of ``self``.\n\n Order is the maximum degree of the polynomial used in the Reed-Muller code.\n\n EXAMPLES::\n\n sage: from sage.coding.reed_muller_code import QAryReedMullerCode\n sage: F = GF(59)\n sage: C = QAryReedMullerCode(F, 2, 4)\n sage: C.order()\n 2\n ' return self._order def number_of_variables(self): '\n Return the number of variables of the polynomial ring used in ``self``.\n\n EXAMPLES::\n\n sage: from sage.coding.reed_muller_code import QAryReedMullerCode\n sage: F = GF(59)\n sage: C = QAryReedMullerCode(F, 2, 4)\n sage: C.number_of_variables()\n 4\n ' return self._num_of_var def minimum_distance(self): '\n Return the minimum distance between two words in ``self``.\n\n The minimum distance of a `q`-ary Reed-Muller code with order `d` and\n number of variables `m` is `(q-d)q^{m-1}`\n\n EXAMPLES::\n\n sage: from sage.coding.reed_muller_code import QAryReedMullerCode\n sage: F = GF(5)\n sage: C = QAryReedMullerCode(F, 2, 4)\n sage: C.minimum_distance()\n 375\n ' d = self.order() q = self.base_field().cardinality() n = self.length() return (((q - d) * n) // q) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.coding.reed_muller_code import QAryReedMullerCode\n sage: F = GF(59)\n sage: C = QAryReedMullerCode(F, 2, 4)\n sage: C\n Reed-Muller Code of order 2 and 4 variables over Finite Field of size 59\n ' return ('Reed-Muller Code of order %s and %s variables over %s' % (self.order(), self.number_of_variables(), self.base_field())) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.coding.reed_muller_code import QAryReedMullerCode\n sage: F = GF(59)\n sage: C = QAryReedMullerCode(F, 2, 4)\n sage: latex(C)\n \\textnormal{Reed-Muller Code of order} 2 \\textnormal{and }4 \\textnormal{variables over} \\Bold{F}_{59}\n ' return ('\\textnormal{Reed-Muller Code of order} %s \\textnormal{and }%s \\textnormal{variables over} %s' % (self.order(), self.number_of_variables(), self.base_field()._latex_())) def __eq__(self, other): '\n Tests equality between Reed-Muller Code objects.\n\n EXAMPLES::\n\n sage: from sage.coding.reed_muller_code import QAryReedMullerCode\n sage: F = GF(59)\n sage: C1 = QAryReedMullerCode(F, 2, 4)\n sage: C2 = QAryReedMullerCode(GF(59), 2, 4)\n sage: C1.__eq__(C2)\n True\n ' return (isinstance(other, QAryReedMullerCode) and (self.base_field() == other.base_field()) and (self.order() == other.order()) and (self.number_of_variables() == other.number_of_variables()))
class BinaryReedMullerCode(AbstractLinearCode): '\n Representation of a binary Reed-Muller code.\n\n For details on the definition of Reed-Muller codes, refer to\n :meth:`ReedMullerCode`.\n\n .. NOTE::\n\n It is better to use the aforementioned method rather than calling this\n class directly, as :meth:`ReedMullerCode` creates either a binary or a\n `q`-ary Reed-Muller code according to the arguments it receives.\n\n\n INPUT:\n\n - ``order`` -- The order of the Reed-Muller Code, i.e., the maximum degree\n of the polynomial to be used in the code.\n\n - ``num_of_var`` -- The number of variables used in the polynomial.\n\n EXAMPLES:\n\n A binary Reed-Muller code can be constructed by simply giving the order of the code and the number of variables::\n\n sage: C = codes.BinaryReedMullerCode(2, 4)\n sage: C\n Binary Reed-Muller Code of order 2 and number of variables 4\n ' _registered_encoders = {} _registered_decoders = {} def __init__(self, order, num_of_var): '\n TESTS:\n\n If the order given is greater than the number of variables an error is raised::\n\n sage: C = codes.BinaryReedMullerCode(5, 4)\n Traceback (most recent call last):\n ...\n ValueError: The order must be less than or equal to 4\n\n The order and the number of variable must be integers::\n\n sage: C = codes.BinaryReedMullerCode(1.1,4)\n Traceback (most recent call last):\n ...\n ValueError: The order of the code must be an integer\n ' if (not isinstance(order, (Integer, int))): raise ValueError('The order of the code must be an integer') if (not isinstance(num_of_var, (Integer, int))): raise ValueError('The number of variables must be an integer') if (num_of_var < order): raise ValueError(('The order must be less than or equal to %s' % num_of_var)) super().__init__(GF(2), (2 ** num_of_var), 'EvaluationVector', 'Syndrome') self._order = order self._num_of_var = num_of_var self._dimension = _binomial_sum(num_of_var, order) def order(self): '\n Return the order of ``self``.\n\n Order is the maximum degree of the polynomial used in the Reed-Muller code.\n\n EXAMPLES::\n\n sage: C = codes.BinaryReedMullerCode(2, 4)\n sage: C.order()\n 2\n ' return self._order def number_of_variables(self): '\n Return the number of variables of the polynomial ring used in ``self``.\n\n EXAMPLES::\n\n sage: C = codes.BinaryReedMullerCode(2, 4)\n sage: C.number_of_variables()\n 4\n ' return self._num_of_var def minimum_distance(self): '\n Return the minimum distance of ``self``.\n\n The minimum distance of a binary Reed-Muller code of order `d` and\n number of variables `m` is `q^{m-d}`\n\n EXAMPLES::\n\n sage: C = codes.BinaryReedMullerCode(2, 4)\n sage: C.minimum_distance()\n 4\n ' return (2 ** (self.number_of_variables() - self.order())) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.BinaryReedMullerCode(2, 4)\n sage: C\n Binary Reed-Muller Code of order 2 and number of variables 4\n ' return ('Binary Reed-Muller Code of order %s and number of variables %s' % (self.order(), self.number_of_variables())) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.BinaryReedMullerCode(2, 4)\n sage: latex(C)\n \\textnormal{Binary Reed-Muller Code of order} 2 \\textnormal{and number of variables} 4\n ' return ('\\textnormal{Binary Reed-Muller Code of order} %s \\textnormal{and number of variables} %s' % (self.order(), self.number_of_variables())) def __eq__(self, other): '\n Tests equality between Reed-Muller Code objects.\n\n EXAMPLES::\n\n sage: C1 = codes.BinaryReedMullerCode(2, 4)\n sage: C2 = codes.BinaryReedMullerCode(2, 4)\n sage: C1.__eq__(C2)\n True\n ' return (isinstance(other, BinaryReedMullerCode) and (self.order() == other.order()) and (self.number_of_variables() == other.number_of_variables()))
class ReedMullerVectorEncoder(Encoder): '\n Encoder for Reed-Muller codes which encodes vectors into codewords.\n\n Consider a Reed-Muller code of order `r`, number of variables `m`, length `n`,\n dimension `k` over some finite field `F`.\n Let those variables be `(x_1, x_2, \\dots, x_m)`.\n We order the monomials by lowest power on lowest index variables. If we have\n three monomials `x_1 x_2`, `x_1 x_2^2` and `x_1^2 x_2`, the ordering is:\n `x_1 x_2 < x_1 x_2^2 < x_1^2 x_2`\n\n Let now `(v_1,v_2,\\ldots,v_k)` be a vector of `F`, which corresponds to the polynomial\n `f = \\Sigma^{k}_{i=1} v_i x_i`.\n\n Let `(\\beta_1, \\beta_2, \\ldots, \\beta_q)` be the elements of `F` ordered as they are\n returned by Sage when calling ``F.list()``.\n\n The aforementioned polynomial `f` is encoded as:\n\n `(f(\\alpha_{11},\\alpha_{12},\\ldots,\\alpha_{1m}),f(\\alpha_{21},\\alpha_{22},\\ldots,\n \\alpha_{2m}),\\ldots,f(\\alpha_{q^m1},\\alpha_{q^m2},\\ldots,\\alpha_{q^mm}))`\n\n with `\\alpha_{ij}=\\beta_{i \\bmod{q^j}}` for all `i`, `j)`.\n\n INPUT:\n\n - ``code`` -- The associated code of this encoder.\n\n EXAMPLES::\n\n sage: C1 = codes.ReedMullerCode(GF(2), 2, 4)\n sage: E1 = codes.encoders.ReedMullerVectorEncoder(C1)\n sage: E1\n Evaluation vector-style encoder for\n Binary Reed-Muller Code of order 2 and number of variables 4\n sage: C2 = codes.ReedMullerCode(GF(3), 2, 2)\n sage: E2 = codes.encoders.ReedMullerVectorEncoder(C2)\n sage: E2\n Evaluation vector-style encoder for\n Reed-Muller Code of order 2 and 2 variables over Finite Field of size 3\n\n Actually, we can construct the encoder from ``C`` directly::\n\n sage: C=codes.ReedMullerCode(GF(2), 2, 4)\n sage: E = C.encoder("EvaluationVector")\n sage: E\n Evaluation vector-style encoder for\n Binary Reed-Muller Code of order 2 and number of variables 4\n ' def __init__(self, code): '\n TESTS:\n\n If ``code`` is not a Reed-Muller code, an error is raised::\n\n sage: C = codes.random_linear_code(GF(11), 10, 4)\n sage: codes.encoders.ReedMullerVectorEncoder(C)\n Traceback (most recent call last):\n ...\n ValueError: the code has to be a Reed-Muller code\n ' if (not (isinstance(code, QAryReedMullerCode) or isinstance(code, BinaryReedMullerCode))): raise ValueError('the code has to be a Reed-Muller code') super().__init__(code) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: C = codes.ReedMullerCode(F, 2, 4)\n sage: E=codes.encoders.ReedMullerVectorEncoder(C)\n sage: E\n Evaluation vector-style encoder for Reed-Muller Code of order 2 and 4 variables over Finite Field of size 11\n ' return ('Evaluation vector-style encoder for %s' % self.code()) def _latex_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: C = codes.ReedMullerCode(F, 2, 4)\n sage: E=codes.encoders.ReedMullerVectorEncoder(C)\n sage: latex(E)\n \\textnormal{Evaluation vector-style encoder for }\\textnormal{Reed-Muller Code of order} 2 \\textnormal{and }4 \\textnormal{variables over} \\Bold{F}_{11}\n ' return ('\\textnormal{Evaluation vector-style encoder for }%s' % self.code()._latex_()) def __eq__(self, other): '\n Tests equality between ReedMullerVectorEncoder objects.\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: C = codes.ReedMullerCode(F, 2, 4)\n sage: D1 = codes.encoders.ReedMullerVectorEncoder(C)\n sage: D2 = codes.encoders.ReedMullerVectorEncoder(C)\n sage: D1.__eq__(D2)\n True\n sage: D1 is D2\n False\n ' return (isinstance(other, ReedMullerVectorEncoder) and (self.code() == other.code())) @cached_method def generator_matrix(self): '\n Return a generator matrix of ``self``\n\n EXAMPLES::\n\n sage: F = GF(3)\n sage: C = codes.ReedMullerCode(F, 2, 2)\n sage: E = codes.encoders.ReedMullerVectorEncoder(C)\n sage: E.generator_matrix()\n [1 1 1 1 1 1 1 1 1]\n [0 1 2 0 1 2 0 1 2]\n [0 0 0 1 1 1 2 2 2]\n [0 1 1 0 1 1 0 1 1]\n [0 0 0 0 1 2 0 2 1]\n [0 0 0 1 1 1 1 1 1]\n ' C = self.code() base_field = C.base_field() order = C.order() num_of_var = C.number_of_variables() q = base_field.cardinality() points = (base_field ** num_of_var) matrix_list = [] max_individual_degree = min(order, (q - 1)) for degree in range((order + 1)): exponents = Subsets((list(range(num_of_var)) * max_individual_degree), degree, submultiset=True) matrix_list += [[reduce(mul, [x[i] for i in exponent], 1) for x in points] for exponent in exponents] M = matrix(base_field, matrix_list) M.set_immutable() return M def points(self): '\n Return the points of `F^m`, where `F` is the base field and `m` is the\n number of variables, in order of which polynomials are evaluated on.\n\n EXAMPLES::\n\n sage: F = GF(3)\n sage: Fx.<x0,x1> = F[]\n sage: C = codes.ReedMullerCode(F, 2, 2)\n sage: E = C.encoder("EvaluationVector")\n sage: E.points()\n [(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1), (0, 2), (1, 2), (2, 2)]\n ' code = self.code() return (code.base_field() ** code.number_of_variables()).list()
class ReedMullerPolynomialEncoder(Encoder): '\n Encoder for Reed-Muller codes which encodes appropriate multivariate polynomials into codewords.\n\n Consider a Reed-Muller code of order `r`, number of variables `m`, length `n`,\n dimension `k` over some finite field `F`.\n Let those variables be `(x_1, x_2, \\dots, x_m)`.\n We order the monomials by lowest power on lowest index variables. If we have three monomials\n `x_1 x_2`, `x_1 x_2^2` and `x_1^2 x_2`, the ordering is:\n `x_1 x_2 < x_1 x_2^2 < x_1^2 x_2`\n\n Let now `f` be a polynomial of the multivariate polynomial ring `F[x_1, \\dots, x_m]`.\n\n Let `(\\beta_1, \\beta_2, \\ldots, \\beta_q)` be the elements of `F` ordered as they are\n returned by Sage when calling ``F.list()``.\n\n The aforementioned polynomial `f` is encoded as:\n\n `(f(\\alpha_{11},\\alpha_{12},\\ldots,\\alpha_{1m}),f(\\alpha_{21},\\alpha_{22},\\ldots,\n \\alpha_{2m}),\\ldots,f(\\alpha_{q^m1},\\alpha_{q^m2},\\ldots,\\alpha_{q^mm}))`\n\n with `\\alpha_{ij}=\\beta_{i \\bmod{q^j}}` for all `i`, `j`.\n\n INPUT:\n\n - ``code`` -- The associated code of this encoder.\n\n - ``polynomial_ring`` -- (default:``None``) The polynomial ring from which\n the message is chosen. If this is set to ``None``, a polynomial ring in\n `x` will be built from the code parameters.\n\n EXAMPLES::\n\n sage: C1 = codes.ReedMullerCode(GF(2), 2, 4)\n sage: E1 = codes.encoders.ReedMullerPolynomialEncoder(C1)\n sage: E1\n Evaluation polynomial-style encoder for\n Binary Reed-Muller Code of order 2 and number of variables 4\n sage: C2 = codes.ReedMullerCode(GF(3), 2, 2)\n sage: E2 = codes.encoders.ReedMullerPolynomialEncoder(C2)\n sage: E2\n Evaluation polynomial-style encoder for\n Reed-Muller Code of order 2 and 2 variables over Finite Field of size 3\n\n We can also pass a predefined polynomial ring::\n\n sage: R = PolynomialRing(GF(3), 2, \'y\')\n sage: C = codes.ReedMullerCode(GF(3), 2, 2)\n sage: E = codes.encoders.ReedMullerPolynomialEncoder(C, R)\n sage: E\n Evaluation polynomial-style encoder for\n Reed-Muller Code of order 2 and 2 variables over Finite Field of size 3\n\n Actually, we can construct the encoder from ``C`` directly::\n\n sage: E = C1.encoder("EvaluationPolynomial")\n sage: E\n Evaluation polynomial-style encoder for\n Binary Reed-Muller Code of order 2 and number of variables 4\n ' def __init__(self, code, polynomial_ring=None): '\n TESTS:\n\n If ``code`` is not a Reed-Muller code, an error is raised::\n\n sage: C = codes.random_linear_code(GF(11), 10, 4)\n sage: codes.encoders.ReedMullerPolynomialEncoder(C)\n Traceback (most recent call last):\n ...\n ValueError: the code has to be a Reed-Muller code\n\n If the polynomial ring passed is not according to the requirement (over a different field or different number of variables) then an error is raised::\n\n sage: F=GF(59)\n sage: R.<x,y,z,w>=F[]\n sage: C=codes.ReedMullerCode(F, 2, 3)\n sage: E=codes.encoders.ReedMullerPolynomialEncoder(C, R)\n Traceback (most recent call last):\n ...\n ValueError: The Polynomial ring should be on Finite Field of size 59 and should have 3 variables\n ' if (not (isinstance(code, QAryReedMullerCode) or isinstance(code, BinaryReedMullerCode))): raise ValueError('the code has to be a Reed-Muller code') super().__init__(code) if (polynomial_ring is None): self._polynomial_ring = PolynomialRing(code.base_field(), code.number_of_variables(), 'x') elif ((polynomial_ring.base_ring() == code.base_field()) and (len(polynomial_ring.variable_names()) == code.number_of_variables())): self._polynomial_ring = polynomial_ring else: raise ValueError(('The Polynomial ring should be on %s and should have %s variables' % (code.base_field(), code.number_of_variables()))) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: C = codes.ReedMullerCode(F, 2, 4)\n sage: E=codes.encoders.ReedMullerPolynomialEncoder(C)\n sage: E\n Evaluation polynomial-style encoder for Reed-Muller Code of order 2 and 4 variables over Finite Field of size 59\n ' return ('Evaluation polynomial-style encoder for %s' % self.code()) def _latex_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F = GF(59)\n sage: C = codes.ReedMullerCode(F, 2, 4)\n sage: E=codes.encoders.ReedMullerPolynomialEncoder(C)\n sage: latex(E)\n \\textnormal{Evaluation polynomial-style encoder for }\\textnormal{Reed-Muller Code of order} 2 \\textnormal{and }4 \\textnormal{variables over} \\Bold{F}_{59}\n ' return ('\\textnormal{Evaluation polynomial-style encoder for }%s' % self.code()._latex_()) def __eq__(self, other): '\n Tests equality between ReedMullerVectorEncoder objects.\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: C = codes.ReedMullerCode(F, 2, 4)\n sage: D1 = codes.encoders.ReedMullerPolynomialEncoder(C)\n sage: D2 = codes.encoders.ReedMullerPolynomialEncoder(C)\n sage: D1.__eq__(D2)\n True\n sage: D1 is D2\n False\n ' return (isinstance(other, ReedMullerPolynomialEncoder) and (self.code() == other.code())) def encode(self, p): '\n Transforms the polynomial ``p`` into a codeword of :meth:`code`.\n\n INPUT:\n\n - ``p`` -- A polynomial from the message space of ``self`` of degree\n less than ``self.code().order()``.\n\n OUTPUT:\n\n - A codeword in associated code of ``self``\n\n EXAMPLES::\n\n sage: F = GF(3)\n sage: Fx.<x0,x1> = F[]\n sage: C = codes.ReedMullerCode(F, 2, 2)\n sage: E = C.encoder("EvaluationPolynomial")\n sage: p = x0*x1 + x1^2 + x0 + x1 + 1\n sage: c = E.encode(p); c\n (1, 2, 0, 0, 2, 1, 1, 1, 1)\n sage: c in C\n True\n\n If a polynomial with good monomial degree but wrong monomial\n degree is given, an error is raised::\n\n sage: p = x0^2*x1\n sage: E.encode(p)\n Traceback (most recent call last):\n ...\n ValueError: The polynomial to encode must have degree at most 2\n\n If ``p`` is not an element of the proper polynomial ring, an error is raised::\n\n sage: Qy.<y1,y2> = QQ[]\n sage: p = y1^2 + 1\n sage: E.encode(p)\n Traceback (most recent call last):\n ...\n ValueError: The value to encode must be in\n Multivariate Polynomial Ring in x0, x1 over Finite Field of size 3\n ' M = self.message_space() if (p not in M): raise ValueError(('The value to encode must be in %s' % M)) C = self.code() if (p.degree() > C.order()): raise ValueError(('The polynomial to encode must have degree at most %s' % C.order())) base_fieldTuple = Tuples(C.base_field().list(), C.number_of_variables()) return vector(C.base_ring(), [p(x) for x in base_fieldTuple]) def unencode_nocheck(self, c): '\n Return the message corresponding to the codeword ``c``.\n\n Use this method with caution: it does not check if ``c``\n belongs to the code, and if this is not the case, the output is\n unspecified. Instead, use :meth:`unencode`.\n\n INPUT:\n\n - ``c`` -- A codeword of :meth:`code`.\n\n OUTPUT:\n\n - A polynomial of degree less than ``self.code().order()``.\n\n EXAMPLES::\n\n sage: F = GF(3)\n sage: C = codes.ReedMullerCode(F, 2, 2)\n sage: E = C.encoder("EvaluationPolynomial")\n sage: c = vector(F, (1, 2, 0, 0, 2, 1, 1, 1, 1))\n sage: c in C\n True\n sage: p = E.unencode_nocheck(c); p\n x0*x1 + x1^2 + x0 + x1 + 1\n sage: E.encode(p) == c\n True\n\n Note that no error is thrown if ``c`` is not a codeword, and that the\n result is undefined::\n\n sage: c = vector(F, (1, 2, 0, 0, 2, 1, 0, 1, 1))\n sage: c in C\n False\n sage: p = E.unencode_nocheck(c); p\n -x0*x1 - x1^2 + x0 + 1\n sage: E.encode(p) == c\n False\n\n ' return _multivariate_polynomial_interpolation(c, self.code().order(), self.polynomial_ring()) def message_space(self): '\n Return the message space of ``self``\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: C = codes.ReedMullerCode(F, 2, 4)\n sage: E = C.encoder("EvaluationPolynomial")\n sage: E.message_space()\n Multivariate Polynomial Ring in x0, x1, x2, x3 over Finite Field of size 11\n ' return self._polynomial_ring def polynomial_ring(self): '\n Return the polynomial ring associated with ``self``\n\n EXAMPLES::\n\n sage: F = GF(11)\n sage: C = codes.ReedMullerCode(F, 2, 4)\n sage: E = C.encoder("EvaluationPolynomial")\n sage: E.polynomial_ring()\n Multivariate Polynomial Ring in x0, x1, x2, x3 over Finite Field of size 11\n ' return self._polynomial_ring def points(self): '\n Return the evaluation points in the appropriate order as used by ``self`` when\n encoding a message.\n\n EXAMPLES::\n\n sage: F = GF(3)\n sage: Fx.<x0,x1> = F[]\n sage: C = codes.ReedMullerCode(F, 2, 2)\n sage: E = C.encoder("EvaluationPolynomial")\n sage: E.points()\n [(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1), (0, 2), (1, 2), (2, 2)]\n ' code = self.code() return (code.base_field() ** code.number_of_variables()).list()
def _MS(n): '\n For internal use; returns the floor(n/2) x n matrix space over GF(2).\n\n EXAMPLES::\n\n sage: import sage.coding.self_dual_codes as self_dual_codes\n sage: self_dual_codes._MS(2)\n Full MatrixSpace of 1 by 2 dense matrices over Finite Field of size 2\n sage: self_dual_codes._MS(3)\n Full MatrixSpace of 1 by 3 dense matrices over Finite Field of size 2\n sage: self_dual_codes._MS(8)\n Full MatrixSpace of 4 by 8 dense matrices over Finite Field of size 2\n ' n2 = (ZZ(n) / 2) return MatrixSpace(_F, n2, n)
def _matA(n): '\n For internal use; returns a list of square matrices over GF(2) `(a_{ij})`\n of sizes 0 x 0, 1 x 1, ..., n x n which are of the form\n `(a_{ij} = 1) + (a_{ij} = \\delta_{ij})`.\n\n EXAMPLES::\n\n sage: import sage.coding.self_dual_codes as self_dual_codes\n sage: self_dual_codes._matA(4)\n [\n [0 1 1]\n [0 1] [1 0 1]\n [], [0], [1 0], [1 1 0]\n ]\n ' A = [] n2 = n.quo_rem(2)[0] for j in range((n2 + 2)): MS0 = MatrixSpace(_F, j, j) I = MS0.identity_matrix() O = MS0(((j * j) * [1])) A.append((I + O)) return A
def _matId(n): '\n For internal use; returns a list of identity matrices over GF(2)\n of sizes (floor(n/2)-j) x (floor(n/2)-j) for j = 0 ... (floor(n/2)-1).\n\n EXAMPLES::\n\n sage: import sage.coding.self_dual_codes as self_dual_codes\n sage: self_dual_codes._matId(6)\n [\n [1 0 0]\n [0 1 0] [1 0]\n [0 0 1], [0 1], [1]\n ]\n ' Id = [] n2 = n.quo_rem(2)[0] for j in range(n2): MSn = MatrixSpace(_F, (n2 - j), (n2 - j)) Id.append(MSn.identity_matrix()) return Id
def _MS2(n): '\n For internal use; returns the floor(n/2) x floor(n/2) matrix space over GF(2).\n\n EXAMPLES::\n\n sage: import sage.coding.self_dual_codes as self_dual_codes\n sage: self_dual_codes._MS2(8)\n Full MatrixSpace of 4 by 4 dense matrices over Finite Field of size 2\n ' n2 = n.quo_rem(2)[0] return MatrixSpace(_F, n2, n2)
def _I2(n): '\n Internal function\n\n EXAMPLES::\n\n sage: from sage.coding.self_dual_codes import _I2\n sage: _I2(3)\n [1]\n sage: _I2(5)\n [1 0]\n [0 1]\n sage: _I2(7)\n [1 0 0]\n [0 1 0]\n [0 0 1]\n ' return _MS2(n).identity_matrix()
@cached_function def _And7(): '\n Auxiliary matrix And7.\n\n EXAMPLES::\n\n sage: from sage.coding.self_dual_codes import _And7\n sage: _And7()\n [1 1 1 0 0 1 1]\n [1 1 1 0 1 0 1]\n [1 1 1 0 1 1 0]\n [0 0 0 0 1 1 1]\n [0 1 1 1 0 0 0]\n [1 0 1 1 0 0 0]\n [1 1 0 1 0 0 0]\n ' return matrix(_F, [[1, 1, 1, 0, 0, 1, 1], [1, 1, 1, 0, 1, 0, 1], [1, 1, 1, 0, 1, 1, 0], [0, 0, 0, 0, 1, 1, 1], [0, 1, 1, 1, 0, 0, 0], [1, 0, 1, 1, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0]])
@cached_function def _H8(): '\n Auxiliary matrix H8.\n\n EXAMPLES::\n\n sage: from sage.coding.self_dual_codes import _H8\n sage: _H8()\n [ 1 1 1 1 1 1 1 1]\n [ 1 -1 1 -1 1 -1 1 -1]\n [ 1 1 -1 -1 1 1 -1 -1]\n [ 1 -1 -1 1 1 -1 -1 1]\n [ 1 1 1 1 -1 -1 -1 -1]\n [ 1 -1 1 -1 -1 1 -1 1]\n [ 1 1 -1 -1 -1 -1 1 1]\n [ 1 -1 -1 1 -1 1 1 -1]\n ' return matrix(ZZ, [[1, 1, 1, 1, 1, 1, 1, 1], [1, (- 1), 1, (- 1), 1, (- 1), 1, (- 1)], [1, 1, (- 1), (- 1), 1, 1, (- 1), (- 1)], [1, (- 1), (- 1), 1, 1, (- 1), (- 1), 1], [1, 1, 1, 1, (- 1), (- 1), (- 1), (- 1)], [1, (- 1), 1, (- 1), (- 1), 1, (- 1), 1], [1, 1, (- 1), (- 1), (- 1), (- 1), 1, 1], [1, (- 1), (- 1), 1, (- 1), 1, 1, (- 1)]])
def self_dual_binary_codes(n): '\n Return the dictionary of inequivalent binary self dual codes of length `n`.\n\n For `n=4` even, returns the sd codes of a given length, up to (perm)\n equivalence, the (perm) aut gp, and the type.\n\n The number of inequivalent "diagonal" sd binary codes in the database of\n length n is ("diagonal" is defined by the conjecture above) is the\n same as the restricted partition number of `n`, where only integers\n from the set 1, 4, 6, 8, ... are allowed. This is the coefficient of\n `x^n` in the series expansion\n `(1-x)^{-1}\\prod_{2^\\infty (1-x^{2j})^{-1}}`. Typing the\n command ``f = (1-x)(-1)\\*prod([(1-x(2\\*j))(-1) for j in range(2,18)])``\n into Sage, we obtain for the coeffs of `x^4`,\n `x^6`, ... [1, 1, 2, 2, 3, 3, 5, 5, 7, 7, 11, 11, 15, 15,\n 22, 22, 30, 30, 42, 42, 56, 56, 77, 77, 101, 101, 135, 135, 176,\n 176, 231] These numbers grow too slowly to account for all the sd\n codes (see Huffman+Pless\' Table 9.1, referenced above). In fact, in\n Table 9.10 of [HP2003]_, the number `B_n` of inequivalent sd binary codes\n of length `n` is given::\n\n n 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30\n B_n 1 1 1 2 2 3 4 7 9 16 25 55 103 261 731\n\n According to http://oeis.org/classic/A003179,\n the next 2 entries are: 3295, 24147.\n\n EXAMPLES::\n\n sage: C = codes.databases.self_dual_binary_codes(10)\n sage: C["10"]["0"]["code"] == C["10"]["0"]["code"].dual_code()\n True\n sage: C["10"]["1"]["code"] == C["10"]["1"]["code"].dual_code()\n True\n sage: len(C["10"].keys()) # number of inequiv sd codes of length 10\n 2\n sage: C = codes.databases.self_dual_binary_codes(12)\n sage: C["12"]["0"]["code"] == C["12"]["0"]["code"].dual_code()\n True\n sage: C["12"]["1"]["code"] == C["12"]["1"]["code"].dual_code()\n True\n sage: C["12"]["2"]["code"] == C["12"]["2"]["code"].dual_code()\n True\n ' self_dual_codes = {} if (n == 4): genmat = _I2(n).augment(_I2(n)) spectrum = [1, 0, 2, 0, 1] self_dual_codes_4_0 = {'order autgp': 8, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Unique.'} self_dual_codes['4'] = {'0': self_dual_codes_4_0} return self_dual_codes if (n == 6): genmat = _I2(n).augment(_I2(n)) spectrum = [1, 0, 3, 0, 3, 0, 1] self_dual_codes_6_0 = {'order autgp': 48, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Unique'} self_dual_codes['6'] = {'0': self_dual_codes_6_0} return self_dual_codes if (n == 8): genmat = _I2(n).augment(_I2(n)) spectrum = [1, 0, 4, 0, 6, 0, 4, 0, 1] self_dual_codes_8_0 = {'order autgp': 384, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Unique Type I of this length.'} genmat = _I2(n).augment(_matA(n)[4]) spectrum = [1, 0, 0, 0, 14, 0, 0, 0, 1] self_dual_codes_8_1 = {'order autgp': 1344, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'II', 'Comment': 'Unique Type II of this length.'} self_dual_codes['8'] = {'0': self_dual_codes_8_0, '1': self_dual_codes_8_1} return self_dual_codes if (n == 10): genmat = _I2(n).augment(_I2(n)) spectrum = [1, 0, 5, 0, 10, 0, 10, 0, 5, 0, 1] self_dual_codes_10_0 = {'order autgp': 3840, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'No Type II of this length.'} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[4], _matId(n)[4]])) spectrum = [1, 0, 1, 0, 14, 0, 14, 0, 1, 0, 1] self_dual_codes_10_1 = {'order autgp': 2688, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Unique lowest weight nonzero codeword.'} self_dual_codes['10'] = {'0': self_dual_codes_10_0, '1': self_dual_codes_10_1} return self_dual_codes if (n == 12): genmat = _I2(n).augment(_I2(n)) spectrum = [1, 0, 6, 0, 15, 0, 20, 0, 15, 0, 6, 0, 1] self_dual_codes_12_0 = {'order autgp': 48080, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'No Type II of this length.'} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[4], _matId(n)[4]])) spectrum = [1, 0, 2, 0, 15, 0, 28, 0, 15, 0, 2, 0, 1] self_dual_codes_12_1 = {'order autgp': 10752, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Smallest automorphism group of these.'} genmat = _I2(n).augment(_matA(n)[6]) spectrum = [1, 0, 0, 0, 15, 0, 32, 0, 15, 0, 0, 0, 1] self_dual_codes_12_2 = {'order autgp': 23040, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Largest minimum distance of these.'} self_dual_codes['12'] = {'0': self_dual_codes_12_0, '1': self_dual_codes_12_1, '2': self_dual_codes_12_2} return self_dual_codes if (n == 14): genmat = _I2(n).augment(_I2(n)) spectrum = [1, 0, 7, 0, 21, 0, 35, 0, 35, 0, 21, 0, 7, 0, 1] self_dual_codes_14_0 = {'order autgp': 645120, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'No Type II of this length. Huge aut gp.'} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[4], _matId(n)[4]])) spectrum = [1, 0, 3, 0, 17, 0, 43, 0, 43, 0, 17, 0, 3, 0, 1] self_dual_codes_14_1 = {'order autgp': 64512, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Automorphism group has order 64512.'} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[6], _matId(n)[6]])) spectrum = [1, 0, 1, 0, 15, 0, 47, 0, 47, 0, 15, 0, 1, 0, 1] self_dual_codes_14_2 = {'order autgp': 46080, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Unique codeword of weight 2.'} genmat = _I2(n).augment(_And7()) spectrum = [1, 0, 0, 0, 14, 0, 49, 0, 49, 0, 14, 0, 0, 0, 1] self_dual_codes_14_3 = {'order autgp': 56448, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Largest minimum distance of these.'} self_dual_codes['14'] = {'0': self_dual_codes_14_0, '1': self_dual_codes_14_1, '2': self_dual_codes_14_2, '3': self_dual_codes_14_3} return self_dual_codes if (n == 16): genmat = _I2(n).augment(_I2(n)) spectrum = [1, 0, 8, 0, 28, 0, 56, 0, 70, 0, 56, 0, 28, 0, 8, 0, 1] self_dual_codes_16_0 = {'order autgp': 10321920, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Huge aut gp.'} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[4], _matId(n)[4]])) spectrum = [1, 0, 4, 0, 20, 0, 60, 0, 86, 0, 60, 0, 20, 0, 4, 0, 1] self_dual_codes_16_1 = {'order autgp': 516096, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': ''} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[4], _matA(n)[4]])) spectrum = [1, 0, 0, 0, 28, 0, 0, 0, 198, 0, 0, 0, 28, 0, 0, 0, 1] self_dual_codes_16_2 = {'order autgp': 3612672, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'II', 'Comment': 'Same spectrum as the other Type II code.'} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[6], _matId(n)[6]])) spectrum = [1, 0, 2, 0, 16, 0, 62, 0, 94, 0, 62, 0, 16, 0, 2, 0, 1] self_dual_codes_16_3 = {'order autgp': 184320, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': ''} genmat = _I2(n).augment(_matA(n)[8]) spectrum = [1, 0, 0, 0, 28, 0, 0, 0, 198, 0, 0, 0, 28, 0, 0, 0, 1] self_dual_codes_16_4 = {'order autgp': 5160960, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'II', 'Comment': 'Same spectrum as the other Type II code. Large aut gp.'} genmat = _I2(n).augment(block_diagonal_matrix([_And7(), _matId(n)[7]])) spectrum = [1, 0, 1, 0, 14, 0, 63, 0, 98, 0, 63, 0, 14, 0, 1, 0, 1] self_dual_codes_16_5 = {'order autgp': 112896, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "'Exceptional' construction."} J8 = MatrixSpace(ZZ, 8, 8)((64 * [1])) genmat = _I2(n).augment((_I2(n) + _MS2(n)(((_H8() + J8) / 2)))) spectrum = [1, 0, 0, 0, 12, 0, 64, 0, 102, 0, 64, 0, 12, 0, 0, 0, 1] self_dual_codes_16_6 = {'order autgp': 73728, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "'Exceptional' construction. Min dist 4."} self_dual_codes['16'] = {'0': self_dual_codes_16_0, '1': self_dual_codes_16_1, '2': self_dual_codes_16_2, '3': self_dual_codes_16_3, '4': self_dual_codes_16_4, '5': self_dual_codes_16_5, '6': self_dual_codes_16_6} return self_dual_codes if (n == 18): genmat = _I2(n).augment(_I2(n)) spectrum = [1, 0, 9, 0, 36, 0, 84, 0, 126, 0, 126, 0, 84, 0, 36, 0, 9, 0, 1] self_dual_codes_18_0 = {'order autgp': 185794560, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Huge aut gp. S_9x(ZZ/2ZZ)^9?'} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[4], _matId(n)[4]])) spectrum = [1, 0, 5, 0, 24, 0, 80, 0, 146, 0, 146, 0, 80, 0, 24, 0, 5, 0, 1] self_dual_codes_18_1 = {'order autgp': 5160960, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Large aut gp.'} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[6], _matId(n)[6]])) spectrum = [1, 0, 3, 0, 18, 0, 78, 0, 156, 0, 156, 0, 78, 0, 18, 0, 3, 0, 1] self_dual_codes_18_2 = {'order autgp': 1105920, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': ''} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[4], _matA(n)[4], _matId(n)[8]])) spectrum = [1, 0, 1, 0, 28, 0, 28, 0, 198, 0, 198, 0, 28, 0, 28, 0, 1, 0, 1] self_dual_codes_18_3 = {'order autgp': 7225344, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "Large aut gp. Unique codeword of smallest non-zero wt. Same spectrum as '[18,4]' sd code."} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[8], _matId(n)[8]])) spectrum = [1, 0, 1, 0, 28, 0, 28, 0, 198, 0, 198, 0, 28, 0, 28, 0, 1, 0, 1] self_dual_codes_18_4 = {'order autgp': 10321920, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "Huge aut gp. Unique codeword of smallest non-zero wt. Same spectrum as '[18,3]' sd code."} C = self_dual_binary_codes((n - 2))[('%s' % (n - 2))]['5']['code'] A0 = C.redundancy_matrix() genmat = _I2(n).augment(block_diagonal_matrix([A0, _matId(n)[8]])) spectrum = [1, 0, 2, 0, 15, 0, 77, 0, 161, 0, 161, 0, 77, 0, 15, 0, 2, 0, 1] self_dual_codes_18_5 = {'order autgp': 451584, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "'Exceptional' construction."} C = self_dual_binary_codes((n - 2))[('%s' % (n - 2))]['6']['code'] A0 = C.redundancy_matrix() genmat = _I2(n).augment(block_diagonal_matrix([A0, _matId(n)[8]])) G = PermutationGroup(['(9,18)', '(7,10)(11,17)', '(7,11)(10,17)', '(6,7)(11,12)', '(4,6)(12,14)', '(3,5)(13,15)', '(3,13)(5,15)', '(2,3)(15,16)', '(1,2)(8,16)', '(1,4)(2,6)(3,7)(5,17)(8,14)(10,13)(11,15)(12,16)']) spectrum = [1, 0, 1, 0, 12, 0, 76, 0, 166, 0, 166, 0, 76, 0, 12, 0, 1, 0, 1] self_dual_codes_18_6 = {'order autgp': 147456, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "'Exceptional'. Unique codeword of smallest non-zero wt."} genmat = _MS(n)([[1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1], [0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1]]) spectrum = [1, 0, 0, 0, 9, 0, 75, 0, 171, 0, 171, 0, 75, 0, 9, 0, 0, 0, 1] self_dual_codes_18_7 = {'order autgp': 82944, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "'Exceptional' construction. Min dist 4."} I18 = _MS(n)([[1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) genmat = _MS(n)([[1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0]]) G = PermutationGroup(['(9,15)(16,17)', '(9,16)(15,17)', '(8,9)(17,18)', '(7,8)(16,17)', '(5,6)(10,13)', '(5,10)(6,13)', '(4,5)(13,14)', '(3,4)(12,14)', '(1,2)(6,10)', '(1,3)(2,12)']) spectrum = [1, 0, 0, 0, 17, 0, 51, 0, 187, 0, 187, 0, 51, 0, 17, 0, 0, 0, 1] self_dual_codes_18_8 = {'order autgp': 322560, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "'Exceptional' construction. Min dist 4."} self_dual_codes['18'] = {'0': self_dual_codes_18_0, '1': self_dual_codes_18_1, '2': self_dual_codes_18_2, '3': self_dual_codes_18_3, '4': self_dual_codes_18_4, '5': self_dual_codes_18_5, '6': self_dual_codes_18_6, '7': self_dual_codes_18_7, '8': self_dual_codes_18_8} return self_dual_codes if (n == 20): A10 = MatrixSpace(_F, 10, 10)([[1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 0, 1, 0, 1, 0, 1, 1], [1, 0, 0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 0, 1, 1, 1, 0, 1, 0, 1], [0, 0, 1, 1, 0, 1, 0, 1, 0, 1], [0, 0, 0, 1, 0, 1, 1, 1, 0, 1], [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1]]) genmat = _I2(n).augment(_I2(n)) spectrum = [1, 0, 10, 0, 45, 0, 120, 0, 210, 0, 252, 0, 210, 0, 120, 0, 45, 0, 10, 0, 1] self_dual_codes_20_0 = {'order autgp': 3715891200, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Huge aut gp'} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[4], _matId(n)[4]])) spectrum = [1, 0, 6, 0, 29, 0, 104, 0, 226, 0, 292, 0, 226, 0, 104, 0, 29, 0, 6, 0, 1] self_dual_codes_20_1 = {'order autgp': 61931520, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': ''} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[6], _matId(n)[6]])) spectrum = [1, 0, 4, 0, 21, 0, 96, 0, 234, 0, 312, 0, 234, 0, 96, 0, 21, 0, 4, 0, 1] self_dual_codes_20_2 = {'order autgp': 8847360, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': ''} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[6], _matA(n)[4]])) spectrum = [1, 0, 0, 0, 29, 0, 32, 0, 226, 0, 448, 0, 226, 0, 32, 0, 29, 0, 0, 0, 1] self_dual_codes_20_3 = {'order autgp': 30965760, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Min dist 4.'} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[4], _matA(n)[4], _matId(n)[8]])) spectrum = [1, 0, 2, 0, 29, 0, 56, 0, 226, 0, 396, 0, 226, 0, 56, 0, 29, 0, 2, 0, 1] self_dual_codes_20_4 = {'order autgp': 28901376, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': ''} genmat = _I2(n).augment(block_diagonal_matrix([_And7(), _matId(n)[7]])) spectrum = [1, 0, 3, 0, 17, 0, 92, 0, 238, 0, 322, 0, 238, 0, 92, 0, 17, 0, 3, 0, 1] self_dual_codes_20_5 = {'order autgp': 2709504, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "'Exceptional' construction."} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[8], _matId(n)[8]])) spectrum = [1, 0, 2, 0, 29, 0, 56, 0, 226, 0, 396, 0, 226, 0, 56, 0, 29, 0, 2, 0, 1] self_dual_codes_20_6 = {'order autgp': 41287680, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': ''} A0 = self_dual_binary_codes((n - 4))['16']['6']['code'].redundancy_matrix() genmat = _I2(n).augment(block_diagonal_matrix([A0, _matId(n)[8]])) spectrum = [1, 0, 2, 0, 13, 0, 88, 0, 242, 0, 332, 0, 242, 0, 88, 0, 13, 0, 2, 0, 1] self_dual_codes_20_7 = {'order autgp': 589824, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "'Exceptional' construction."} genmat = _I2(n).augment(_matA(n)[10]) J20 = _MS(n)([[1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]]) genmat2 = _MS(n)([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1]]) spectrum = [1, 0, 0, 0, 45, 0, 0, 0, 210, 0, 512, 0, 210, 0, 0, 0, 45, 0, 0, 0, 1] self_dual_codes_20_8 = {'order autgp': 1857945600, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Huge aut gp. Min dist 4.'} genmat = _I2(n).augment(A10) K20 = _MS(n)([[1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]]) spectrum = [1, 0, 0, 0, 21, 0, 48, 0, 234, 0, 416, 0, 234, 0, 48, 0, 21, 0, 0, 0, 1] self_dual_codes_20_9 = {'order autgp': 4423680, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Min dist 4.'} L20 = _MS(n)([[1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0], [0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0]]) genmat = L20 spectrum = [1, 0, 0, 0, 17, 0, 56, 0, 238, 0, 400, 0, 238, 0, 56, 0, 17, 0, 0, 0, 1] self_dual_codes_20_10 = {'order autgp': 1354752, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Min dist 4.'} S20 = _MS(n)([[1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0]]) genmat = S20 spectrum = [1, 0, 0, 0, 13, 0, 64, 0, 242, 0, 384, 0, 242, 0, 64, 0, 13, 0, 0, 0, 1] self_dual_codes_20_11 = {'order autgp': 294912, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Min dist 4.'} R20 = _MS(n)([[0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0], [1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1], [1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1]]) genmat = R20 spectrum = [1, 0, 0, 0, 9, 0, 72, 0, 246, 0, 368, 0, 246, 0, 72, 0, 9, 0, 0, 0, 1] self_dual_codes_20_12 = {'order autgp': 82944, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Min dist 4.'} M20 = _MS(n)([[1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]]) genmat = M20 spectrum = [1, 0, 0, 0, 5, 0, 80, 0, 250, 0, 352, 0, 250, 0, 80, 0, 5, 0, 0, 0, 1] self_dual_codes_20_13 = {'order autgp': 122880, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Min dist 4.'} A0 = self_dual_binary_codes((n - 2))['18']['8']['code'].redundancy_matrix() genmat = _I2(n).augment(block_diagonal_matrix([A0, _matId(n)[9]])) spectrum = [1, 0, 1, 0, 17, 0, 68, 0, 238, 0, 374, 0, 238, 0, 68, 0, 17, 0, 1, 0, 1] self_dual_codes_20_14 = {'order autgp': 645120, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "'Exceptional' construction."} A0 = self_dual_binary_codes((n - 2))['18']['7']['code'].redundancy_matrix() genmat = _I2(n).augment(block_diagonal_matrix([A0, _matId(n)[9]])) spectrum = [1, 0, 1, 0, 9, 0, 84, 0, 246, 0, 342, 0, 246, 0, 84, 0, 9, 0, 1, 0, 1] self_dual_codes_20_15 = {'order autgp': 165888, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "'Exceptional' construction. Unique lowest wt codeword."} self_dual_codes['20'] = {'0': self_dual_codes_20_0, '1': self_dual_codes_20_1, '2': self_dual_codes_20_2, '3': self_dual_codes_20_3, '4': self_dual_codes_20_4, '5': self_dual_codes_20_5, '6': self_dual_codes_20_6, '7': self_dual_codes_20_7, '8': self_dual_codes_20_8, '9': self_dual_codes_20_9, '10': self_dual_codes_20_10, '11': self_dual_codes_20_11, '12': self_dual_codes_20_12, '13': self_dual_codes_20_13, '14': self_dual_codes_20_14, '15': self_dual_codes_20_15} return self_dual_codes if (n == 22): genmat = _I2(n).augment(_I2(n)) spectrum = [1, 0, 11, 0, 55, 0, 165, 0, 330, 0, 462, 0, 462, 0, 330, 0, 165, 0, 55, 0, 11, 0, 1] self_dual_codes_22_0 = {'order autgp': 81749606400, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Huge aut gp.'} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[4], _matId(n)[4]])) spectrum = [1, 0, 7, 0, 35, 0, 133, 0, 330, 0, 518, 0, 518, 0, 330, 0, 133, 0, 35, 0, 7, 0, 1] self_dual_codes_22_1 = {'order autgp': 867041280, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': ''} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[6], _matId(n)[6]])) spectrum = [1, 0, 5, 0, 25, 0, 117, 0, 330, 0, 546, 0, 546, 0, 330, 0, 117, 0, 25, 0, 5, 0, 1] self_dual_codes_22_2 = {'order autgp': 88473600, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': ''} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[8], _matId(n)[8]])) spectrum = [1, 0, 3, 0, 31, 0, 85, 0, 282, 0, 622, 0, 622, 0, 282, 0, 85, 0, 31, 0, 3, 0, 1] self_dual_codes_22_3 = {'order autgp': 247726080, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "Same spectrum as the '[20,5]' code."} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[10], _matId(n)[10]])) spectrum = [1, 0, 1, 0, 45, 0, 45, 0, 210, 0, 722, 0, 722, 0, 210, 0, 45, 0, 45, 0, 1, 0, 1] self_dual_codes_22_4 = {'order autgp': 3715891200, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Unique lowest weight codeword.'} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[4], _matA(n)[4], _matId(n)[8]])) spectrum = [1, 0, 3, 0, 31, 0, 85, 0, 282, 0, 622, 0, 622, 0, 282, 0, 85, 0, 31, 0, 3, 0, 1] self_dual_codes_22_5 = {'order autgp': 173408256, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': "Same spectrum as the '[20,3]' code."} genmat = _I2(n).augment(block_diagonal_matrix([_matA(n)[6], _matA(n)[4], _matId(n)[10]])) spectrum = [1, 0, 1, 0, 29, 0, 61, 0, 258, 0, 674, 0, 674, 0, 258, 0, 61, 0, 29, 0, 1, 0, 1] self_dual_codes_22_6 = {'order autgp': 61931520, 'code': LinearCode(genmat), 'spectrum': spectrum, 'Type': 'I', 'Comment': 'Unique lowest weight codeword.'} self_dual_codes['22'] = {'0': self_dual_codes_22_0, '1': self_dual_codes_22_1, '2': self_dual_codes_22_2, '3': self_dual_codes_22_3, '4': self_dual_codes_22_4, '5': self_dual_codes_22_5, '6': self_dual_codes_22_6} return self_dual_codes
def frequency_table(string): '\n Return the frequency table corresponding to the given string.\n\n INPUT:\n\n - ``string`` -- a string of symbols over some alphabet.\n\n OUTPUT:\n\n - A table of frequency of each unique symbol in ``string``. If ``string``\n is an empty string, return an empty table.\n\n EXAMPLES:\n\n The frequency table of a non-empty string::\n\n sage: from sage.coding.source_coding.huffman import frequency_table\n sage: str = "Stop counting my characters!"\n sage: T = sorted(frequency_table(str).items())\n sage: for symbol, code in T:\n ....: print("{} {}".format(symbol, code))\n 3\n ! 1\n S 1\n a 2\n c 3\n e 1\n g 1\n h 1\n i 1\n m 1\n n 2\n o 2\n p 1\n r 2\n s 1\n t 3\n u 1\n y 1\n\n The frequency of an empty string::\n\n sage: frequency_table("")\n defaultdict(<... \'int\'>, {})\n ' d = defaultdict(int) for s in string: d[s] += 1 return d
class Huffman(SageObject): '\n This class implements the basic functionalities of Huffman codes.\n\n It can build a Huffman code from a given string, or from the information\n of a dictionary associating to each key (the elements of the alphabet) a\n weight (most of the time, a probability value or a number of occurrences).\n\n INPUT:\n\n - ``source`` -- can be either\n\n - A string from which the Huffman encoding should be created.\n\n - A dictionary that associates to each symbol of an alphabet a numeric\n value. If we consider the frequency of each alphabetic symbol, then\n ``source`` is considered as the frequency table of the alphabet with\n each numeric (non-negative integer) value being the number of\n occurrences of a symbol. The numeric values can also represent weights\n of the symbols. In that case, the numeric values are not necessarily\n integers, but can be real numbers.\n\n In order to construct a Huffman code for an alphabet, we use exactly one of\n the following methods:\n\n #. Let ``source`` be a string of symbols over an alphabet and feed\n ``source`` to the constructor of this class. Based on the input string, a\n frequency table is constructed that contains the frequency of each unique\n symbol in ``source``. The alphabet in question is then all the unique\n symbols in ``source``. A significant implication of this is that any\n subsequent string that we want to encode must contain only symbols that\n can be found in ``source``.\n\n #. Let ``source`` be the frequency table of an alphabet. We can feed this\n table to the constructor of this class. The table ``source`` can be a\n table of frequencies or a table of weights.\n\n In either case, the alphabet must consist of at least two symbols.\n\n EXAMPLES::\n\n sage: from sage.coding.source_coding.huffman import Huffman, frequency_table\n sage: h1 = Huffman("There once was a french fry")\n sage: for letter, code in sorted(h1.encoding_table().items()):\n ....: print("\'{}\' : {}".format(letter, code))\n \' \' : 00\n \'T\' : 11100\n \'a\' : 0111\n \'c\' : 1010\n \'e\' : 100\n \'f\' : 1011\n \'h\' : 1100\n \'n\' : 1101\n \'o\' : 11101\n \'r\' : 010\n \'s\' : 11110\n \'w\' : 11111\n \'y\' : 0110\n\n We can obtain the same result by "training" the Huffman code with the\n following table of frequency::\n\n sage: ft = frequency_table("There once was a french fry")\n sage: sorted(ft.items())\n [(\' \', 5),\n (\'T\', 1),\n (\'a\', 2),\n (\'c\', 2),\n (\'e\', 4),\n (\'f\', 2),\n (\'h\', 2),\n (\'n\', 2),\n (\'o\', 1),\n (\'r\', 3),\n (\'s\', 1),\n (\'w\', 1),\n (\'y\', 1)]\n\n sage: h2 = Huffman(ft)\n\n Once ``h1`` has been trained, and hence possesses an encoding table,\n it is possible to obtain the Huffman encoding of any string\n (possibly the same) using this code::\n\n sage: encoded = h1.encode("There once was a french fry"); encoded\n \'11100110010001010000111011101101010000111110111111100001110010110101001101101011000010110100110\'\n\n We can decode the above encoded string in the following way::\n\n sage: h1.decode(encoded)\n \'There once was a french fry\'\n\n Obviously, if we try to decode a string using a Huffman instance which\n has been trained on a different sample (and hence has a different encoding\n table), we are likely to get some random-looking string::\n\n sage: h3 = Huffman("There once were two french fries")\n sage: h3.decode(encoded)\n \' eierhffcoeft TfewrnwrTrsc\'\n\n This does not look like our original string.\n\n Instead of using frequency, we can assign weights to each alphabetic\n symbol::\n\n sage: from sage.coding.source_coding.huffman import Huffman\n sage: T = {"a":45, "b":13, "c":12, "d":16, "e":9, "f":5}\n sage: H = Huffman(T)\n sage: L = ["deaf", "bead", "fab", "bee"]\n sage: E = []\n sage: for e in L:\n ....: E.append(H.encode(e))\n ....: print(E[-1])\n 111110101100\n 10111010111\n 11000101\n 10111011101\n sage: D = []\n sage: for e in E:\n ....: D.append(H.decode(e))\n ....: print(D[-1])\n deaf\n bead\n fab\n bee\n sage: D == L\n True\n ' def __init__(self, source): '\n Constructor for Huffman.\n\n See the docstring of this class for full documentation.\n\n EXAMPLES::\n\n sage: from sage.coding.source_coding.huffman import Huffman\n sage: str = "Sage is my most favorite general purpose computer algebra system"\n sage: h = Huffman(str)\n\n TESTS:\n\n Feeding anything else than a string or a dictionary::\n\n sage: Huffman(Graph()) # optional - sage.graphs\n Traceback (most recent call last):\n ...\n ValueError: Input must be either a string or a dictionary.\n ' self._character_to_code = [] self._tree = None self._index = None if isinstance(source, str): self._build_code(frequency_table(source)) elif isinstance(source, dict): self._build_code(source) else: raise ValueError('Input must be either a string or a dictionary.') def _build_code_from_tree(self, tree, d, prefix): '\n Builds the Huffman code corresponding to a given tree and prefix.\n\n INPUT:\n\n - ``tree`` -- integer, or list of size `2`\n\n - ``d`` -- the dictionary to fill\n\n - ``prefix`` (string) -- binary string which is the prefix\n of any element of the tree\n\n EXAMPLES::\n\n sage: from sage.coding.source_coding.huffman import Huffman\n sage: str = "Sage is my most favorite general purpose computer algebra system"\n sage: h = Huffman(str)\n sage: d = {}\n sage: h._build_code_from_tree(h._tree, d, prefix="")\n ' try: self._build_code_from_tree(tree[0], d, prefix=''.join([prefix, '0'])) self._build_code_from_tree(tree[1], d, prefix=''.join([prefix, '1'])) except TypeError: d[tree] = prefix def _build_code(self, dic): '\n Constructs a Huffman code corresponding to an alphabet with the given\n weight table.\n\n INPUT:\n\n - ``dic`` -- a dictionary that associates to each symbol of an alphabet\n a numeric value. If we consider the frequency of each alphabetic\n symbol, then ``dic`` is considered as the frequency table of the\n alphabet with each numeric (non-negative integer) value being the\n number of occurrences of a symbol. The numeric values can also\n represent weights of the symbols. In that case, the numeric values\n are not necessarily integers, but can be real numbers. In general,\n we refer to ``dic`` as a weight table.\n\n EXAMPLES::\n\n sage: from sage.coding.source_coding.huffman import Huffman, frequency_table\n sage: str = "Sage is my most favorite general purpose computer algebra system"\n sage: h = Huffman(str)\n sage: h._build_code(frequency_table(str))\n\n TESTS:\n\n Trying to build a Huffman code for fewer than two symbols fails. We\n could support these corner cases of course, but instead we just don\'t\n allow it::\n\n sage: Huffman(\'\')\n Traceback (most recent call last):\n ...\n ValueError: The alphabet for Huffman must contain at least two\n symbols.\n sage: Huffman(\' \')\n Traceback (most recent call last):\n ...\n ValueError: The alphabet for Huffman must contain at least two\n symbols.\n ' if (len(dic) < 2): raise ValueError('The alphabet for {} must contain at least two symbols.'.format(self.__class__.__name__)) symbols = sorted(dic.items(), key=(lambda x: (x[1], x[0]))) q0 = [(weight, idx) for (idx, (sym, weight)) in enumerate(symbols)] q1 = [] queues = [q0, q1] tot_weight = sum((s[1] for s in symbols)) def pop(): q = min(queues, key=(lambda q: ((q and q[0][0]) or tot_weight))) return q.pop(0) while ((len(q0) + len(q1)) > 1): (weight_a, node_a) = pop() (weight_b, node_b) = pop() q1.append(((weight_a + weight_b), (node_a, node_b))) d = {} self._tree = q1[0][1] self._build_code_from_tree(self._tree, d, prefix='') self._index = {i: s for (i, (s, w)) in enumerate(symbols)} self._character_to_code = {s: d[i] for (i, (s, w)) in enumerate(symbols)} def encode(self, string): '\n Encode the given string based on the current encoding table.\n\n INPUT:\n\n - ``string`` -- a string of symbols over an alphabet.\n\n OUTPUT:\n\n - A Huffman encoding of ``string``.\n\n EXAMPLES:\n\n This is how a string is encoded and then decoded::\n\n sage: from sage.coding.source_coding.huffman import Huffman\n sage: str = "Sage is my most favorite general purpose computer algebra system"\n sage: h = Huffman(str)\n sage: encoded = h.encode(str); encoded\n \'11000011010001010101100001111101001110011101001101101111011110111001111010000101101110100000111010101000101000000010111011011000110100101001011100010011011110101011100100110001100101001001110101110101110110001000101011000111101101101111110011111101110100011\'\n sage: h.decode(encoded)\n \'Sage is my most favorite general purpose computer algebra system\'\n ' if self._character_to_code: return ''.join((self._character_to_code[x] for x in string)) def decode(self, string): '\n Decode the given string using the current encoding table.\n\n INPUT:\n\n - ``string`` -- a string of Huffman encodings.\n\n OUTPUT:\n\n - The Huffman decoding of ``string``.\n\n EXAMPLES:\n\n This is how a string is encoded and then decoded::\n\n sage: from sage.coding.source_coding.huffman import Huffman\n sage: str = "Sage is my most favorite general purpose computer algebra system"\n sage: h = Huffman(str)\n sage: encoded = h.encode(str); encoded\n \'11000011010001010101100001111101001110011101001101101111011110111001111010000101101110100000111010101000101000000010111011011000110100101001011100010011011110101011100100110001100101001001110101110101110110001000101011000111101101101111110011111101110100011\'\n sage: h.decode(encoded)\n \'Sage is my most favorite general purpose computer algebra system\'\n\n TESTS:\n\n Of course, the string one tries to decode has to be a binary one. If\n not, an exception is raised::\n\n sage: h.decode(\'I clearly am not a binary string\')\n Traceback (most recent call last):\n ...\n ValueError: Input must be a binary string.\n ' chars = [] tree = self._tree index = self._index for i in string: if (i == '0'): tree = tree[0] elif (i == '1'): tree = tree[1] else: raise ValueError('Input must be a binary string.') if (not isinstance(tree, tuple)): chars.append(index[tree]) tree = self._tree return ''.join(chars) def encoding_table(self): '\n Returns the current encoding table.\n\n INPUT:\n\n - None.\n\n OUTPUT:\n\n - A dictionary associating an alphabetic symbol to a Huffman encoding.\n\n EXAMPLES::\n\n sage: from sage.coding.source_coding.huffman import Huffman\n sage: str = "Sage is my most favorite general purpose computer algebra system"\n sage: h = Huffman(str)\n sage: T = sorted(h.encoding_table().items())\n sage: for symbol, code in T:\n ....: print("{} {}".format(symbol, code))\n 101\n S 110000\n a 1101\n b 110001\n c 110010\n e 010\n f 110011\n g 0001\n i 10000\n l 10001\n m 0011\n n 00000\n o 0110\n p 0010\n r 1110\n s 1111\n t 0111\n u 10010\n v 00001\n y 10011\n ' return self._character_to_code.copy() def tree(self): '\n Returns the Huffman tree corresponding to the current encoding.\n\n INPUT:\n\n - None.\n\n OUTPUT:\n\n - The binary tree representing a Huffman code.\n\n EXAMPLES::\n\n sage: from sage.coding.source_coding.huffman import Huffman\n sage: str = "Sage is my most favorite general purpose computer algebra system"\n sage: h = Huffman(str)\n sage: T = h.tree(); T # optional - sage.graphs\n Digraph on 39 vertices\n sage: T.show(figsize=[20,20]) # optional - sage.graphs sage.plot\n <BLANKLINE>\n ' from sage.graphs.digraph import DiGraph g = DiGraph() g.add_edges(self._generate_edges(self._tree)) return g def _generate_edges(self, tree, parent='', bit=''): '\n Generate the edges of the given Huffman tree.\n\n INPUT:\n\n - ``tree`` -- a Huffman binary tree.\n\n - ``parent`` -- (default: empty string) a parent vertex with exactly\n two children.\n\n - ``bit`` -- (default: empty string) the bit signifying either the\n left or right branch. The bit "0" denotes the left branch and "1"\n denotes the right branch.\n\n OUTPUT:\n\n - An edge list of the Huffman binary tree.\n\n EXAMPLES::\n\n sage: from sage.coding.source_coding.huffman import Huffman\n sage: H = Huffman("Sage")\n sage: T = H.tree() # optional - sage.graphs\n sage: T.edges(sort=True, labels=None) # indirect doctest # optional - sage.graphs\n [(\'0\', \'S: 00\'), (\'0\', \'a: 01\'), (\'1\', \'e: 10\'), (\'1\', \'g: 11\'), (\'root\', \'0\'), (\'root\', \'1\')]\n ' if (parent == ''): u = 'root' else: u = parent s = ''.join([parent, bit]) try: left = self._generate_edges(tree[0], parent=s, bit='0') right = self._generate_edges(tree[1], parent=s, bit='1') L = ([(u, s)] if (s != '') else []) return ((left + right) + L) except TypeError: return [(u, ''.join([self.decode(s), ': ', s]))]
class SubfieldSubcode(AbstractLinearCode): "\n Representation of a subfield subcode.\n\n INPUT:\n\n - ``original_code`` -- the code ``self`` comes from.\n\n - ``subfield`` -- the base field of ``self``.\n\n - ``embedding`` -- (default: ``None``) a homomorphism from ``subfield`` to\n ``original_code``'s base field. If ``None`` is provided, it will default\n to the first homomorphism of the list of homomorphisms Sage can build.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(16, 'aa'), 7, 3)\n sage: codes.SubfieldSubcode(C, GF(4, 'a'))\n Subfield subcode of [7, 3] linear code over GF(16) down to GF(4)\n " _registered_encoders = {} _registered_decoders = {} def __init__(self, original_code, subfield, embedding=None): "\n TESTS:\n\n ``subfield`` has to be a finite field, otherwise an error is raised::\n\n sage: C = codes.random_linear_code(GF(16, 'aa'), 7, 3)\n sage: Cs = codes.SubfieldSubcode(C, RR)\n Traceback (most recent call last):\n ...\n ValueError: subfield has to be a finite field\n\n ``subfield`` has to be a subfield of ``original_code``'s base field,\n otherwise an error is raised::\n\n sage: C = codes.random_linear_code(GF(16, 'aa'), 7, 3)\n sage: Cs = codes.SubfieldSubcode(C, GF(8, 'a'))\n Traceback (most recent call last):\n ...\n ValueError: subfield has to be a subfield of the base field of the original code\n\n " if (not isinstance(original_code, AbstractLinearCode)): raise ValueError('original_code must be a linear code') if (not subfield.is_finite()): raise ValueError('subfield has to be a finite field') super().__init__(subfield, original_code.length(), 'Systematic', 'Syndrome') F = original_code.base_field() sm = F.degree() s = subfield.degree() if (not s.divides(sm)): raise ValueError('subfield has to be a subfield of the base field of the original code') H = Hom(subfield, F) if ((embedding is not None) and (embedding not in H)): raise ValueError("embedding has to be an embedding from subfield to original_code's base field") if (embedding is None): embedding = H[0] self._extension_degree = (sm // s) self._embedding = embedding self._original_code = original_code def __eq__(self, other): "\n Tests equality between Subfield Subcode objects.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(16, 'aa'), 7, 3)\n sage: Cs1 = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: Cs2 = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: Cs1 == Cs2\n True\n " return (isinstance(other, SubfieldSubcode) and (self.original_code() == other.original_code()) and (self.embedding() == other.embedding())) def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(16, 'aa'), 7, 3)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: Cs\n Subfield subcode of [7, 3] linear code over GF(16) down to GF(4)\n " return ('Subfield subcode of %s down to GF(%s)' % (self.original_code(), self.base_field().cardinality())) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(16, 'aa'), 7, 3)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: latex(Cs)\n \\textnormal{Subfield subcode of }[7, 3]\\textnormal{ Linear code over }\\Bold{F}_{2^{4}}\\textnormal{ down to }\\Bold{F}_{2^{2}}\n " return ('\\textnormal{Subfield subcode of }%s\\textnormal{ down to }%s' % (self.original_code()._latex_(), self.base_field()._latex_())) def dimension(self): "\n Return the dimension of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'aa').list()[:13], 5)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: Cs.dimension()\n 3\n " return self.generator_matrix().nrows() def dimension_upper_bound(self): "\n Return an upper bound for the dimension of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(16, 'aa'), 7, 3)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: Cs.dimension_upper_bound()\n 3\n " return self.original_code().dimension() def dimension_lower_bound(self): "\n Return a lower bound for the dimension of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(16, 'aa'), 7, 3)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: Cs.dimension_lower_bound()\n -1\n " C = self.original_code() n = C.length() k = C.dimension() m = self._extension_degree return (n - (m * (n - k))) def original_code(self): "\n Return the original code of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(16, 'aa'), 7, 3)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: Cs.original_code()\n [7, 3] linear code over GF(16)\n " return self._original_code def embedding(self): "\n Return the field embedding between the base field of ``self`` and\n the base field of its original code.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(16, 'aa'), 7, 3)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: Cs.embedding()\n Ring morphism:\n From: Finite Field in a of size 2^2\n To: Finite Field in aa of size 2^4\n Defn: a |--> aa^2 + aa\n " return self._embedding @cached_method def parity_check_matrix(self): "\n Return a parity check matrix of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'aa').list()[:13], 5)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: Cs.parity_check_matrix()\n [ 1 0 0 0 0 0 0 0 0 0 1 a + 1 a + 1]\n [ 0 1 0 0 0 0 0 0 0 0 a + 1 0 a]\n [ 0 0 1 0 0 0 0 0 0 0 a + 1 a 0]\n [ 0 0 0 1 0 0 0 0 0 0 0 a + 1 a]\n [ 0 0 0 0 1 0 0 0 0 0 a + 1 1 a + 1]\n [ 0 0 0 0 0 1 0 0 0 0 1 1 1]\n [ 0 0 0 0 0 0 1 0 0 0 a a 1]\n [ 0 0 0 0 0 0 0 1 0 0 a 1 a]\n [ 0 0 0 0 0 0 0 0 1 0 a + 1 a + 1 1]\n [ 0 0 0 0 0 0 0 0 0 1 a 0 a + 1]\n " F = self.base_field() n = self.length() C = self.original_code() H_original = C.parity_check_matrix() codimC = H_original.nrows() phi = self.embedding() E = phi.codomain() (V, from_V, to_V) = E.vector_space(phi, map=True) m = V.dimension() H = matrix(F, (codimC * m), n) for i in range(codimC): for j in range(n): h_vec = to_V(H_original[i][j]) for k in range(m): H[(((i * m) + k), j)] = h_vec[k] H = H.echelon_form() delete = [] for i in range(H.nrows()): if (H.row(i) == 0): delete.append(i) M = H.delete_rows(delete) M.set_immutable() return M
class SubfieldSubcodeOriginalCodeDecoder(Decoder): "\n Decoder decoding through a decoder over the original code of ``code``.\n\n INPUT:\n\n - ``code`` -- The associated code of this decoder\n\n - ``original_decoder`` -- (default: ``None``) The decoder that will be used\n over the original code. It has to be a decoder object over the original\n code. If it is set to ``None``, the default decoder over the original\n code will be used.\n\n - ``**kwargs`` -- All extra arguments are forwarded to original code's decoder\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'aa').list()[:13], 5)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: codes.decoders.SubfieldSubcodeOriginalCodeDecoder(Cs)\n Decoder of Subfield subcode of [13, 5, 9] Reed-Solomon Code over GF(16) down to GF(4)\n through Gao decoder for [13, 5, 9] Reed-Solomon Code over GF(16)\n " def __init__(self, code, original_decoder=None, **kwargs): "\n TESTS:\n\n If the original decoder is not a decoder over ``code``'s original code, an error is\n raised::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'aa').list()[:13], 5)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: Cbis = codes.GeneralizedReedSolomonCode(GF(16, 'aa').list()[:9], 5)\n sage: D = Cbis.decoder()\n sage: codes.decoders.SubfieldSubcodeOriginalCodeDecoder(Cs, original_decoder=D)\n Traceback (most recent call last):\n ...\n ValueError: original_decoder must have the original code as associated code\n " original_code = code.original_code() if ((original_decoder is not None) and (not (original_decoder.code() == code.original_code()))): raise ValueError('original_decoder must have the original code as associated code') elif (original_decoder is not None): self._original_decoder = original_decoder else: self._original_decoder = original_code.decoder(**kwargs) super().__init__(code, code.ambient_space(), self._original_decoder.connected_encoder()) self._decoder_type = copy(self._decoder_type) self._decoder_type.remove('dynamic') self._decoder_type = self._original_decoder.decoder_type() def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'aa').list()[:13], 5)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: D = codes.decoders.SubfieldSubcodeOriginalCodeDecoder(Cs)\n sage: D\n Decoder of Subfield subcode of [13, 5, 9] Reed-Solomon Code over GF(16) down to GF(4) through Gao decoder for [13, 5, 9] Reed-Solomon Code over GF(16)\n " return ('Decoder of %s through %s' % (self.code(), self.original_decoder())) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'aa').list()[:13], 5)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: D = codes.decoders.SubfieldSubcodeOriginalCodeDecoder(Cs)\n sage: latex(D)\n \\textnormal{Decoder of Subfield subcode of [13, 5, 9] Reed-Solomon Code over GF(16) down to GF(4) through } Gao decoder for [13, 5, 9] Reed-Solomon Code over GF(16)\n " return ('\\textnormal{Decoder of %s through } %s' % (self.code(), self.original_decoder())) def original_decoder(self): "\n Return the decoder over the original code that will be used to decode words of\n :meth:`sage.coding.decoder.Decoder.code`.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'aa').list()[:13], 5)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: D = codes.decoders.SubfieldSubcodeOriginalCodeDecoder(Cs)\n sage: D.original_decoder()\n Gao decoder for [13, 5, 9] Reed-Solomon Code over GF(16)\n " return self._original_decoder def decode_to_code(self, y): "\n Return an error-corrected codeword from ``y``.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'aa').list()[:13], 5)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: D = codes.decoders.SubfieldSubcodeOriginalCodeDecoder(Cs)\n sage: Chan = channels.StaticErrorRateChannel(Cs.ambient_space(),\n ....: D.decoding_radius())\n sage: c = Cs.random_element()\n sage: y = Chan(c)\n sage: c == D.decode_to_code(y)\n True\n " C = self.code() D = self.original_decoder() phi = C.embedding() sec = phi.section() result = D.decode_to_code(vector([phi(i) for i in y])) if ('list-decoder' in self.decoder_type()): l = [] for cw in result: try: l.append(vector([sec(c) for c in cw])) except ValueError: pass return l else: try: cw = vector([sec(c) for c in result]) except ValueError: raise DecodingError('Original decoder does not output a subfield codeword. You may have exceeded the decoding radius.') return cw def decoding_radius(self, **kwargs): "\n Return the maximal number of errors ``self`` can decode.\n\n INPUT:\n\n - ``kwargs`` -- Optional arguments are forwarded to original decoder's\n :meth:`sage.coding.decoder.Decoder.decoding_radius` method.\n\n EXAMPLES::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(16, 'aa').list()[:13], 5)\n sage: Cs = codes.SubfieldSubcode(C, GF(4, 'a'))\n sage: D = codes.decoders.SubfieldSubcodeOriginalCodeDecoder(Cs)\n sage: D.decoding_radius()\n 4\n " return self.original_decoder().decoding_radius(**kwargs)
class AbstractTree(): '\n Abstract Tree.\n\n There is no data structure defined here, as this class is meant to be\n extended, not instantiated.\n\n .. rubric:: How should this class be extended?\n\n A class extending :class:`AbstractTree\n <sage.combinat.abstract_tree.AbstractTree>` should respect several\n assumptions:\n\n * For a tree ``T``, the call ``iter(T)`` should return an iterator on the\n children of the root ``T``.\n\n * The :meth:`canonical_labelling\n <AbstractTree.canonical_labelling>` method\n should return the same value for trees that are considered equal (see the\n "canonical labellings" section in the documentation of the\n :class:`AbstractTree <sage.combinat.abstract_tree.AbstractTree>` class).\n\n * For a tree ``T`` the call ``T.parent().labelled_trees()`` should return\n a parent for labelled trees of the same kind: for example,\n\n - if ``T`` is a binary tree, ``T.parent()`` is ``BinaryTrees()`` and\n ``T.parent().labelled_trees()`` is ``LabelledBinaryTrees()``\n\n - if ``T`` is an ordered tree, ``T.parent()`` is ``OrderedTrees()`` and\n ``T.parent().labelled_trees()`` is ``LabelledOrderedTrees()``\n\n TESTS::\n\n sage: TestSuite(OrderedTree()).run()\n sage: TestSuite(BinaryTree()).run()\n ' def pre_order_traversal_iter(self): '\n The depth-first pre-order traversal iterator.\n\n This method iters each node following the depth-first pre-order\n traversal algorithm (recursive implementation). The algorithm\n is::\n\n yield the root (in the case of binary trees, if it is not\n a leaf);\n then explore each subtree (by the algorithm) from the\n leftmost one to the rightmost one.\n\n EXAMPLES:\n\n For example, on the following binary tree `b`::\n\n | ___3____ |\n | / \\ |\n | 1 _7_ |\n | \\ / \\ |\n | 2 5 8 |\n | / \\ |\n | 4 6 |\n\n (only the nodes shown), the depth-first pre-order traversal\n algorithm explores `b` in the following order of nodes:\n `3,1,2,7,5,4,6,8`.\n\n Another example::\n\n | __1____ |\n | / / / |\n | 2 6 8_ |\n | | | / / |\n | 3_ 7 9 10 |\n | / / |\n | 4 5 |\n\n The algorithm explores this labelled tree in the following\n order: `1,2,3,4,5,6,7,8,9,10`.\n\n TESTS::\n\n sage: b = BinaryTree([[None,[]],[[[],[]],[]]]).canonical_labelling()\n sage: ascii_art([b])\n [ ___3____ ]\n [ / \\ ]\n [ 1 _7_ ]\n [ \\ / \\ ]\n [ 2 5 8 ]\n [ / \\ ]\n [ 4 6 ]\n sage: [n.label() for n in b.pre_order_traversal_iter()]\n [3, 1, 2, 7, 5, 4, 6, 8]\n\n sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).canonical_labelling()\n sage: ascii_art([t])\n [ __1____ ]\n [ / / / ]\n [ 2 6 8_ ]\n [ | | / / ]\n [ 3_ 7 9 10 ]\n [ / / ]\n [ 4 5 ]\n sage: [n.label() for n in t.pre_order_traversal_iter()]\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n sage: [n for n in BinaryTree(None).pre_order_traversal_iter()]\n []\n\n The following test checks that things do not go wrong if some among\n the descendants of the tree are equal or even identical::\n\n sage: u = BinaryTree(None)\n sage: v = BinaryTree([u, u])\n sage: w = BinaryTree([v, v])\n sage: t = BinaryTree([w, w])\n sage: t.node_number()\n 7\n sage: l = [1 for i in t.pre_order_traversal_iter()]\n sage: len(l)\n 7\n ' if self.is_empty(): return (yield self) (yield from itertools.chain(*[c.pre_order_traversal_iter() for c in self])) def iterative_pre_order_traversal(self, action=None): '\n Run the depth-first pre-order traversal algorithm (iterative\n implementation) and subject every node encountered\n to some procedure ``action``. The algorithm is::\n\n manipulate the root with function `action` (in the case\n of a binary tree, only if the root is not a leaf);\n then explore each subtree (by the algorithm) from the\n leftmost one to the rightmost one.\n\n INPUT:\n\n - ``action`` -- (optional) a function which takes a node as\n input, and does something during the exploration\n\n OUTPUT:\n\n ``None``. (This is *not* an iterator.)\n\n .. SEEALSO::\n\n - :meth:`~sage.combinat.abstract_tree.AbstractTree.pre_order_traversal_iter()`\n - :meth:`~sage.combinat.abstract_tree.AbstractTree.pre_order_traversal()`\n\n TESTS::\n\n sage: l = []\n sage: b = BinaryTree([[None,[]],[[[],[]],[]]]).canonical_labelling()\n sage: b\n 3[1[., 2[., .]], 7[5[4[., .], 6[., .]], 8[., .]]]\n sage: b.iterative_pre_order_traversal(lambda node: l.append(node.label()))\n sage: l\n [3, 1, 2, 7, 5, 4, 6, 8]\n\n sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).canonical_labelling()\n sage: t\n 1[2[3[4[], 5[]]], 6[7[]], 8[9[], 10[]]]\n sage: l = []\n sage: t.iterative_pre_order_traversal(lambda node: l.append(node.label()))\n sage: l\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n sage: l = []\n\n sage: BinaryTree().canonical_labelling().\\\n ....: pre_order_traversal(lambda node: l.append(node.label()))\n sage: l\n []\n sage: OrderedTree([]).canonical_labelling().\\\n ....: iterative_pre_order_traversal(lambda node: l.append(node.label()))\n sage: l\n [1]\n\n The following test checks that things do not go wrong if some among\n the descendants of the tree are equal or even identical::\n\n sage: u = BinaryTree(None)\n sage: v = BinaryTree([u, u])\n sage: w = BinaryTree([v, v])\n sage: t = BinaryTree([w, w])\n sage: t.node_number()\n 7\n sage: l = []\n sage: t.iterative_pre_order_traversal(lambda node: l.append(1))\n sage: len(l)\n 7\n ' if self.is_empty(): return if (action is None): def action(x): return None stack = [] stack.append(self) while stack: node = stack.pop() action(node) for i in range(len(node)): subtree = node[((- i) - 1)] if (not subtree.is_empty()): stack.append(subtree) def pre_order_traversal(self, action=None): '\n Run the depth-first pre-order traversal algorithm (recursive\n implementation) and subject every node encountered\n to some procedure ``action``. The algorithm is::\n\n manipulate the root with function `action` (in the case\n of a binary tree, only if the root is not a leaf);\n then explore each subtree (by the algorithm) from the\n leftmost one to the rightmost one.\n\n INPUT:\n\n - ``action`` -- (optional) a function which takes a node as\n input, and does something during the exploration\n\n OUTPUT:\n\n ``None``. (This is *not* an iterator.)\n\n EXAMPLES:\n\n For example, on the following binary tree `b`::\n\n | ___3____ |\n | / \\ |\n | 1 _7_ |\n | \\ / \\ |\n | 2 5 8 |\n | / \\ |\n | 4 6 |\n\n the depth-first pre-order traversal algorithm explores `b` in the\n following order of nodes: `3,1,2,7,5,4,6,8`.\n\n Another example::\n\n | __1____ |\n | / / / |\n | 2 6 8_ |\n | | | / / |\n | 3_ 7 9 10 |\n | / / |\n | 4 5 |\n\n The algorithm explores this tree in the following order:\n `1,2,3,4,5,6,7,8,9,10`.\n\n .. SEEALSO::\n\n - :meth:`~sage.combinat.abstract_tree.AbstractTree.pre_order_traversal_iter()`\n - :meth:`~sage.combinat.abstract_tree.AbstractTree.iterative_pre_order_traversal()`\n\n TESTS::\n\n sage: l = []\n sage: b = BinaryTree([[None,[]],[[[],[]],[]]]).canonical_labelling()\n sage: b\n 3[1[., 2[., .]], 7[5[4[., .], 6[., .]], 8[., .]]]\n sage: b.pre_order_traversal(lambda node: l.append(node.label()))\n sage: l\n [3, 1, 2, 7, 5, 4, 6, 8]\n sage: li = []\n sage: b.iterative_pre_order_traversal(lambda node: li.append(node.label()))\n sage: l == li\n True\n\n sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).canonical_labelling()\n sage: t\n 1[2[3[4[], 5[]]], 6[7[]], 8[9[], 10[]]]\n sage: l = []\n sage: t.pre_order_traversal(lambda node: l.append(node.label()))\n sage: l\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n sage: li = []\n sage: t.iterative_pre_order_traversal(lambda node: li.append(node.label()))\n sage: l == li\n True\n\n sage: l = []\n sage: BinaryTree().canonical_labelling().\\\n ....: pre_order_traversal(lambda node: l.append(node.label()))\n sage: l\n []\n sage: OrderedTree([]).canonical_labelling().\\\n ....: pre_order_traversal(lambda node: l.append(node.label()))\n sage: l\n [1]\n\n The following test checks that things do not go wrong if some among\n the descendants of the tree are equal or even identical::\n\n sage: u = BinaryTree(None)\n sage: v = BinaryTree([u, u])\n sage: w = BinaryTree([v, v])\n sage: t = BinaryTree([w, w])\n sage: t.node_number()\n 7\n sage: l = []\n sage: t.pre_order_traversal(lambda node: l.append(1))\n sage: len(l)\n 7\n ' if (action is None): def action(x): return None for node in self.pre_order_traversal_iter(): action(node) def post_order_traversal_iter(self): '\n The depth-first post-order traversal iterator.\n\n This method iters each node following the depth-first post-order\n traversal algorithm (recursive implementation). The algorithm\n is::\n\n explore each subtree (by the algorithm) from the\n leftmost one to the rightmost one;\n then yield the root (in the case of binary trees, only if\n it is not a leaf).\n\n EXAMPLES:\n\n For example on the following binary tree `b`::\n\n | ___3____ |\n | / \\ |\n | 1 _7_ |\n | \\ / \\ |\n | 2 5 8 |\n | / \\ |\n | 4 6 |\n\n (only the nodes are shown), the depth-first post-order traversal\n algorithm explores `b` in the following order of nodes:\n `2,1,4,6,5,8,7,3`.\n\n For another example, consider the labelled tree::\n\n | __1____ |\n | / / / |\n | 2 6 8_ |\n | | | / / |\n | 3_ 7 9 10 |\n | / / |\n | 4 5 |\n\n The algorithm explores this tree in the following order:\n `4,5,3,2,7,6,9,10,8,1`.\n\n TESTS::\n\n sage: b = BinaryTree([[None,[]],[[[],[]],[]]]).canonical_labelling()\n sage: ascii_art([b])\n [ ___3____ ]\n [ / \\ ]\n [ 1 _7_ ]\n [ \\ / \\ ]\n [ 2 5 8 ]\n [ / \\ ]\n [ 4 6 ]\n sage: [node.label() for node in b.post_order_traversal_iter()]\n [2, 1, 4, 6, 5, 8, 7, 3]\n\n sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).canonical_labelling()\n sage: ascii_art([t])\n [ __1____ ]\n [ / / / ]\n [ 2 6 8_ ]\n [ | | / / ]\n [ 3_ 7 9 10 ]\n [ / / ]\n [ 4 5 ]\n sage: [node.label() for node in t.post_order_traversal_iter()]\n [4, 5, 3, 2, 7, 6, 9, 10, 8, 1]\n\n sage: [node.label() for node in BinaryTree().canonical_labelling().\\\n ....: post_order_traversal_iter()]\n []\n sage: [node.label() for node in OrderedTree([]).\\\n ....: canonical_labelling().post_order_traversal_iter()]\n [1]\n\n The following test checks that things do not go wrong if some among\n the descendants of the tree are equal or even identical::\n\n sage: u = BinaryTree(None)\n sage: v = BinaryTree([u, u])\n sage: w = BinaryTree([v, v])\n sage: t = BinaryTree([w, w])\n sage: t.node_number()\n 7\n sage: l = [1 for i in t.post_order_traversal_iter()]\n sage: len(l)\n 7\n ' if self.is_empty(): return (yield from itertools.chain(*[c.post_order_traversal_iter() for c in self])) (yield self) def post_order_traversal(self, action=None): '\n Run the depth-first post-order traversal algorithm (recursive\n implementation) and subject every node encountered\n to some procedure ``action``. The algorithm is::\n\n explore each subtree (by the algorithm) from the\n leftmost one to the rightmost one;\n then manipulate the root with function `action` (in the\n case of a binary tree, only if the root is not a leaf).\n\n INPUT:\n\n - ``action`` -- (optional) a function which takes a node as\n input, and does something during the exploration\n\n OUTPUT:\n\n ``None``. (This is *not* an iterator.)\n\n .. SEEALSO::\n\n - :meth:`~sage.combinat.abstract_tree.AbstractTree.post_order_traversal_iter()`\n - :meth:`~sage.combinat.abstract_tree.AbstractTree.iterative_post_order_traversal()`\n\n TESTS::\n\n sage: l = []\n sage: b = BinaryTree([[None,[]],[[[],[]],[]]]).canonical_labelling()\n sage: b\n 3[1[., 2[., .]], 7[5[4[., .], 6[., .]], 8[., .]]]\n sage: b.post_order_traversal(lambda node: l.append(node.label()))\n sage: l\n [2, 1, 4, 6, 5, 8, 7, 3]\n\n sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).\\\n ....: canonical_labelling(); t\n 1[2[3[4[], 5[]]], 6[7[]], 8[9[], 10[]]]\n sage: l = []\n sage: t.post_order_traversal(lambda node: l.append(node.label()))\n sage: l\n [4, 5, 3, 2, 7, 6, 9, 10, 8, 1]\n\n sage: l = []\n sage: BinaryTree().canonical_labelling().\\\n ....: post_order_traversal(lambda node: l.append(node.label()))\n sage: l\n []\n sage: OrderedTree([]).canonical_labelling().\\\n ....: post_order_traversal(lambda node: l.append(node.label()))\n sage: l\n [1]\n\n The following test checks that things do not go wrong if some among\n the descendants of the tree are equal or even identical::\n\n sage: u = BinaryTree(None)\n sage: v = BinaryTree([u, u])\n sage: w = BinaryTree([v, v])\n sage: t = BinaryTree([w, w])\n sage: t.node_number()\n 7\n sage: l = []\n sage: t.post_order_traversal(lambda node: l.append(1))\n sage: len(l)\n 7\n ' if (action is None): def action(x): return None for node in self.post_order_traversal_iter(): action(node) def iterative_post_order_traversal(self, action=None): '\n Run the depth-first post-order traversal algorithm (iterative\n implementation) and subject every node encountered\n to some procedure ``action``. The algorithm is::\n\n explore each subtree (by the algorithm) from the\n leftmost one to the rightmost one;\n then manipulate the root with function `action` (in the\n case of a binary tree, only if the root is not a leaf).\n\n INPUT:\n\n - ``action`` -- (optional) a function which takes a node as\n input, and does something during the exploration\n\n OUTPUT:\n\n ``None``. (This is *not* an iterator.)\n\n .. SEEALSO::\n\n - :meth:`~sage.combinat.abstract_tree.AbstractTree.post_order_traversal_iter()`\n\n TESTS::\n\n sage: l = []\n sage: b = BinaryTree([[None,[]],[[[],[]],[]]]).canonical_labelling()\n sage: b\n 3[1[., 2[., .]], 7[5[4[., .], 6[., .]], 8[., .]]]\n sage: b.iterative_post_order_traversal(lambda node: l.append(node.label()))\n sage: l\n [2, 1, 4, 6, 5, 8, 7, 3]\n\n sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).canonical_labelling()\n sage: t\n 1[2[3[4[], 5[]]], 6[7[]], 8[9[], 10[]]]\n sage: l = []\n sage: t.iterative_post_order_traversal(lambda node: l.append(node.label()))\n sage: l\n [4, 5, 3, 2, 7, 6, 9, 10, 8, 1]\n\n sage: l = []\n sage: BinaryTree().canonical_labelling().\\\n ....: iterative_post_order_traversal(\n ....: lambda node: l.append(node.label()))\n sage: l\n []\n sage: OrderedTree([]).canonical_labelling().\\\n ....: iterative_post_order_traversal(\n ....: lambda node: l.append(node.label()))\n sage: l\n [1]\n\n The following test checks that things do not go wrong if some among\n the descendants of the tree are equal or even identical::\n\n sage: u = BinaryTree(None)\n sage: v = BinaryTree([u, u])\n sage: w = BinaryTree([v, v])\n sage: t = BinaryTree([w, w])\n sage: t.node_number()\n 7\n sage: l = []\n sage: t.iterative_post_order_traversal(lambda node: l.append(1))\n sage: len(l)\n 7\n ' if self.is_empty(): return if (action is None): def action(x): return None stack = [self] while stack: node = stack[(- 1)] if (node is not None): stack.append(None) for i in range(len(node)): subtree = node[((- i) - 1)] if (not subtree.is_empty()): stack.append(subtree) else: stack.pop() node = stack.pop() action(node) def breadth_first_order_traversal(self, action=None): '\n Run the breadth-first post-order traversal algorithm\n and subject every node encountered to some procedure\n ``action``. The algorithm is::\n\n queue <- [ root ];\n while the queue is not empty:\n node <- pop( queue );\n manipulate the node;\n prepend to the queue the list of all subtrees of\n the node (from the rightmost to the leftmost).\n\n INPUT:\n\n - ``action`` -- (optional) a function which takes a node as\n input, and does something during the exploration\n\n OUTPUT:\n\n ``None``. (This is *not* an iterator.)\n\n EXAMPLES:\n\n For example, on the following binary tree `b`::\n\n | ___3____ |\n | / \\ |\n | 1 _7_ |\n | \\ / \\ |\n | 2 5 8 |\n | / \\ |\n | 4 6 |\n\n the breadth-first order traversal algorithm explores `b` in the\n following order of nodes: `3,1,7,2,5,8,4,6`.\n\n TESTS::\n\n sage: b = BinaryTree([[None,[]],[[[],[]],[]]]).canonical_labelling()\n sage: l = []\n sage: b.breadth_first_order_traversal(lambda node: l.append(node.label()))\n sage: l\n [3, 1, 7, 2, 5, 8, 4, 6]\n\n sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).canonical_labelling()\n sage: t\n 1[2[3[4[], 5[]]], 6[7[]], 8[9[], 10[]]]\n sage: l = []\n sage: t.breadth_first_order_traversal(lambda node: l.append(node.label()))\n sage: l\n [1, 2, 6, 8, 3, 7, 9, 10, 4, 5]\n\n sage: l = []\n sage: BinaryTree().canonical_labelling().\\\n ....: breadth_first_order_traversal(\n ....: lambda node: l.append(node.label()))\n sage: l\n []\n sage: OrderedTree([]).canonical_labelling().\\\n ....: breadth_first_order_traversal(\n ....: lambda node: l.append(node.label()))\n sage: l\n [1]\n ' if self.is_empty(): return if (action is None): def action(x): return None queue = [] queue.append(self) while queue: node = queue.pop() action(node) for subtree in node: if (not subtree.is_empty()): queue.insert(0, subtree) def paths_at_depth(self, depth, path=[]): '\n Return a generator for all paths at a fixed depth.\n\n This iterates over all paths for nodes that are at the given depth.\n\n Here the root is considered to have depth 0.\n\n INPUT:\n\n - depth -- an integer\n - path -- optional given path (as a list) used in the recursion\n\n .. WARNING::\n\n The ``path`` option should not be used directly.\n\n .. SEEALSO::\n\n :meth:`paths`, :meth:`paths_to_the_right`, :meth:`node_number_at_depth`\n\n EXAMPLES::\n\n sage: T = OrderedTree([[[], [[], [[]]]], [], [[[],[]]], [], []])\n sage: ascii_art(T)\n ______o_______\n / / / / /\n _o__ o o o o\n / / |\n o o_ o_\n / / / /\n o o o o\n |\n o\n sage: list(T.paths_at_depth(0))\n [()]\n sage: list(T.paths_at_depth(2))\n [(0, 0), (0, 1), (2, 0)]\n sage: list(T.paths_at_depth(4))\n [(0, 1, 1, 0)]\n sage: list(T.paths_at_depth(5))\n []\n\n sage: T2 = OrderedTree([])\n sage: list(T2.paths_at_depth(0))\n [()]\n ' if (not depth): (yield tuple(path)) else: for i in range(len(self)): (yield from self[i].paths_at_depth((depth - 1), (path + [i]))) def node_number_at_depth(self, depth): '\n Return the number of nodes at a given depth.\n\n This counts all nodes that are at the given depth.\n\n Here the root is considered to have depth 0.\n\n INPUT:\n\n - depth -- an integer\n\n .. SEEALSO::\n\n :meth:`node_number`, :meth:`node_number_to_the_right`, :meth:`paths_at_depth`\n\n EXAMPLES::\n\n sage: T = OrderedTree([[[], [[]]], [[], [[[]]]], []])\n sage: ascii_art(T)\n ___o____\n / / /\n o_ o_ o\n / / / /\n o o o o\n | |\n o o\n |\n o\n sage: [T.node_number_at_depth(i) for i in range(6)]\n [1, 3, 4, 2, 1, 0]\n\n TESTS:\n\n Check that the empty tree has no nodes (:trac:`29134`)::\n\n sage: T = BinaryTree()\n sage: T\n .\n sage: T.is_empty()\n True\n sage: [T.node_number_at_depth(i) for i in range(3)]\n [0, 0, 0]\n ' if self.is_empty(): return Integer(0) if (depth == 0): return Integer(1) return sum((son.node_number_at_depth((depth - 1)) for son in self)) def paths_to_the_right(self, path): '\n Return a generator of paths for all nodes at the same\n depth and to the right of the node identified by ``path``.\n\n This iterates over the paths for nodes that are at the same\n depth as the given one, and strictly to its right.\n\n INPUT:\n\n - ``path`` -- any path in the tree\n\n .. SEEALSO::\n\n :meth:`paths`, :meth:`paths_at_depth`, :meth:`node_number_to_the_right`\n\n EXAMPLES::\n\n sage: T = OrderedTree([[[], [[]]], [[], [[[]]]], []])\n sage: ascii_art(T)\n ___o____\n / / /\n o_ o_ o\n / / / /\n o o o o\n | |\n o o\n |\n o\n sage: g = T.paths_to_the_right(())\n sage: list(g)\n []\n\n sage: g = T.paths_to_the_right((0,))\n sage: list(g)\n [(1,), (2,)]\n\n sage: g = T.paths_to_the_right((0,1))\n sage: list(g)\n [(1, 0), (1, 1)]\n\n sage: g = T.paths_to_the_right((0,1,0))\n sage: list(g)\n [(1, 1, 0)]\n\n sage: g = T.paths_to_the_right((1,2))\n sage: list(g)\n []\n ' depth = len(path) if ((not depth) or (path[0] >= len(self))): return for i in range((path[0] + 1), len(self)): for p in self[i].paths_at_depth((depth - 1), path=[i]): (yield p) for p in self[path[0]].paths_to_the_right(path[1:]): (yield tuple(([path[0]] + list(p)))) def node_number_to_the_right(self, path): '\n Return the number of nodes at the same depth and to the right of\n the node identified by ``path``.\n\n This counts the nodes that are at the same depth as the given\n one, and strictly to its right.\n\n .. SEEALSO::\n\n :meth:`node_number`, :meth:`node_number_at_depth`, :meth:`paths_to_the_right`\n\n EXAMPLES::\n\n sage: T = OrderedTree([[[], [[]]], [[], [[[]]]], []])\n sage: ascii_art(T)\n ___o____\n / / /\n o_ o_ o\n / / / /\n o o o o\n | |\n o o\n |\n o\n sage: T.node_number_to_the_right(())\n 0\n sage: T.node_number_to_the_right((0,))\n 2\n sage: T.node_number_to_the_right((0,1))\n 2\n sage: T.node_number_to_the_right((0,1,0))\n 1\n\n sage: T = OrderedTree([])\n sage: T.node_number_to_the_right(())\n 0\n ' depth = len(path) if (depth == 0): return Integer(0) result = sum((son.node_number_at_depth((depth - 1)) for son in self[(path[0] + 1):])) if ((path[0] < len(self)) and (path[0] >= 0)): result += self[path[0]].node_number_to_the_right(path[1:]) return result def subtrees(self): '\n Return a generator for all nonempty subtrees of ``self``.\n\n The number of nonempty subtrees of a tree is its number of\n nodes. (The word "nonempty" makes a difference only in the\n case of binary trees. For ordered trees, for example, all\n trees are nonempty.)\n\n EXAMPLES::\n\n sage: list(OrderedTree([]).subtrees())\n [[]]\n sage: list(OrderedTree([[],[[]]]).subtrees())\n [[[], [[]]], [], [[]], []]\n\n sage: list(OrderedTree([[],[[]]]).canonical_labelling().subtrees())\n [1[2[], 3[4[]]], 2[], 3[4[]], 4[]]\n\n sage: list(BinaryTree([[],[[],[]]]).subtrees())\n [[[., .], [[., .], [., .]]], [., .], [[., .], [., .]], [., .], [., .]]\n\n sage: v = BinaryTree([[],[]])\n sage: list(v.canonical_labelling().subtrees())\n [2[1[., .], 3[., .]], 1[., .], 3[., .]]\n\n TESTS::\n\n sage: t = OrderedTree([[], [[], [[], []], [[], []]], [[], []]])\n sage: t.node_number() == len(list(t.subtrees()))\n True\n sage: list(BinaryTree().subtrees())\n []\n sage: bt = BinaryTree([[],[[],[]]])\n sage: bt.node_number() == len(list(bt.subtrees()))\n True\n ' return self.pre_order_traversal_iter() def paths(self): '\n Return a generator for all paths to nodes of ``self``.\n\n OUTPUT:\n\n This method returns a list of sequences of integers. Each of these\n sequences represents a path from the root node to some node. For\n instance, `(1, 3, 2, 5, 0, 3)` represents the node obtained by\n choosing the 1st child of the root node (in the ordering returned\n by ``iter``), then the 3rd child of its child, then the 2nd child\n of the latter, etc. (where the labelling of the children is\n zero-based).\n\n The root element is represented by the empty tuple ``()``.\n\n .. SEEALSO::\n\n :meth:`paths_at_depth`, :meth:`paths_to_the_right`\n\n EXAMPLES::\n\n sage: list(OrderedTree([]).paths())\n [()]\n sage: list(OrderedTree([[],[[]]]).paths())\n [(), (0,), (1,), (1, 0)]\n\n sage: list(BinaryTree([[],[[],[]]]).paths())\n [(), (0,), (1,), (1, 0), (1, 1)]\n\n TESTS::\n\n sage: t = OrderedTree([[], [[], [[], []], [[], []]], [[], []]])\n sage: t.node_number() == len(list(t.paths()))\n True\n sage: list(BinaryTree().paths())\n []\n sage: bt = BinaryTree([[],[[],[]]])\n sage: bt.node_number() == len(list(bt.paths()))\n True\n ' if (not self.is_empty()): (yield ()) for (i, t) in enumerate(self): for p in t.paths(): (yield ((i,) + p)) def node_number(self): '\n Return the number of nodes of ``self``.\n\n .. SEEALSO::\n\n :meth:`node_number_at_depth`, :meth:`node_number_to_the_right`\n\n EXAMPLES::\n\n sage: OrderedTree().node_number()\n 1\n sage: OrderedTree([]).node_number()\n 1\n sage: OrderedTree([[],[]]).node_number()\n 3\n sage: OrderedTree([[],[[]]]).node_number()\n 4\n sage: OrderedTree([[], [[], [[], []], [[], []]], [[], []]]).node_number()\n 13\n\n EXAMPLES::\n\n sage: BinaryTree(None).node_number()\n 0\n sage: BinaryTree([]).node_number()\n 1\n sage: BinaryTree([[], None]).node_number()\n 2\n sage: BinaryTree([[None, [[], []]], None]).node_number()\n 5\n ' if self.is_empty(): return Integer(0) else: return sum((i.node_number() for i in self), Integer(1)) def depth(self): '\n Return the depth of ``self``.\n\n EXAMPLES::\n\n sage: OrderedTree().depth()\n 1\n sage: OrderedTree([]).depth()\n 1\n sage: OrderedTree([[],[]]).depth()\n 2\n sage: OrderedTree([[],[[]]]).depth()\n 3\n sage: OrderedTree([[], [[], [[], []], [[], []]], [[], []]]).depth()\n 4\n\n sage: BinaryTree().depth()\n 0\n sage: BinaryTree([[],[[],[]]]).depth()\n 3\n ' if self: return Integer((1 + max((i.depth() for i in self)))) else: return Integer((0 if self.is_empty() else 1)) def _ascii_art_(self): '\n TESTS::\n\n sage: t = OrderedTree([])\n sage: ascii_art(t)\n o\n sage: t = OrderedTree([[]])\n sage: aa = ascii_art(t);aa\n o\n |\n o\n sage: aa.get_baseline()\n 2\n sage: tt1 = OrderedTree([[],[[],[],[[[[]]]]],[[[],[],[],[]]]])\n sage: ascii_art(tt1)\n _____o_______\n / / /\n o _o__ o\n / / / |\n o o o __o___\n | / / / /\n o o o o o\n |\n o\n |\n o\n sage: ascii_art(tt1.canonical_labelling())\n ______1_______\n / / /\n 2 _3__ 10\n / / / |\n 4 5 6 ___11____\n | / / / /\n 7 12 13 14 15\n |\n 8\n |\n 9\n sage: ascii_art(OrderedTree([[],[[]]]))\n o_\n / /\n o o\n |\n o\n sage: t = OrderedTree([[[],[[[],[]]],[[]]],[[[[[],[]]]]],[[],[]]])\n sage: ascii_art(t)\n _____o_______\n / / /\n __o____ o o_\n / / / | / /\n o o o o o o\n | | |\n o_ o o\n / / |\n o o o_\n / /\n o o\n sage: ascii_art(t.canonical_labelling())\n ______1________\n / / /\n __2____ 10 16_\n / / / | / /\n 3 4 8 11 17 18\n | | |\n 5_ 9 12\n / / |\n 6 7 13_\n / /\n 14 15\n ' def node_to_str(t): return (str(t.label()) if hasattr(t, 'label') else 'o') if self.is_empty(): from sage.typeset.ascii_art import empty_ascii_art return empty_ascii_art from sage.typeset.ascii_art import AsciiArt if (len(self) == 0): t_repr = AsciiArt([node_to_str(self)]) t_repr._root = 1 return t_repr if (len(self) == 1): repr_child = self[0]._ascii_art_() sep = AsciiArt([(' ' * (repr_child._root - 1))]) t_repr = AsciiArt([node_to_str(self)]) t_repr._root = 1 repr_root = ((sep + t_repr) * (sep + AsciiArt(['|']))) t_repr = (repr_root * repr_child) t_repr._root = repr_child._root t_repr._baseline = (t_repr._h - 1) return t_repr l_repr = [subtree._ascii_art_() for subtree in self] acc = l_repr.pop(0) whitesep = (acc._root + 1) lf_sep = ((' ' * (acc._root + 1)) + ('_' * (acc._l - acc._root))) ls_sep = (((' ' * acc._root) + '/') + (' ' * (acc._l - acc._root))) while l_repr: t_repr = l_repr.pop(0) acc += (AsciiArt([' ']) + t_repr) if (len(l_repr) == 0): lf_sep += ('_' * (t_repr._root + 1)) else: lf_sep += ('_' * (t_repr._l + 1)) ls_sep += (((' ' * t_repr._root) + '/') + (' ' * (t_repr._l - t_repr._root))) mid = (whitesep + ((len(lf_sep) - whitesep) // 2)) node = node_to_str(self) t_repr = (AsciiArt([((lf_sep[:(mid - 1)] + node) + lf_sep[((mid + len(node)) - 1):]), ls_sep]) * acc) t_repr._root = mid t_repr._baseline = (t_repr._h - 1) return t_repr def _unicode_art_(self): '\n TESTS::\n\n sage: t = OrderedTree([])\n sage: unicode_art(t)\n o\n sage: t = OrderedTree([[]])\n sage: aa = unicode_art(t);aa\n o\n │\n o\n sage: aa.get_baseline()\n 2\n sage: tt1 = OrderedTree([[],[[],[],[[[[]]]]],[[[],[],[],[]]]])\n sage: unicode_art(tt1)\n ╭───┬─o────╮\n │ │ │\n o ╭─o─╮ o\n │ │ │ │\n o o o ╭─┬o┬─╮\n │ │ │ │ │\n o o o o o\n │\n o\n │\n o\n sage: unicode_art(tt1.canonical_labelling())\n ╭───┬──1─────╮\n │ │ │\n 2 ╭─3─╮ 10\n │ │ │ │\n 4 5 6 ╭──┬11┬──╮\n │ │ │ │ │\n 7 12 13 14 15\n │\n 8\n │\n 9\n sage: unicode_art(OrderedTree([[],[[]]]))\n ╭o╮\n │ │\n o o\n │\n o\n sage: t = OrderedTree([[[],[[[],[]]],[[]]],[[[[[],[]]]]],[[],[]]])\n sage: unicode_art(t)\n ╭────o┬───╮\n │ │ │\n ╭──o──╮ o ╭o╮\n │ │ │ │ │ │\n o o o o o o\n │ │ │\n ╭o╮ o o\n │ │ │\n o o ╭o╮\n │ │\n o o\n sage: unicode_art(t.canonical_labelling())\n ╭──────1─────╮\n │ │ │\n ╭──2──╮ 10 ╭16╮\n │ │ │ │ │ │\n 3 4 8 11 17 18\n │ │ │\n ╭5╮ 9 12\n │ │ │\n 6 7 ╭13╮\n │ │\n 14 15\n ' def node_to_str(t): if hasattr(t, 'label'): return str(t.label()) else: return 'o' if self.is_empty(): from sage.typeset.unicode_art import empty_unicode_art return empty_unicode_art from sage.typeset.unicode_art import UnicodeArt if (not len(self)): t_repr = UnicodeArt([node_to_str(self)]) t_repr._root = 0 return t_repr if (len(self) == 1): repr_child = self[0]._unicode_art_() sep = UnicodeArt([(' ' * repr_child._root)]) t_repr = UnicodeArt([node_to_str(self)]) repr_root = ((sep + t_repr) * (sep + UnicodeArt(['│']))) t_repr = (repr_root * repr_child) t_repr._root = repr_child._root t_repr._baseline = (t_repr._h - 1) return t_repr l_repr = [subtree._unicode_art_() for subtree in self] acc = l_repr.pop(0) whitesep = acc._root lf_sep = (((' ' * whitesep) + '╭') + ('─' * (acc._l - acc._root))) ls_sep = (((' ' * whitesep) + '│') + (' ' * (acc._l - acc._root))) while l_repr: tr = l_repr.pop(0) acc += (UnicodeArt([' ']) + tr) if (not len(l_repr)): lf_sep += (('─' * tr._root) + '╮') ls_sep += ((' ' * tr._root) + '│') else: lf_sep += ((('─' * tr._root) + '┬') + ('─' * (tr._l - tr._root))) ls_sep += (((' ' * tr._root) + '│') + (' ' * (tr._l - tr._root))) mid = (whitesep + ((len(lf_sep) - whitesep) // 2)) node = node_to_str(self) lf_sep = ((lf_sep[:(mid - (len(node) // 2))] + node) + lf_sep[((mid + len(node)) - (len(node) // 2)):]) t_repr = (UnicodeArt([lf_sep, ls_sep]) * acc) t_repr._root = mid t_repr._baseline = (t_repr._h - 1) return t_repr def canonical_labelling(self, shift=1): '\n Return a labelled version of ``self``.\n\n The actual canonical labelling is currently unspecified. However, it\n is guaranteed to have labels in `1...n` where `n` is the number of\n nodes of the tree. Moreover, two (unlabelled) trees compare as equal if\n and only if their canonical labelled trees compare as equal.\n\n EXAMPLES::\n\n sage: t = OrderedTree([[], [[], [[], []], [[], []]], [[], []]])\n sage: t.canonical_labelling()\n 1[2[], 3[4[], 5[6[], 7[]], 8[9[], 10[]]], 11[12[], 13[]]]\n\n sage: BinaryTree([]).canonical_labelling()\n 1[., .]\n sage: BinaryTree([[],[[],[]]]).canonical_labelling()\n 2[1[., .], 4[3[., .], 5[., .]]]\n\n TESTS::\n\n sage: BinaryTree().canonical_labelling()\n .\n ' LTR = self.parent().labelled_trees() liste = [] deca = 1 for subtree in self: liste += [subtree.canonical_labelling((shift + deca))] deca += subtree.node_number() return LTR._element_constructor_(liste, label=shift) def to_hexacode(self): "\n Transform a tree into a hexadecimal string.\n\n The definition of the hexacode is recursive. The first letter is\n the valence of the root as a hexadecimal (up to 15), followed by\n the concatenation of the hexacodes of the subtrees.\n\n This method only works for trees where every vertex has\n valency at most 15.\n\n See :func:`from_hexacode` for the reverse transformation.\n\n EXAMPLES::\n\n sage: from sage.combinat.abstract_tree import from_hexacode\n sage: LT = LabelledOrderedTrees()\n sage: from_hexacode('2010', LT).to_hexacode()\n '2010'\n sage: LT.an_element().to_hexacode()\n '3020010'\n sage: t = from_hexacode('a0000000000000000', LT)\n sage: t.to_hexacode()\n 'a0000000000'\n\n sage: OrderedTrees(6).an_element().to_hexacode()\n '500000'\n\n TESTS::\n\n sage: one = LT([], label='@')\n sage: LT([one for _ in range(15)], label='@').to_hexacode()\n 'f000000000000000'\n sage: LT([one for _ in range(16)], label='@').to_hexacode()\n Traceback (most recent call last):\n ...\n ValueError: the width of the tree is too large\n " if (len(self) > 15): raise ValueError('the width of the tree is too large') if (self.node_number() == 1): return '0' return (('%x' % len(self)) + ''.join((u.to_hexacode() for u in self))) def tree_factorial(self): '\n Return the tree-factorial of ``self``.\n\n Definition:\n\n The tree-factorial `T!` of a tree `T` is the product `\\prod_{v\\in\n T}\\#\\mbox{children}(v)`.\n\n EXAMPLES::\n\n sage: LT = LabelledOrderedTrees()\n sage: t = LT([LT([],label=6),LT([],label=1)],label=9)\n sage: t.tree_factorial()\n 3\n\n sage: BinaryTree([[],[[],[]]]).tree_factorial()\n 15\n\n TESTS::\n\n sage: BinaryTree().tree_factorial()\n 1\n ' nb = self.node_number() if (nb <= 1): return Integer(1) return (nb * prod((s.tree_factorial() for s in self))) def _latex_(self): '\n Generate `\\LaTeX` output which can be easily modified.\n\n TESTS::\n\n sage: latex(BinaryTree([[[],[]],[[],None]]))\n { \\newcommand{\\nodea}{\\node[draw,circle] (a) {$$}\n ;}\\newcommand{\\nodeb}{\\node[draw,circle] (b) {$$}\n ;}\\newcommand{\\nodec}{\\node[draw,circle] (c) {$$}\n ;}\\newcommand{\\noded}{\\node[draw,circle] (d) {$$}\n ;}\\newcommand{\\nodee}{\\node[draw,circle] (e) {$$}\n ;}\\newcommand{\\nodef}{\\node[draw,circle] (f) {$$}\n ;}\\begin{tikzpicture}[auto]\n \\matrix[column sep=.3cm, row sep=.3cm,ampersand replacement=\\&]{\n \\& \\& \\& \\nodea \\& \\& \\& \\\\\n \\& \\nodeb \\& \\& \\& \\& \\nodee \\& \\\\\n \\nodec \\& \\& \\noded \\& \\& \\nodef \\& \\& \\\\\n };\n <BLANKLINE>\n \\path[ultra thick, red] (b) edge (c) edge (d)\n (e) edge (f)\n (a) edge (b) edge (e);\n \\end{tikzpicture}}\n ' from sage.misc.latex import latex latex.add_package_to_preamble_if_available('tikz') begin_env = '\\begin{tikzpicture}[auto]\n' end_env = '\\end{tikzpicture}' matrix_begin = '\\matrix[column sep=.3cm, row sep=.3cm,ampersand replacement=\\&]{\n' matrix_end = '\\\\\n};\n' path_begin = '\\path[ultra thick, red] ' path_end = ';\n' cmd = '\\node' new_cmd1 = ('\\newcommand{' + cmd) new_cmd2 = '}{\\node[draw,circle] (' new_cmd3 = ') {$' new_cmd4 = '$}\n;}' sep = '\\&' space = (' ' * 9) sepspace = (sep + space) spacesep = (space + sep) def node_to_str(node): return ((' ' + node) + (' ' * ((len(space) - 1) - len(node)))) num = [0] def resolve(self): nodes = [] matrix = [] edges = [] def create_node(self): '\n create a name (infixe reading)\n -> ex: b\n create a new command:\n -> ex: \\newcommand{\\nodeb}{\\node[draw,circle] (b) {$$};\n return the name and the command to build:\n . the matrix\n . and the edges\n ' name = ''.join((chr((ord(x) + 49)) for x in str(num[0]))) node = (cmd + name) nodes.append((name, (str(self.label()) if hasattr(self, 'label') else ''))) num[0] += 1 return (node, name) def empty_tree(): '\n TESTS::\n\n sage: t = BinaryTree()\n sage: print(latex(t))\n { \\begin{tikzpicture}[auto]\n \\matrix[column sep=.3cm, row sep=.3cm,ampersand replacement=\\&]{\n \\\\\n };\n \\end{tikzpicture}}\n ' matrix.append(space) def one_node_tree(self): '\n TESTS::\n\n sage: t = BinaryTree([]); print(latex(t))\n { \\newcommand{\\nodea}{\\node[draw,circle] (a) {$$}\n ;}\\begin{tikzpicture}[auto]\n \\matrix[column sep=.3cm, row sep=.3cm,ampersand replacement=\\&]{\n \\nodea \\\\\n };\n \\end{tikzpicture}}\n sage: t = OrderedTree([]); print(latex(t))\n { \\newcommand{\\nodea}{\\node[draw,circle] (a) {$$}\n ;}\\begin{tikzpicture}[auto]\n \\matrix[column sep=.3cm, row sep=.3cm,ampersand replacement=\\&]{\n \\nodea \\\\\n };\n \\end{tikzpicture}}\n ' (node, _) = create_node(self) matrix.append(node_to_str(node)) def concat_matrix(mat, mat2): lmat = len(mat) lmat2 = len(mat2) for i in range(max(lmat, lmat2)): try: mat[i] += (sep + mat2[i]) except IndexError: if (i >= lmat): if (i != 0): nb_of_and = (mat[0].count(sep) - mat2[0].count(sep)) mat.append(((spacesep * nb_of_and) + mat2[i])) else: mat.extend(mat2) return else: nb_of_and = mat2[0].count(sep) mat[i] += (sepspace * (nb_of_and + 1)) def tmp(subtree, edge, nodes, edges, matrix): if (not subtree.is_empty()): (nodes_st, matrix_st, edges_st) = resolve(subtree) nodes.extend(nodes_st) edge.append(nodes_st[0][0]) edges.extend(edges_st) concat_matrix(matrix, matrix_st) else: concat_matrix(matrix, [space]) def pair_nodes_tree(self, nodes, edges, matrix): '\n TESTS::\n\n sage: t = OrderedTree([[[],[]],[[],[]]]).\\\n ....: canonical_labelling(); print(latex(t))\n { \\newcommand{\\nodea}{\\node[draw,circle] (a) {$1$}\n ;}\\newcommand{\\nodeb}{\\node[draw,circle] (b) {$2$}\n ;}\\newcommand{\\nodec}{\\node[draw,circle] (c) {$3$}\n ;}\\newcommand{\\noded}{\\node[draw,circle] (d) {$4$}\n ;}\\newcommand{\\nodee}{\\node[draw,circle] (e) {$5$}\n ;}\\newcommand{\\nodef}{\\node[draw,circle] (f) {$6$}\n ;}\\newcommand{\\nodeg}{\\node[draw,circle] (g) {$7$}\n ;}\\begin{tikzpicture}[auto]\n \\matrix[column sep=.3cm, row sep=.3cm,ampersand replacement=\\&]{\n \\& \\& \\& \\nodea \\& \\& \\& \\\\\n \\& \\nodeb \\& \\& \\& \\& \\nodee \\& \\\\\n \\nodec \\& \\& \\noded \\& \\& \\nodef \\& \\& \\nodeg \\\\\n };\n <BLANKLINE>\n \\path[ultra thick, red] (b) edge (c) edge (d)\n (e) edge (f) edge (g)\n (a) edge (b) edge (e);\n \\end{tikzpicture}}\n sage: t = BinaryTree([[],[[],[]]]); print(latex(t))\n { \\newcommand{\\nodea}{\\node[draw,circle] (a) {$$}\n ;}\\newcommand{\\nodeb}{\\node[draw,circle] (b) {$$}\n ;}\\newcommand{\\nodec}{\\node[draw,circle] (c) {$$}\n ;}\\newcommand{\\noded}{\\node[draw,circle] (d) {$$}\n ;}\\newcommand{\\nodee}{\\node[draw,circle] (e) {$$}\n ;}\\begin{tikzpicture}[auto]\n \\matrix[column sep=.3cm, row sep=.3cm,ampersand replacement=\\&]{\n \\& \\nodea \\& \\& \\& \\\\\n \\nodeb \\& \\& \\& \\nodec \\& \\\\\n \\& \\& \\noded \\& \\& \\nodee \\\\\n };\n <BLANKLINE>\n \\path[ultra thick, red] (c) edge (d) edge (e)\n (a) edge (b) edge (c);\n \\end{tikzpicture}}\n ' (node, name) = create_node(self) edge = [name] split = (len(self) // 2) for i in range(split): tmp(self[i], edge, nodes, edges, matrix) nb_of_and = matrix[0].count(sep) for i in range(len(matrix)): matrix[i] += sepspace for i in range(split, len(self)): tmp(self[i], edge, nodes, edges, matrix) root_line = (((spacesep * (nb_of_and + 1)) + node_to_str(node)) + (sepspace * ((matrix[0].count(sep) - nb_of_and) - 1))) matrix.insert(0, root_line) edges.append(edge) def odd_nodes_tree(self, nodes, edges, matrix): '\n TESTS::\n\n sage: t = OrderedTree([[]]).canonical_labelling()\n sage: print(latex(t))\n { \\newcommand{\\nodea}{\\node[draw,circle] (a) {$1$}\n ;}\\newcommand{\\nodeb}{\\node[draw,circle] (b) {$2$}\n ;}\\begin{tikzpicture}[auto]\n \\matrix[column sep=.3cm, row sep=.3cm,ampersand replacement=\\&]{\n \\nodea \\\\\n \\nodeb \\\\\n };\n <BLANKLINE>\n \\path[ultra thick, red] (a) edge (b);\n \\end{tikzpicture}}\n sage: t = OrderedTree([[[],[]]]).canonical_labelling(); print(latex(t))\n { \\newcommand{\\nodea}{\\node[draw,circle] (a) {$1$}\n ;}\\newcommand{\\nodeb}{\\node[draw,circle] (b) {$2$}\n ;}\\newcommand{\\nodec}{\\node[draw,circle] (c) {$3$}\n ;}\\newcommand{\\noded}{\\node[draw,circle] (d) {$4$}\n ;}\\begin{tikzpicture}[auto]\n \\matrix[column sep=.3cm, row sep=.3cm,ampersand replacement=\\&]{\n \\& \\nodea \\& \\\\\n \\& \\nodeb \\& \\\\\n \\nodec \\& \\& \\noded \\\\\n };\n <BLANKLINE>\n \\path[ultra thick, red] (b) edge (c) edge (d)\n (a) edge (b);\n \\end{tikzpicture}}\n sage: t = OrderedTree([[[],[],[]]]).canonical_labelling(); print(latex(t))\n { \\newcommand{\\nodea}{\\node[draw,circle] (a) {$1$}\n ;}\\newcommand{\\nodeb}{\\node[draw,circle] (b) {$2$}\n ;}\\newcommand{\\nodec}{\\node[draw,circle] (c) {$3$}\n ;}\\newcommand{\\noded}{\\node[draw,circle] (d) {$4$}\n ;}\\newcommand{\\nodee}{\\node[draw,circle] (e) {$5$}\n ;}\\begin{tikzpicture}[auto]\n \\matrix[column sep=.3cm, row sep=.3cm,ampersand replacement=\\&]{\n \\& \\nodea \\& \\\\\n \\& \\nodeb \\& \\\\\n \\nodec \\& \\noded \\& \\nodee \\\\\n };\n <BLANKLINE>\n \\path[ultra thick, red] (b) edge (c) edge (d) edge (e)\n (a) edge (b);\n \\end{tikzpicture}}\n sage: t = OrderedTree([[[],[],[]],[],[]]).canonical_labelling(); print(latex(t))\n { \\newcommand{\\nodea}{\\node[draw,circle] (a) {$1$}\n ;}\\newcommand{\\nodeb}{\\node[draw,circle] (b) {$2$}\n ;}\\newcommand{\\nodec}{\\node[draw,circle] (c) {$3$}\n ;}\\newcommand{\\noded}{\\node[draw,circle] (d) {$4$}\n ;}\\newcommand{\\nodee}{\\node[draw,circle] (e) {$5$}\n ;}\\newcommand{\\nodef}{\\node[draw,circle] (f) {$6$}\n ;}\\newcommand{\\nodeg}{\\node[draw,circle] (g) {$7$}\n ;}\\begin{tikzpicture}[auto]\n \\matrix[column sep=.3cm, row sep=.3cm,ampersand replacement=\\&]{\n \\& \\& \\& \\nodea \\& \\\\\n \\& \\nodeb \\& \\& \\nodef \\& \\nodeg \\\\\n \\nodec \\& \\noded \\& \\nodee \\& \\& \\\\\n };\n <BLANKLINE>\n \\path[ultra thick, red] (b) edge (c) edge (d) edge (e)\n (a) edge (b) edge (f) edge (g);\n \\end{tikzpicture}}\n ' (node, name) = create_node(self) edge = [name] split = (len(self) // 2) for i in range(split): tmp(self[i], edge, nodes, edges, matrix) if matrix: nb_of_and = matrix[0].count(sep) sizetmp = len(matrix[0]) else: nb_of_and = 0 sizetmp = 0 tmp(self[split], edge, nodes, edges, matrix) nb_of_and += matrix[0][sizetmp:].split('node')[0].count(sep) for i in range((split + 1), len(self)): tmp(self[i], edge, nodes, edges, matrix) root_line = (((spacesep * nb_of_and) + node_to_str(node)) + (sepspace * (matrix[0].count(sep) - nb_of_and))) matrix.insert(0, root_line) edges.append(edge) if self.is_empty(): empty_tree() elif ((len(self) == 0) or all((subtree.is_empty() for subtree in self))): one_node_tree(self) elif (not (len(self) % 2)): pair_nodes_tree(self, nodes, edges, matrix) else: odd_nodes_tree(self, nodes, edges, matrix) return (nodes, matrix, edges) (nodes, matrix, edges) = resolve(self) def make_cmd(nodes): cmds = [] for (name, label) in nodes: cmds.append(((((((new_cmd1 + name) + new_cmd2) + name) + new_cmd3) + label) + new_cmd4)) return cmds def make_edges(edges): all_paths = [] for edge in edges: path = (('(' + edge[0]) + ')') for i in range(1, len(edge)): path += (' edge (%s)' % edge[i]) all_paths.append(path) return all_paths return ((((('{ ' + ''.join(make_cmd(nodes))) + begin_env) + ((((matrix_begin + '\\\\ \n'.join(matrix)) + matrix_end) + (((('\n' + path_begin) + '\n\t'.join(make_edges(edges))) + path_end) if edges else '')) if matrix else '')) + end_env) + '}')
class AbstractClonableTree(AbstractTree): '\n Abstract Clonable Tree.\n\n An abstract class for trees with clone protocol (see\n :mod:`~sage.structure.list_clone`). It is expected that classes extending\n this one may also inherit from classes like :class:`~sage.structure.list_clone.ClonableArray` or\n :class:`~sage.structure.list_clone.ClonableList` depending whether one\n wants to build trees where adding a child is allowed.\n\n .. NOTE:: Due to the limitation of Cython inheritance, one cannot inherit\n here from :class:`~sage.structure.list_clone.ClonableElement`, because\n it would prevent us from later inheriting from\n :class:`~sage.structure.list_clone.ClonableArray` or\n :class:`~sage.structure.list_clone.ClonableList`.\n\n .. rubric:: How should this class be extended ?\n\n A class extending :class:`AbstractClonableTree\n <sage.combinat.abstract_tree.AbstractClonableTree>` should satisfy the\n following assumptions:\n\n * An instantiable class extending :class:`AbstractClonableTree\n <sage.combinat.abstract_tree.AbstractClonableTree>` should also extend\n the :class:`ClonableElement <sage.structure.list_clone.ClonableElement>`\n class or one of its subclasses generally, at least :class:`ClonableArray\n <sage.structure.list_clone.ClonableArray>`.\n\n * To respect the Clone protocol, the :meth:`AbstractClonableTree.check`\n method should be overridden by the new class.\n\n See also the assumptions in :class:`AbstractTree`.\n ' def check(self): '\n Check that ``self`` is a correct tree.\n\n This method does nothing. It is implemented here because many\n extensions of :class:`AbstractClonableTree\n <sage.combinat.abstract_tree.AbstractClonableTree>` also extend\n :class:`sage.structure.list_clone.ClonableElement`, which requires it.\n\n It should be overridden in subclasses in order to check that the\n characterizing property of the respective kind of tree holds (eg: two\n children for binary trees).\n\n EXAMPLES::\n\n sage: OrderedTree([[],[[]]]).check()\n sage: BinaryTree([[],[[],[]]]).check()\n ' pass def __setitem__(self, idx, value): '\n Substitute a subtree.\n\n .. NOTE::\n\n The tree ``self`` must be in a mutable state. See\n :mod:`sage.structure.list_clone` for more details about\n mutability. The default implementation here assume that the\n container of the node implement a method `_setitem` with signature\n `self._setitem(idx, value)`. It is usually provided by inheriting\n from :class:`~sage.structure.list_clone.ClonableArray`.\n\n INPUT:\n\n - ``idx`` -- a valid path in ``self`` identifying a node\n\n - ``value`` -- the tree to be substituted\n\n EXAMPLES:\n\n Trying to modify a non mutable tree raises an error::\n\n sage: x = OrderedTree([])\n sage: x[0] = OrderedTree([[]])\n Traceback (most recent call last):\n ...\n ValueError: object is immutable; please change a copy instead.\n\n Here is the correct way to do it::\n\n sage: x = OrderedTree([[],[[]]])\n sage: with x.clone() as x:\n ....: x[0] = OrderedTree([[]])\n sage: x\n [[[]], [[]]]\n\n One can also substitute at any depth::\n\n sage: y = OrderedTree(x)\n sage: with x.clone() as x:\n ....: x[0,0] = OrderedTree([[]])\n sage: x\n [[[[]]], [[]]]\n sage: y\n [[[]], [[]]]\n sage: with y.clone() as y:\n ....: y[(0,)] = OrderedTree([])\n sage: y\n [[], [[]]]\n\n This works for binary trees as well::\n\n sage: bt = BinaryTree([[],[[],[]]]); bt\n [[., .], [[., .], [., .]]]\n sage: with bt.clone() as bt1:\n ....: bt1[0,0] = BinaryTree([[[], []], None])\n sage: bt1\n [[[[[., .], [., .]], .], .], [[., .], [., .]]]\n\n TESTS::\n\n sage: x = OrderedTree([])\n sage: with x.clone() as x:\n ....: x[0] = OrderedTree([[]])\n Traceback (most recent call last):\n ...\n IndexError: list assignment index out of range\n\n sage: x = OrderedTree([]); x = OrderedTree([x,x]); x = OrderedTree([x,x]); x = OrderedTree([x,x])\n sage: with x.clone() as x:\n ....: x[0,0] = OrderedTree()\n sage: x\n [[[], [[], []]], [[[], []], [[], []]]]\n ' if (not isinstance(value, self.__class__)): raise TypeError('the given value is not a tree') if isinstance(idx, tuple): self.__setitem_rec__(idx, 0, value) else: self._setitem(idx, value) def __setitem_rec__(self, idx, i, value): '\n TESTS::\n\n sage: x = OrderedTree([[[], []],[[]]])\n sage: with x.clone() as x: # indirect doctest\n ....: x[0,1] = OrderedTree([[[]]])\n sage: x\n [[[], [[[]]]], [[]]]\n ' if (i == (len(idx) - 1)): self._setitem(idx[(- 1)], value) else: with self[idx[i]].clone() as child: child.__setitem_rec__(idx, (i + 1), value) self[idx[i]] = child def __getitem__(self, idx): '\n Return the ``idx``-th child of ``self`` (which is a subtree) if\n ``idx`` is an integer, or the ``idx[n-1]``-th child of the\n ``idx[n-2]``-th child of the ... of the ``idx[0]``-th child of\n ``self`` if ``idx`` is a list (or iterable) of length `n`.\n\n The indexing of the children is zero-based.\n\n INPUT:\n\n - ``idx`` -- an integer, or a valid path in ``self`` identifying a node\n\n .. NOTE::\n\n The default implementation here assumes that the container of the\n node inherits from\n :class:`~sage.structure.list_clone.ClonableArray`.\n\n EXAMPLES::\n\n sage: x = OrderedTree([[],[[]]])\n sage: x[1,0]\n []\n sage: x = OrderedTree([[],[[]]])\n sage: x[()]\n [[], [[]]]\n sage: x[(0,)]\n []\n sage: x[0,0]\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n\n sage: u = BinaryTree(None)\n sage: v = BinaryTree([u, u])\n sage: w = BinaryTree([u, v])\n sage: t = BinaryTree([v, w])\n sage: z = BinaryTree([w, t])\n sage: z[0,1]\n [., .]\n sage: z[0,0]\n .\n sage: z[1]\n [[., .], [., [., .]]]\n sage: z[1,1]\n [., [., .]]\n sage: z[1][1,1]\n [., .]\n ' if isinstance(idx, slice): return ClonableArray.__getitem__(self, idx) try: i = int(idx) except TypeError: res = self for i in idx: res = ClonableArray._getitem(res, i) return res else: return ClonableArray._getitem(self, i)
class AbstractLabelledTree(AbstractTree): '\n Abstract Labelled Tree.\n\n Typically a class for labelled trees is constructed by inheriting from\n a class for unlabelled trees and :class:`AbstractLabelledTree`.\n\n .. rubric:: How should this class be extended ?\n\n A class extending :class:`AbstractLabelledTree\n <sage.combinat.abstract_tree.AbstractLabelledTree>` should respect the\n following assumptions:\n\n * For a labelled tree ``T`` the call ``T.parent().unlabelled_trees()``\n should return a parent for unlabelled trees of the same kind: for\n example,\n\n - if ``T`` is a binary labelled tree, ``T.parent()`` is\n ``LabelledBinaryTrees()`` and ``T.parent().unlabelled_trees()`` is\n ``BinaryTrees()``\n\n - if ``T`` is an ordered labelled tree, ``T.parent()`` is\n ``LabelledOrderedTrees()`` and ``T.parent().unlabelled_trees()`` is\n ``OrderedTrees()``\n\n * In the same vein, the class of ``T`` should contain an attribute\n ``_UnLabelled`` which should be the class for the corresponding\n unlabelled trees.\n\n See also the assumptions in :class:`AbstractTree`.\n\n .. SEEALSO:: :class:`AbstractTree`\n ' def __init__(self, parent, children, label=None, check=True): '\n TESTS::\n\n sage: LabelledOrderedTree([])\n None[]\n sage: LabelledOrderedTree([], 3)\n 3[]\n sage: LT = LabelledOrderedTree\n sage: t = LT([LT([LT([], label=42), LT([], 21)])], label=1)\n sage: t\n 1[None[42[], 21[]]]\n sage: LabelledOrderedTree(OrderedTree([[],[[],[]],[]]))\n None[None[], None[None[], None[]], None[]]\n\n We test that inheriting from `LabelledOrderedTree` allows construction from a\n `LabelledOrderedTree` (:trac:`16314`)::\n\n sage: LBTS = LabelledOrderedTrees()\n sage: class Foo(LabelledOrderedTree):\n ....: def bar(self):\n ....: print("bar called")\n sage: foo = Foo(LBTS, [], label=1); foo\n 1[]\n sage: foo1 = LBTS([LBTS([], label=21)], label=42); foo1\n 42[21[]]\n sage: foo2 = Foo(LBTS, foo1); foo2\n 42[21[]]\n sage: foo2[0]\n 21[]\n sage: foo2.__class__\n <class \'__main__.Foo\'>\n sage: foo2[0].__class__\n <class \'__main__.Foo\'>\n sage: foo2.bar()\n bar called\n sage: foo2.label()\n 42\n ' if isinstance(children, AbstractLabelledTree): if (label is None): self._label = children._label else: self._label = label else: self._label = label super().__init__(parent, children, check=check) def _repr_(self): '\n Return the string representation of ``self``.\n\n TESTS::\n\n sage: LabelledOrderedTree([]) # indirect doctest\n None[]\n sage: LabelledOrderedTree([], label=3) # indirect doctest\n 3[]\n sage: LabelledOrderedTree([[],[[]]]) # indirect doctest\n None[None[], None[None[]]]\n sage: LabelledOrderedTree([[],LabelledOrderedTree([[]], label=2)], label=3)\n 3[None[], 2[None[]]]\n ' return ('%s%s' % (self._label, self[:])) def label(self, path=None): '\n Return the label of ``self``.\n\n INPUT:\n\n - ``path`` -- ``None`` (default) or a path (list or tuple of\n children index in the tree)\n\n OUTPUT: the label of the subtree indexed by ``path``\n\n EXAMPLES::\n\n sage: t = LabelledOrderedTree([[],[]], label = 3)\n sage: t.label()\n 3\n sage: t[0].label()\n sage: t = LabelledOrderedTree([LabelledOrderedTree([], 5),[]], label = 3)\n sage: t.label()\n 3\n sage: t[0].label()\n 5\n sage: t[1].label()\n sage: t.label([0])\n 5\n ' if (path is None): return self._label else: tr = self for i in path: tr = tr[i] return tr._label def labels(self): "\n Return the list of labels of ``self``.\n\n EXAMPLES::\n\n sage: LT = LabelledOrderedTree\n sage: t = LT([LT([],label='b'),LT([],label='c')],label='a')\n sage: t.labels()\n ['a', 'b', 'c']\n\n sage: LBT = LabelledBinaryTree\n sage: LBT([LBT([],label=1),LBT([],label=4)],label=2).labels()\n [2, 1, 4]\n " return [t.label() for t in self.subtrees()] def leaf_labels(self): '\n Return the list of labels of the leaves of ``self``.\n\n In case of a labelled binary tree, these "leaves" are not actually\n the leaves of the binary trees, but the nodes whose both children\n are leaves!\n\n EXAMPLES::\n\n sage: LT = LabelledOrderedTree\n sage: t = LT([LT([],label=\'b\'),LT([],label=\'c\')],label=\'a\')\n sage: t.leaf_labels()\n [\'b\', \'c\']\n\n sage: LBT = LabelledBinaryTree\n sage: bt = LBT([LBT([],label=\'b\'),LBT([],label=\'c\')],label=\'a\')\n sage: bt.leaf_labels()\n [\'b\', \'c\']\n sage: LBT([], label=\'1\').leaf_labels()\n [\'1\']\n sage: LBT(None).leaf_labels()\n []\n ' return [t.label() for t in self.subtrees() if (t.node_number() == 1)] def __eq__(self, other): '\n Test if ``self`` is equal to ``other``\n\n TESTS::\n\n sage LabelledOrderedTree() == LabelledOrderedTree()\n True\n sage LabelledOrderedTree([]) == LabelledOrderedTree()\n False\n sage: t1 = LabelledOrderedTree([[],[[]]])\n sage: t2 = LabelledOrderedTree([[],[[]]])\n sage: t1 == t2\n True\n sage: t2 = LabelledOrderedTree(t1)\n sage: t1 == t2\n True\n sage: t1 = LabelledOrderedTree([[],[[]]])\n sage: t2 = LabelledOrderedTree([[[]],[]])\n sage: t1 == t2\n False\n ' return (super().__eq__(other) and (self._label == other._label)) def _hash_(self): '\n Return the hash value for ``self``\n\n TESTS::\n\n sage: t1 = LabelledOrderedTree([[],[[]]], label = 1); t1hash = t1.__hash__()\n sage: LabelledOrderedTree([[],[[]]], label = 1).__hash__() == t1hash\n True\n sage: LabelledOrderedTree([[[]],[]], label = 1).__hash__() == t1hash\n False\n sage: LabelledOrderedTree(t1, label = 1).__hash__() == t1hash\n True\n sage: LabelledOrderedTree([[],[[]]], label = 25).__hash__() == t1hash\n False\n sage: LabelledOrderedTree(t1, label = 25).__hash__() == t1hash\n False\n\n sage: LabelledBinaryTree([[],[[],[]]], label = 25).__hash__() #random\n 8544617749928727644\n\n We check that the hash value depends on the value of the labels of the\n subtrees::\n\n sage: LBT = LabelledBinaryTree\n sage: t1 = LBT([], label = 1)\n sage: t2 = LBT([], label = 2)\n sage: t3 = LBT([], label = 3)\n sage: t12 = LBT([t1, t2], label = "a")\n sage: t13 = LBT([t1, t3], label = "a")\n sage: t12.__hash__() != t13.__hash__()\n True\n ' return (self._UnLabelled._hash_(self) ^ hash(self._label)) def shape(self): "\n Return the unlabelled tree associated to ``self``.\n\n EXAMPLES::\n\n sage: t = LabelledOrderedTree([[],[[]]], label = 25).shape(); t\n [[], [[]]]\n\n sage: LabelledBinaryTree([[],[[],[]]], label = 25).shape()\n [[., .], [[., .], [., .]]]\n\n sage: LRT = LabelledRootedTree\n sage: tb = LRT([],label='b')\n sage: LRT([tb, tb], label='a').shape()\n [[], []]\n\n TESTS::\n\n sage: t.parent()\n Ordered trees\n sage: type(t)\n <class 'sage.combinat.ordered_tree.OrderedTrees_all_with_category.element_class'>\n " TR = self.parent().unlabelled_trees() if (not self): return TR.leaf() else: return TR._element_constructor_([i.shape() for i in self]) def as_digraph(self): '\n Return a directed graph version of ``self``.\n\n .. WARNING::\n\n At this time, the output makes sense only if ``self`` is a\n labelled binary tree with no repeated labels and no ``None``\n labels.\n\n EXAMPLES::\n\n sage: LT = LabelledOrderedTrees()\n sage: t1 = LT([LT([],label=6),LT([],label=1)],label=9)\n sage: t1.as_digraph()\n Digraph on 3 vertices\n\n sage: t = BinaryTree([[None, None],[[],None]])\n sage: lt = t.canonical_labelling()\n sage: lt.as_digraph()\n Digraph on 4 vertices\n ' from sage.graphs.digraph import DiGraph resu = {self.label(): [t.label() for t in self if (not t.is_empty())]} resu = DiGraph(resu, format='dict_of_lists') for t in self: if (not t.is_empty()): resu = resu.union(t.as_digraph()) return resu
class AbstractLabelledClonableTree(AbstractLabelledTree, AbstractClonableTree): '\n Abstract Labelled Clonable Tree\n\n This class takes care of modification for the label by the clone protocol.\n\n .. NOTE:: Due to the limitation of Cython inheritance, one cannot inherit\n here from :class:`~sage.structure.list_clone.ClonableArray`, because it would prevent us to\n inherit later from :class:`~sage.structure.list_clone.ClonableList`.\n ' def set_root_label(self, label): '\n Set the label of the root of ``self``.\n\n INPUT: ``label`` -- any Sage object\n\n OUTPUT: ``None``, ``self`` is modified in place\n\n .. NOTE::\n\n ``self`` must be in a mutable state. See\n :mod:`sage.structure.list_clone` for more details about\n mutability.\n\n EXAMPLES::\n\n sage: t = LabelledOrderedTree([[],[[],[]]])\n sage: t.set_root_label(3)\n Traceback (most recent call last):\n ...\n ValueError: object is immutable; please change a copy instead.\n sage: with t.clone() as t:\n ....: t.set_root_label(3)\n sage: t.label()\n 3\n sage: t\n 3[None[], None[None[], None[]]]\n\n This also works for binary trees::\n\n sage: bt = LabelledBinaryTree([[],[]])\n sage: bt.set_root_label(3)\n Traceback (most recent call last):\n ...\n ValueError: object is immutable; please change a copy instead.\n sage: with bt.clone() as bt:\n ....: bt.set_root_label(3)\n sage: bt.label()\n 3\n sage: bt\n 3[None[., .], None[., .]]\n\n TESTS::\n\n sage: with t.clone() as t:\n ....: t[0] = LabelledOrderedTree(t[0], label = 4)\n sage: t\n 3[4[], None[None[], None[]]]\n sage: with t.clone() as t:\n ....: t[1,0] = LabelledOrderedTree(t[1,0], label = 42)\n sage: t\n 3[4[], None[42[], None[]]]\n ' self._require_mutable() self._label = label def set_label(self, path, label): '\n Change the label of subtree indexed by ``path`` to ``label``.\n\n INPUT:\n\n - ``path`` -- ``None`` (default) or a path (list or tuple of children\n index in the tree)\n\n - ``label`` -- any sage object\n\n OUTPUT: Nothing, ``self`` is modified in place\n\n .. NOTE::\n\n ``self`` must be in a mutable state. See\n :mod:`sage.structure.list_clone` for more details about\n mutability.\n\n EXAMPLES::\n\n sage: t = LabelledOrderedTree([[],[[],[]]])\n sage: t.set_label((0,), 4)\n Traceback (most recent call last):\n ...\n ValueError: object is immutable; please change a copy instead.\n sage: with t.clone() as t:\n ....: t.set_label((0,), 4)\n sage: t\n None[4[], None[None[], None[]]]\n sage: with t.clone() as t:\n ....: t.set_label((1,0), label = 42)\n sage: t\n None[4[], None[42[], None[]]]\n\n .. TODO::\n\n Do we want to implement the following syntactic sugar::\n\n with t.clone() as tt:\n tt.labels[1,2] = 3 ?\n ' self._require_mutable() path = tuple(path) if (path == ()): self._label = label else: with self[path[0]].clone() as child: child.set_label(path[1:], label) self[path[0]] = child def map_labels(self, f): '\n Apply the function `f` to the labels of ``self``\n\n This method returns a copy of ``self`` on which the function `f` has\n been applied on all labels (a label `x` is replaced by `f(x)`).\n\n EXAMPLES::\n\n sage: LT = LabelledOrderedTree\n sage: t = LT([LT([],label=1),LT([],label=7)],label=3); t\n 3[1[], 7[]]\n sage: t.map_labels(lambda z:z+1)\n 4[2[], 8[]]\n\n sage: LBT = LabelledBinaryTree\n sage: bt = LBT([LBT([],label=1),LBT([],label=4)],label=2); bt\n 2[1[., .], 4[., .]]\n sage: bt.map_labels(lambda z:z+1)\n 3[2[., .], 5[., .]]\n ' if self.is_empty(): return self return self.parent()([t.map_labels(f) for t in self], label=f(self.label()))
def from_hexacode(ch, parent=None, label='@'): "\n Transform a hexadecimal string into a tree.\n\n INPUT:\n\n - ``ch`` -- a hexadecimal string\n\n - ``parent`` -- kind of trees to be produced. If ``None``, this will\n be ``LabelledOrderedTrees``\n\n - ``label`` -- a label (default: ``'@'``) to be used for every vertex\n of the tree\n\n See :meth:`AbstractTree.to_hexacode` for the description of the encoding\n\n See :func:`_from_hexacode_aux` for the actual code\n\n EXAMPLES::\n\n sage: from sage.combinat.abstract_tree import from_hexacode\n sage: from_hexacode('12000', LabelledOrderedTrees())\n @[@[@[], @[]]]\n sage: from_hexacode('12000')\n @[@[@[], @[]]]\n\n sage: from_hexacode('1200', LabelledOrderedTrees())\n @[@[@[], @[]]]\n\n It can happen that only a prefix of the word is used::\n\n sage: from_hexacode('a'+14*'0', LabelledOrderedTrees())\n @[@[], @[], @[], @[], @[], @[], @[], @[], @[], @[]]\n\n One can choose the label::\n\n sage: from_hexacode('1200', LabelledOrderedTrees(), label='o')\n o[o[o[], o[]]]\n\n One can also create other kinds of trees::\n\n sage: from_hexacode('1200', OrderedTrees())\n [[[], []]]\n " if (parent is None): from sage.combinat.ordered_tree import LabelledOrderedTrees parent = LabelledOrderedTrees() return _from_hexacode_aux(ch, parent, label)[0]
def _from_hexacode_aux(ch, parent, label='@'): "\n Transform a hexadecimal string into a tree and a remainder string.\n\n INPUT:\n\n - ``ch`` -- a hexadecimal string\n\n - ``parent`` -- kind of trees to be produced.\n\n - ``label`` -- a label (default: ``'@'``) to be used for every vertex\n of the tree\n\n This method is used in :func:`from_hexacode`\n\n EXAMPLES::\n\n sage: from sage.combinat.abstract_tree import _from_hexacode_aux\n sage: _from_hexacode_aux('12000', LabelledOrderedTrees())\n (@[@[@[], @[]]], '0')\n\n sage: _from_hexacode_aux('1200', LabelledOrderedTrees())\n (@[@[@[], @[]]], '')\n\n sage: _from_hexacode_aux('1200', OrderedTrees())\n ([[[], []]], '')\n\n sage: _from_hexacode_aux('a00000000000000', LabelledOrderedTrees())\n (@[@[], @[], @[], @[], @[], @[], @[], @[], @[], @[]], '0000')\n " Trees = parent width = int(ch[0], 16) remainder = ch[1:] if (width == 0): return (Trees([], label), remainder) branches = {} for i in range(width): (tree, remainder) = _from_hexacode_aux(remainder, parent, label) branches[i] = tree return (Trees(branches.values(), label), remainder)
class AffinePermutation(ClonableArray): "\n An affine permutation, represented in the window notation, and\n considered as a bijection from `\\ZZ` to `\\ZZ`.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p = A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p\n Type A affine permutation with window [3, -1, 0, 6, 5, 4, 10, 9]\n " def __init__(self, parent, lst, check=True): "\n Initialize ``self``\n\n INPUT:\n\n - ``parent`` -- the parent affine permutation group\n\n - ``lst`` -- list giving the base window of the affine permutation\n\n - ``check``-- whether to test if the affine permutation is valid\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p = A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p\n Type A affine permutation with window [3, -1, 0, 6, 5, 4, 10, 9]\n sage: TestSuite(p).run()\n\n TESTS:\n\n Check that :trac:`26436` is fixed::\n\n sage: A = AffinePermutationGroup(['A',3,1])\n sage: p = A([-3/1,2/1,3/1,8/1])\n sage: q = ~p\n sage: q * p\n Type A affine permutation with window [1, 2, 3, 4]\n " if check: lst = [ZZ(val) for val in lst] self.k = parent.k self.n = (self.k + 1) if (parent.cartan_type()[0] == 'A'): self.N = self.n elif (parent.cartan_type()[0] in ['B', 'C', 'D']): self.N = ((2 * self.k) + 1) elif (parent.cartan_type()[0] == 'G'): self.N = 6 else: raise NotImplementedError('unsupported Cartan type') ClonableArray.__init__(self, parent, lst, check) def _repr_(self): "\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p = A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p\n Type A affine permutation with window [3, -1, 0, 6, 5, 4, 10, 9]\n " return ((('Type ' + self.parent().cartan_type().letter) + ' affine permutation with window ') + str(list(self))) def __rmul__(self, q): "\n Given ``self`` and `q`, returns ``self*q``.\n\n INPUT:\n\n - ``q`` -- an element of ``self.parent()``\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p = A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: q = A([0, 2, 3, 4, 5, 6, 7, 9])\n sage: p.__rmul__(q)\n Type A affine permutation with window [1, -1, 0, 6, 5, 4, 10, 11]\n " l = [self.value(q.value(i)) for i in range(1, (len(self) + 1))] return type(self)(self.parent(), l, check=False) def __lmul__(self, q): "\n Given ``self`` and `q`, returns ``q*self``.\n\n INPUT:\n\n - ``q`` -- an element of ``self.parent()``\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p = A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: q = A([0,2,3,4,5,6,7,9])\n sage: p.__lmul__(q)\n Type A affine permutation with window [3, -1, 1, 6, 5, 4, 10, 8]\n " l = [q.value(self.value(i)) for i in range(1, (len(self) + 1))] return type(self)(self.parent(), l, check=False) def __mul__(self, q): "\n Given ``self`` and `q`, returns ``self*q``.\n\n INPUT:\n\n - ``q`` -- An element of ``self.parent()``\n\n EXAMPLES::\n\n sage: p = AffinePermutationGroup(['A',7,1])([3, -1, 0, 6, 5, 4, 10, 9])\n sage: s1 = AffinePermutationGroup(['A',7,1]).one().apply_simple_reflection(1)\n sage: p * s1\n Type A affine permutation with window [-1, 3, 0, 6, 5, 4, 10, 9]\n sage: p.apply_simple_reflection(1, 'right')\n Type A affine permutation with window [-1, 3, 0, 6, 5, 4, 10, 9]\n\n " return self.__rmul__(q) @cached_method def __invert__(self): "\n Return the inverse affine permutation.\n\n EXAMPLES::\n\n sage: p = AffinePermutationGroup(['A',7,1])([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.inverse() # indirect doctest\n Type A affine permutation with window [0, -1, 1, 6, 5, 4, 10, 11]\n " inv = [self.position(i) for i in range(1, (len(self) + 1))] return type(self)(self.parent(), inv, check=False) def apply_simple_reflection(self, i, side='right'): "\n Apply a simple reflection.\n\n INPUT:\n\n - ``i`` -- an integer\n - ``side`` -- (default: ``'right'``) determines whether to apply the\n reflection on the ``'right'`` or ``'left'``\n\n EXAMPLES::\n\n sage: p = AffinePermutationGroup(['A',7,1])([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.apply_simple_reflection(3)\n Type A affine permutation with window [3, -1, 6, 0, 5, 4, 10, 9]\n sage: p.apply_simple_reflection(11)\n Type A affine permutation with window [3, -1, 6, 0, 5, 4, 10, 9]\n sage: p.apply_simple_reflection(3, 'left')\n Type A affine permutation with window [4, -1, 0, 6, 5, 3, 10, 9]\n sage: p.apply_simple_reflection(11, 'left')\n Type A affine permutation with window [4, -1, 0, 6, 5, 3, 10, 9]\n " if (side == 'right'): return self.apply_simple_reflection_right(i) if (side == 'left'): return self.apply_simple_reflection_left(i) def __call__(self, i): "\n Return the image of the integer ``i`` under this permutation.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.value(1) #indirect doctest\n 3\n sage: p.value(9)\n 11\n " return self.value(i) def is_i_grassmannian(self, i=0, side='right') -> bool: "\n Test whether ``self`` is `i`-grassmannian, i.e., either is the\n identity or has ``i`` as the sole descent.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n - ``side`` -- determines the side on which to check the descents\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.is_i_grassmannian()\n False\n sage: q=A.from_word([3,2,1,0])\n sage: q.is_i_grassmannian()\n True\n sage: q=A.from_word([2,3,4,5])\n sage: q.is_i_grassmannian(5)\n True\n sage: q.is_i_grassmannian(2, side='left')\n True\n " return ((self == self.parent().one()) or (self.descents(side) == [i])) def index_set(self): "\n Index set of the affine permutation group.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: A.index_set()\n (0, 1, 2, 3, 4, 5, 6, 7)\n " return tuple(range((self.k + 1))) def lower_covers(self, side='right'): "\n Return lower covers of ``self``.\n\n The set of affine permutations of one less length related by\n multiplication by a simple transposition on the indicated side.\n These are the elements that ``self`` covers in weak order.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.lower_covers()\n [Type A affine permutation with window [-1, 3, 0, 6, 5, 4, 10, 9],\n Type A affine permutation with window [3, -1, 0, 5, 6, 4, 10, 9],\n Type A affine permutation with window [3, -1, 0, 6, 4, 5, 10, 9],\n Type A affine permutation with window [3, -1, 0, 6, 5, 4, 9, 10]]\n " S = self.descents(side) return [self.apply_simple_reflection(i, side) for i in S] def is_one(self) -> bool: "\n Tests whether the affine permutation is the identity.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.is_one()\n False\n sage: q=A.one()\n sage: q.is_one()\n True\n " return (self == self.parent().one()) def reduced_word(self): "\n Returns a reduced word for the affine permutation.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.reduced_word()\n [0, 7, 4, 1, 0, 7, 5, 4, 2, 1]\n " x = self i = 0 word = [] while (not x.is_one()): if x.has_descent(i): x = x.apply_simple_reflection_right(i) word.append(i) i = ((i + 1) % (self.k + 1)) word.reverse() return word def signature(self): "\n Signature of the affine permutation, `(-1)^l`, where `l` is the\n length of the permutation.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.signature()\n 1\n " return ((- 1) ** self.length()) @cached_method def to_weyl_group_element(self): "\n The affine Weyl group element corresponding to the affine permutation.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.to_weyl_group_element()\n [ 0 -1 0 1 0 0 1 0]\n [ 1 -1 0 1 0 0 1 -1]\n [ 1 -1 0 1 0 0 0 0]\n [ 0 0 0 1 0 0 0 0]\n [ 0 0 0 1 0 -1 1 0]\n [ 0 0 0 1 -1 0 1 0]\n [ 0 0 0 0 0 0 1 0]\n [ 0 -1 1 0 0 0 1 0]\n " W = self.parent().weyl_group() return W.from_reduced_word(self.reduced_word()) def grassmannian_quotient(self, i=0, side='right'): "\n Return the Grassmannian quotient.\n\n Factors ``self`` into a unique product of a Grassmannian and a\n finite-type element. Returns a tuple containing the Grassmannian\n and finite elements, in order according to ``side``.\n\n INPUT:\n\n - ``i`` -- (default: 0) an element of the index set; the descent\n checked for\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: gq=p.grassmannian_quotient()\n sage: gq\n (Type A affine permutation with window [-1, 0, 3, 4, 5, 6, 9, 10],\n Type A affine permutation with window [3, 1, 2, 6, 5, 4, 8, 7])\n sage: gq[0].is_i_grassmannian()\n True\n sage: 0 not in gq[1].reduced_word()\n True\n sage: prod(gq)==p\n True\n\n sage: gqLeft=p.grassmannian_quotient(side='left')\n sage: 0 not in gqLeft[0].reduced_word()\n True\n sage: gqLeft[1].is_i_grassmannian(side='left')\n True\n sage: prod(gqLeft)==p\n True\n " fin = self.parent().one() gr = self D = gr.descents(side=side) while (not ((D == [i]) or (D == []))): m = D[0] if (m == i): m = D[1] if (side == 'right'): fin = fin.apply_simple_reflection(m, side='left') gr = gr.apply_simple_reflection(m, side='right') else: fin = fin.apply_simple_reflection(m, side='right') gr = gr.apply_simple_reflection(m, side='left') D = gr.descents(side=side) if (side == 'right'): return (gr, fin) else: return (fin, gr)
class AffinePermutationTypeA(AffinePermutation): def check(self): "\n Check that ``self`` is an affine permutation.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p = A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p\n Type A affine permutation with window [3, -1, 0, 6, 5, 4, 10, 9]\n sage: q = A([1,2,3]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: length of list must be k+1=8\n sage: q = A([1,2,3,4,5,6,7,0]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: window does not sum to 36\n sage: q = A([1,1,3,4,5,6,7,9]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: entries must have distinct residues\n " if (not self): return k = self.parent().k if (len(self) != (k + 1)): raise ValueError(('length of list must be k+1=' + str((k + 1)))) if (binomial((k + 2), 2) != sum(self)): raise ValueError(('window does not sum to ' + str(binomial((k + 2), 2)))) l = sorted([(i % (k + 1)) for i in self]) if (l != list(range((k + 1)))): raise ValueError('entries must have distinct residues') def value(self, i, base_window=False): "\n Return the image of the integer ``i`` under this permutation.\n\n INPUT:\n\n - ``base_window`` -- boolean; indicating whether ``i`` is in the\n base window; if ``True``, will run a bit faster, but the method\n will screw up if ``i`` is not actually in the index set\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p = A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.value(1)\n 3\n sage: p.value(9)\n 11\n " if base_window: self[(i - 1)] window = ((i - 1) // (self.k + 1)) return (self[((i - 1) % (self.k + 1))] + (window * (self.k + 1))) def position(self, i): "\n Find the position ``j`` such the ``self.value(j) == i``.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p = A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.position(3)\n 1\n sage: p.position(11)\n 9\n " for r in range((self.k + 1)): if ((self[r] % (self.k + 1)) == (i % (self.k + 1))): diff = ((i - self[r]) // (self.k + 1)) return ((r + (diff * (self.k + 1))) + 1) return False def apply_simple_reflection_right(self, i): "\n Apply the simple reflection to positions `i`, `i+1`.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: p = AffinePermutationGroup(['A',7,1])([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.apply_simple_reflection_right(3)\n Type A affine permutation with window [3, -1, 6, 0, 5, 4, 10, 9]\n sage: p.apply_simple_reflection_right(11)\n Type A affine permutation with window [3, -1, 6, 0, 5, 4, 10, 9]\n " j = (i % (self.k + 1)) l = self[:] if (j == 0): a = l[0] l[0] = (l[(- 1)] - (self.k + 1)) l[(- 1)] = (a + (self.k + 1)) else: a = l[(j - 1)] l[(j - 1)] = l[j] l[j] = a return type(self)(self.parent(), l, check=False) def apply_simple_reflection_left(self, i): "\n Apply the simple reflection to the values `i`, `i+1`.\n\n EXAMPLES::\n\n sage: p = AffinePermutationGroup(['A',7,1])([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.apply_simple_reflection_left(3)\n Type A affine permutation with window [4, -1, 0, 6, 5, 3, 10, 9]\n sage: p.apply_simple_reflection_left(11)\n Type A affine permutation with window [4, -1, 0, 6, 5, 3, 10, 9]\n " i = (i % (self.k + 1)) l = [] if (i != self.k): for m in range((self.k + 1)): res = (self[m] % (self.k + 1)) if (res == i): l.append((self[m] + 1)) elif (res == (i + 1)): l.append((self[m] - 1)) else: l.append(self[m]) if (i == self.k): for m in range((self.k + 1)): res = (self[m] % (self.k + 1)) if (res == i): l.append((self[m] + 1)) elif (res == 0): l.append((self[m] - 1)) else: l.append(self[m]) return type(self)(self.parent(), l, check=False) def has_right_descent(self, i) -> bool: "\n Determine whether there is a descent at ``i``.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: p = AffinePermutationGroup(['A',7,1])([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.has_right_descent(1)\n True\n sage: p.has_right_descent(9)\n True\n sage: p.has_right_descent(0)\n False\n " return (self.value(i) > self.value((i + 1))) def has_left_descent(self, i) -> bool: "\n Determine whether there is a descent at ``i``.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: p = AffinePermutationGroup(['A',7,1])([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.has_left_descent(1)\n True\n sage: p.has_left_descent(9)\n True\n sage: p.has_left_descent(0)\n True\n " return (self.position(i) > self.position((i + 1))) def to_type_a(self): "\n Return an embedding of ``self`` into the affine permutation group of\n type `A`. (For type `A`, just returns ``self``.)\n\n EXAMPLES::\n\n sage: p = AffinePermutationGroup(['A',7,1])([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.to_type_a() is p\n True\n " return self def flip_automorphism(self): "\n The Dynkin diagram automorphism which fixes `s_0` and reverses all\n other indices.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.flip_automorphism()\n Type A affine permutation with window [0, -1, 5, 4, 3, 9, 10, 6]\n " w = [(((self.k + 1) - i) % (self.k + 1)) for i in self.reduced_word()] return self.parent().from_word(w) def promotion(self): "\n The Dynkin diagram automorphism which sends `s_i` to `s_{i+1}`.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.promotion()\n Type A affine permutation with window [2, 4, 0, 1, 7, 6, 5, 11]\n " l = [] l.append((self[(- 1)] - self.k)) for i in range(1, (self.k + 1)): l.append((self[(i - 1)] + 1)) return type(self)(self.parent(), l) def maximal_cyclic_factor(self, typ='decreasing', side='right', verbose=False): "\n For an affine permutation `x`, find the unique maximal subset `A`\n of the index set such that `x = yd_A` is a reduced product.\n\n INPUT:\n\n - ``typ`` -- ``'increasing'`` or ``'decreasing'``\n (default: ``'decreasing'``); chooses whether to find increasing\n or decreasing sets\n\n - ``side`` -- ``'right'`` or ``'left'`` (default: ``'right'``) chooses\n whether to find maximal sets starting from the left or the right\n\n - ``verbose`` -- True or False. If True, outputs information about how\n the cyclically increasing element was found.\n\n EXAMPLES::\n\n sage: p = AffinePermutationGroup(['A',7,1])([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.maximal_cyclic_factor()\n [7, 5, 4, 2, 1]\n sage: p.maximal_cyclic_factor(side='left')\n [1, 0, 7, 5, 4]\n sage: p.maximal_cyclic_factor('increasing','right')\n [4, 5, 7, 0, 1]\n sage: p.maximal_cyclic_factor('increasing','left')\n [0, 1, 2, 4, 5]\n " k = self.k if (side[0] == 'r'): descents = self.descents(side='right') side = 'right' else: descents = self.descents(side='left') side = 'left' best_T = [] for i in descents: y = self.clone().apply_simple_reflection(i, side) T = [i] j = i for _ in range(1, self.k): if ((typ[0], side[0]) == ('d', 'r')): j = ((j + 1) % (k + 1)) if ((typ[0], side[0]) == ('i', 'r')): j = ((j - 1) % (k + 1)) if ((typ[0], side[0]) == ('d', 'l')): j = ((j - 1) % (k + 1)) if ((typ[0], side[0]) == ('i', 'l')): j = ((j + 1) % (k + 1)) if y.has_descent(j, side): y = y.apply_simple_reflection(j, side) T.append((j % (k + 1))) if verbose: print(i, T) if (len(T) > len(best_T)): best_T = T if (side[0] == 'r'): best_T.reverse() return best_T def maximal_cyclic_decomposition(self, typ='decreasing', side='right', verbose=False): "\n Find the unique maximal decomposition of ``self`` into cyclically\n decreasing/increasing elements.\n\n INPUT:\n\n - ``typ`` -- ``'increasing'`` or ``'decreasing'``\n (default: ``'decreasing'``); chooses whether to find increasing\n or decreasing sets\n\n - ``side`` -- ``'right'`` or ``'left'`` (default: ``'right'``) chooses\n whether to find maximal sets starting from the left or the right\n\n - ``verbose`` -- (default: ``False``) print extra information while\n finding the decomposition\n\n EXAMPLES::\n\n sage: p = AffinePermutationGroup(['A',7,1])([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.maximal_cyclic_decomposition()\n [[0, 7], [4, 1, 0], [7, 5, 4, 2, 1]]\n sage: p.maximal_cyclic_decomposition(side='left')\n [[1, 0, 7, 5, 4], [1, 0, 5], [2, 1]]\n sage: p.maximal_cyclic_decomposition(typ='increasing', side='right')\n [[1], [5, 0, 1, 2], [4, 5, 7, 0, 1]]\n sage: p.maximal_cyclic_decomposition(typ='increasing', side='left')\n [[0, 1, 2, 4, 5], [4, 7, 0, 1], [7]]\n\n TESTS::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: S=p.maximal_cyclic_decomposition()\n sage: p==prod(A.from_word(l) for l in S)\n True\n sage: S=p.maximal_cyclic_decomposition(typ='increasing', side='left')\n sage: p==prod(A.from_word(l) for l in S)\n True\n sage: S=p.maximal_cyclic_decomposition(typ='increasing', side='right')\n sage: p==prod(A.from_word(l) for l in S)\n True\n sage: S=p.maximal_cyclic_decomposition(typ='decreasing', side='right')\n sage: p==prod(A.from_word(l) for l in S)\n True\n " y = self.clone() listy = [] if verbose: print('length of x:', self.length()) while (not y.is_one()): S = y.maximal_cyclic_factor(typ, side, verbose) listy.append(S[:]) if (side[0] == 'r'): S.reverse() for i in S: if (side[0] == 'r'): y = y.apply_simple_reflection_right(i) else: y = y.apply_simple_reflection_left(i) if verbose: print(S, y.length()) if (side[0] == 'r'): listy.reverse() return listy def to_lehmer_code(self, typ='decreasing', side='right'): "\n Return the affine Lehmer code.\n\n There are four such codes; the options ``typ`` and ``side`` determine\n which code is generated. The codes generated are the shape of the\n maximal cyclic decompositions of ``self`` according to the given\n ``typ`` and ``side`` options.\n\n INPUT:\n\n - ``typ`` -- ``'increasing'`` or ``'decreasing'``\n (default: ``'decreasing'``); chooses whether to find increasing\n or decreasing sets\n\n - ``side`` -- ``'right'`` or ``'left'`` (default: ``'right'``) chooses\n whether to find maximal sets starting from the left or the right\n\n EXAMPLES::\n\n sage: import itertools\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: orders = ('increasing','decreasing')\n sage: sides = ('left','right')\n sage: for o,s in itertools.product(orders, sides):\n ....: p.to_lehmer_code(o,s)\n [2, 3, 2, 0, 1, 2, 0, 0]\n [2, 2, 0, 0, 2, 1, 0, 3]\n [3, 1, 0, 0, 2, 1, 0, 3]\n [0, 3, 3, 0, 1, 2, 0, 1]\n sage: for a in itertools.product(orders, sides):\n ....: A.from_lehmer_code(p.to_lehmer_code(a[0],a[1]), a[0],a[1])==p\n True\n True\n True\n True\n " code = [0 for i in range((self.k + 1))] if ((typ[0] == 'i') and (side[0] == 'r')): for i in range((self.k + 1)): a = self(i) for j in range((i + 1), ((i + self.k) + 1)): b = self(j) if (b < a): code[i] += (((a - b) // (self.k + 1)) + 1) elif ((typ[0] == 'd') and (side[0] == 'r')): for i in range((self.k + 1)): a = self(i) for j in range((i - self.k), i): b = self(j) if (a < b): code[(i - 1)] += (((b - a) // (self.k + 1)) + 1) elif ((typ[0] == 'i') and (side[0] == 'l')): for i in range((self.k + 1)): pos = self.position(i) for j in range((pos + 1), ((pos + self.k) + 1)): b = self(j) if (b < i): code[(i - 1)] += (((i - b) // (self.k + 1)) + 1) elif ((typ[0] == 'd') and (side[0] == 'l')): for i in range((self.k + 1)): pos = self.position(i) for j in range((pos - self.k), pos): b = self(j) if (b > i): code[i] += (((b - i) // (self.k + 1)) + 1) return Composition(code) def is_fully_commutative(self) -> bool: "\n Determine whether ``self`` is fully commutative.\n\n This means that it has no reduced word with a braid.\n\n This uses a specific algorithm.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p = A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.is_fully_commutative()\n False\n sage: q = A([-3, -2, 0, 7, 9, 2, 11, 12])\n sage: q.is_fully_commutative()\n True\n " if (self == self.parent().one()): return True c = self.to_lehmer_code() firstnonzero = None m = (- 1) for i in range(self.n): if (c[i] > 0): if (firstnonzero is None): firstnonzero = i if ((m != (- 1)) and ((c[i] - (i - m)) >= c[m])): return False m = i d = (self.n - (m - firstnonzero)) return (not ((c[firstnonzero] - d) >= c[m])) def to_bounded_partition(self, typ='decreasing', side='right'): "\n Return the `k`-bounded partition associated to the dominant element\n obtained by sorting the Lehmer code.\n\n INPUT:\n\n - ``typ`` -- ``'increasing'`` or ``'decreasing'`` (default: ``'decreasing'``.)\n Chooses whether to find increasing or decreasing sets.\n\n - ``side`` -- ``'right'`` or ``'left'`` (default: ``'right'``.) Chooses whether to\n find maximal sets starting from the left or the right.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',2,1])\n sage: p=A.from_lehmer_code([4,1,0])\n sage: p.to_bounded_partition()\n [2, 1, 1, 1]\n " c = sorted(self.to_lehmer_code(typ, side)) c.reverse() return Partition(c).conjugate() def to_core(self, typ='decreasing', side='right'): "\n Returns the core associated to the dominant element obtained by sorting\n the Lehmer code.\n\n INPUT:\n\n - ``typ`` -- ``'increasing'`` or ``'decreasing'`` (default: ``'decreasing'``.)\n\n - ``side`` -- ``'right'`` or ``'left'`` (default: ``'right'``.) Chooses whether to\n find maximal sets starting from the left or the right.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',2,1])\n sage: p=A.from_lehmer_code([4,1,0])\n sage: p.to_bounded_partition()\n [2, 1, 1, 1]\n sage: p.to_core()\n [4, 2, 1, 1]\n " return self.to_bounded_partition(typ, side).to_core(self.k) def to_dominant(self, typ='decreasing', side='right'): "\n Finds the Lehmer code and then sorts it. Returns the affine permutation\n with the given sorted Lehmer code; this element is 0-dominant.\n\n INPUT:\n\n - ``typ`` -- ``'increasing'`` or ``'decreasing'``\n (default: ``'decreasing'``) chooses whether to find increasing\n or decreasing sets\n\n - ``side`` -- ``'right'`` or ``'left'`` (default: ``'right'``) chooses\n whether to find maximal sets starting from the left or the right\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.to_dominant()\n Type A affine permutation with window [-2, -1, 1, 3, 4, 8, 10, 13]\n sage: p.to_dominant(typ='increasing', side='left')\n Type A affine permutation with window [3, 4, -1, 5, 0, 9, 6, 10]\n " if self.is_i_grassmannian(side=side): return self c = sorted(self.to_lehmer_code(typ, side)) c.reverse() return self.parent().from_lehmer_code(c, typ, side) def tableau_of_word(self, w, typ='decreasing', side='right', alpha=None): "\n Finds a tableau on the Lehmer code of ``self`` corresponding\n to the given reduced word.\n\n For a full description of this algorithm, see [Den2012]_.\n\n INPUT:\n\n - ``w`` -- a reduced word for ``self``\n - ``typ`` -- ``'increasing'`` or ``'decreasing'``; the type of\n Lehmer code used\n - ``side`` -- ``'right'`` or ``'left'``\n - ``alpha`` -- a content vector; ``w`` should be of type ``alpha``;\n specifying ``alpha`` produces semistandard tableaux\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p.tableau_of_word(p.reduced_word())\n [[], [1, 6, 9], [2, 7, 10], [], [3], [4, 8], [], [5]]\n sage: A = AffinePermutationGroup(['A',7,1])\n sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: w=p.reduced_word()\n sage: w\n [0, 7, 4, 1, 0, 7, 5, 4, 2, 1]\n sage: alpha=[5,3,2]\n sage: p.tableau_of_word(p.reduced_word(), alpha=alpha)\n [[], [1, 2, 3], [1, 2, 3], [], [1], [1, 2], [], [1]]\n sage: p.tableau_of_word(p.reduced_word(), side='left')\n [[1, 4, 9], [6], [], [], [3, 7], [8], [], [2, 5, 10]]\n sage: p.tableau_of_word(p.reduced_word(), typ='increasing', side='right')\n [[9, 10], [1, 2], [], [], [3, 4], [8], [], [5, 6, 7]]\n sage: p.tableau_of_word(p.reduced_word(), typ='increasing', side='left')\n [[1, 2], [4, 5, 6], [9, 10], [], [3], [7, 8], [], []]\n " g = self.parent().simple_reflections() x0 = prod((g[i] for i in w)) if (x0.length() != len(w)): raise ValueError('word was not reduced') if (alpha is None): alpha = Composition([1 for i in w]) else: if (sum(alpha) != len(w)): raise ValueError('size of alpha must match length of w') alpha = Composition(alpha) tab = [[] for _ in repeat(None, (self.k + 1))] label = 1 al_index = 0 j = 0 x = self.parent().one() cx = x.to_lehmer_code(typ, side) n = (len(w) - 1) for i in range(len(w)): if (side[0] == 'r'): y = x.apply_simple_reflection_left(w[(n - i)]) else: y = x.apply_simple_reflection_right(w[i]) cy = y.to_lehmer_code(typ, side) for r in range((self.k + 1)): if (cy[r] > cx[r]): tab[r].append(label) j += 1 if (j == alpha[al_index]): al_index += 1 j = 0 label += 1 break x = y cx = cy return tab
class AffinePermutationTypeC(AffinePermutation): def check(self): "\n Check that ``self`` is an affine permutation.\n\n EXAMPLES::\n\n sage: C = AffinePermutationGroup(['C',4,1])\n sage: x = C([-1,5,3,7])\n sage: x\n Type C affine permutation with window [-1, 5, 3, 7]\n " if (not self): return k = self.parent().k if (len(self) != k): raise ValueError(('length of list must be k=' + str(k))) reslist = [] for i in self: r = (i % self.N) if (r == 0): raise ValueError('entries may not have residue 0 mod 2k+1') if (not ((r not in reslist) and ((self.N - r) not in reslist))): raise ValueError('entries must have distinct residues') reslist.append(r) def value(self, i): "\n Return the image of the integer ``i`` under this permutation.\n\n EXAMPLES::\n\n sage: C = AffinePermutationGroup(['C',4,1])\n sage: x = C.one()\n sage: [x.value(i) for i in range(-10,10)] == list(range(-10,10))\n True\n " N = ((2 * self.k) + 1) window = (i // N) index = (i % N) if (index == 0): return i if (index <= self.k): return (self[(index - 1)] + (window * N)) if (index > self.k): return ((- (self[((N - index) - 1)] - N)) + (window * N)) def position(self, i): "\n Find the position `j` such the ``self.value(j)=i``\n\n EXAMPLES::\n\n sage: C = AffinePermutationGroup(['C',4,1])\n sage: x = C.one()\n sage: [x.position(i) for i in range(-10,10)] == list(range(-10,10))\n True\n " N = ((2 * self.k) + 1) index = (i % N) if (index == 0): return i for r in range(len(self)): if ((self[r] % N) == index): diff = ((i - self[r]) // N) return ((r + (diff * N)) + 1) if ((self[r] % N) == (N - index)): diff = ((i + self[r]) // N) return (((- r) + (diff * N)) - 1) return False def apply_simple_reflection_right(self, i): "\n Apply the simple reflection indexed by ``i`` on positions.\n\n EXAMPLES::\n\n sage: C = AffinePermutationGroup(['C',4,1])\n sage: x=C([-1,5,3,7])\n sage: for i in C.index_set(): x.apply_simple_reflection_right(i)\n Type C affine permutation with window [1, 5, 3, 7]\n Type C affine permutation with window [5, -1, 3, 7]\n Type C affine permutation with window [-1, 3, 5, 7]\n Type C affine permutation with window [-1, 5, 7, 3]\n Type C affine permutation with window [-1, 5, 3, 2]\n " if (i not in self.parent().index_set()): raise ValueError('index not in index set') j = i l = self[:] if ((j != 0) and (j != self.k)): a = l[(j - 1)] l[(j - 1)] = l[j] l[j] = a elif (j == 0): l[0] = (- l[0]) elif (j == self.k): l[(self.k - 1)] = self((self.k + 1)) return type(self)(self.parent(), l, check=False) def apply_simple_reflection_left(self, i): "\n Apply the simple reflection indexed by ``i`` on values.\n\n EXAMPLES::\n\n sage: C = AffinePermutationGroup(['C',4,1])\n sage: x = C([-1,5,3,7])\n sage: for i in C.index_set(): x.apply_simple_reflection_left(i)\n Type C affine permutation with window [1, 5, 3, 7]\n Type C affine permutation with window [-2, 5, 3, 8]\n Type C affine permutation with window [-1, 5, 2, 6]\n Type C affine permutation with window [-1, 6, 4, 7]\n Type C affine permutation with window [-1, 4, 3, 7]\n " if (i not in self.parent().index_set()): raise ValueError('index not in index set') j = (self.N - i) l = [] if ((i != self.k) and (i != 0)): for m in range(self.k): res = (self[m] % self.N) if (res == i): l.append((self[m] + 1)) elif (res == (i + 1)): l.append((self[m] - 1)) elif (res == j): l.append((self[m] - 1)) elif (res == (j - 1)): l.append((self[m] + 1)) else: l.append(self[m]) elif (i == 0): for m in range(self.k): res = (self[m] % self.N) if (res == 1): l.append((self[m] - 2)) elif (res == (self.N - 1)): l.append((self[m] + 2)) else: l.append(self[m]) elif (i == self.k): for m in range(self.k): res = (self[m] % self.N) if (res == i): l.append((self[m] + 1)) elif (res == j): l.append((self[m] - 1)) else: l.append(self[m]) return type(self)(self.parent(), l, check=False) def has_right_descent(self, i) -> bool: "\n Determine whether there is a descent at index ``i``.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: C = AffinePermutationGroup(['C',4,1])\n sage: x = C([-1,5,3,7])\n sage: for i in C.index_set(): x.has_right_descent(i)\n True\n False\n True\n False\n True\n " return (self.value(i) > self.value((i + 1))) def has_left_descent(self, i) -> bool: "\n Determine whether there is a descent at ``i``.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: C = AffinePermutationGroup(['C',4,1])\n sage: x = C([-1,5,3,7])\n sage: for i in C.index_set(): x.has_left_descent(i)\n True\n False\n True\n False\n True\n " return (self.position(i) > self.position((i + 1))) def to_type_a(self): "\n Return an embedding of ``self`` into the affine permutation group of\n type `A`.\n\n EXAMPLES::\n\n sage: C = AffinePermutationGroup(['C',4,1])\n sage: x = C([-1,5,3,7])\n sage: x.to_type_a()\n Type A affine permutation with window [-1, 5, 3, 7, 2, 6, 4, 10, 9]\n " A = AffinePermutationGroup(['A', (self.N - 1), 1]) return A([self.value(i) for i in range(1, (self.N + 1))])
class AffinePermutationTypeB(AffinePermutationTypeC): def check(self): "\n Check that ``self`` is an affine permutation.\n\n EXAMPLES::\n\n sage: B = AffinePermutationGroup(['B',4,1])\n sage: x = B([-5,1,6,-2])\n sage: x\n Type B affine permutation with window [-5, 1, 6, -2]\n " if (not self): return k = self.parent().k if (len(self) != k): raise ValueError(('length of list must be k=' + str(k))) reslist = [] for i in self: r = (i % self.N) if (r == 0): raise ValueError('entries may not have residue 0 mod 2k+1') if (not ((r not in reslist) and ((self.N - r) not in reslist))): raise ValueError('entries must have distinct residues') reslist.append(r) s = sum(((((- i) // self.N) + 1) for i in (self.value(j) for j in range(1, (self.N + 1))) if (i < 0))) if (s % 2): raise ValueError('type B affine permutations have an even number of entries less than 0 to the right of the 0th position') def apply_simple_reflection_right(self, i): "\n Apply the simple reflection indexed by ``i`` on positions.\n\n EXAMPLES::\n\n sage: B = AffinePermutationGroup(['B',4,1])\n sage: p=B([-5,1,6,-2])\n sage: p.apply_simple_reflection_right(1)\n Type B affine permutation with window [1, -5, 6, -2]\n sage: p.apply_simple_reflection_right(0)\n Type B affine permutation with window [-1, 5, 6, -2]\n sage: p.apply_simple_reflection_right(4)\n Type B affine permutation with window [-5, 1, 6, 11]\n " if (i not in self.parent().index_set()): raise ValueError('index not in index set') j = i l = self[:] if ((j != 0) and (j != self.k)): (l[(j - 1)], l[j]) = (l[j], l[(j - 1)]) elif (j == 0): l[0] = (- self(2)) l[1] = (- self(1)) elif (j == self.k): l[(self.k - 1)] = self((self.k + 1)) return type(self)(self.parent(), l, check=False) def apply_simple_reflection_left(self, i): "\n Apply the simple reflection indexed by ``i`` on values.\n\n EXAMPLES::\n\n sage: B = AffinePermutationGroup(['B',4,1])\n sage: p=B([-5,1,6,-2])\n sage: p.apply_simple_reflection_left(0)\n Type B affine permutation with window [-5, -2, 6, 1]\n sage: p.apply_simple_reflection_left(2)\n Type B affine permutation with window [-5, 1, 7, -3]\n sage: p.apply_simple_reflection_left(4)\n Type B affine permutation with window [-4, 1, 6, -2]\n " if (i not in self.parent().index_set()): raise ValueError('index not in index set') j = (self.N - i) l = [] if ((i != self.k) and (i != 0)): for m in range(self.k): res = (self[m] % self.N) if (res == i): l.append((self[m] + 1)) elif (res == (i + 1)): l.append((self[m] - 1)) elif (res == j): l.append((self[m] - 1)) elif (res == (j - 1)): l.append((self[m] + 1)) else: l.append(self[m]) elif (i == 0): for m in range(self.k): res = (self[m] % self.N) if (res == 1): l.append((self[m] - 3)) elif (res == (self.N - 2)): l.append((self[m] + 3)) elif (res == 2): l.append((self[m] - 3)) elif (res == (self.N - 1)): l.append((self[m] + 3)) else: l.append(self[m]) elif (i == self.k): for m in range(self.k): res = (self[m] % self.N) if (res == i): l.append((self[m] + 1)) elif (res == j): l.append((self[m] - 1)) else: l.append(self[m]) return type(self)(self.parent(), l, check=False) def has_right_descent(self, i) -> bool: "\n Determines whether there is a descent at index ``i``.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: B = AffinePermutationGroup(['B',4,1])\n sage: p = B([-5,1,6,-2])\n sage: [p.has_right_descent(i) for i in B.index_set()]\n [True, False, False, True, False]\n " if (i == 0): return (self.value((- 2)) > self.value(1)) return (self.value(i) > self.value((i + 1))) def has_left_descent(self, i) -> bool: "\n Determines whether there is a descent at ``i``.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: B = AffinePermutationGroup(['B',4,1])\n sage: p=B([-5,1,6,-2])\n sage: [p.has_left_descent(i) for i in B.index_set()]\n [True, True, False, False, True]\n " if (i == 0): return (self.position((- 2)) > self.position(1)) return (self.position(i) > self.position((i + 1)))
class AffinePermutationTypeD(AffinePermutationTypeC): def check(self): "\n Check that ``self`` is an affine permutation.\n\n EXAMPLES::\n\n sage: D = AffinePermutationGroup(['D',4,1])\n sage: p = D([1,-6,5,-2])\n sage: p\n Type D affine permutation with window [1, -6, 5, -2]\n " if (not self): return k = self.parent().k if (len(self) != k): raise ValueError(('length of list must be k=' + str(k))) reslist = [] for i in self: r = (i % self.N) if (r == 0): raise ValueError('entries may not have residue 0 mod 2k+1') if (not ((r not in reslist) and ((self.N - r) not in reslist))): raise ValueError('entries must have distinct residues') reslist.append(r) s = sum(((((i // self.N) + 1) - ((i % self.N) <= self.k)) for i in (self.value(j) for j in range((- self.k), (self.k + 1))) if (i > self.k))) if (s % 2): raise ValueError('type D affine permutations have an even number of entries greater than x.k weakly to the left of the x.k position') s = sum(((((- i) // self.N) + 1) for i in (self.value(j) for j in range(1, (self.N + 1))) if (i < 0))) if (s % 2): raise ValueError('type D affine permutations have an even number of entries less than 0 to the right of the 0th position') def apply_simple_reflection_right(self, i): "\n Apply the simple reflection indexed by ``i`` on positions.\n\n EXAMPLES::\n\n sage: D = AffinePermutationGroup(['D',4,1])\n sage: p=D([1,-6,5,-2])\n sage: p.apply_simple_reflection_right(0)\n Type D affine permutation with window [6, -1, 5, -2]\n sage: p.apply_simple_reflection_right(1)\n Type D affine permutation with window [-6, 1, 5, -2]\n sage: p.apply_simple_reflection_right(4)\n Type D affine permutation with window [1, -6, 11, 4]\n " if (i not in self.parent().index_set()): raise ValueError('index not in index set') j = i l = self[:] if ((j != 0) and (j != self.k)): a = l[(j - 1)] l[(j - 1)] = l[j] l[j] = a elif (j == 0): c = l[0] l[0] = (- l[1]) l[1] = (- c) elif (j == self.k): l[(self.k - 2)] = self((self.k + 1)) l[(self.k - 1)] = self((self.k + 2)) return type(self)(self.parent(), l, check=False) def apply_simple_reflection_left(self, i): "\n Apply simple reflection indexed by ``i`` on values.\n\n EXAMPLES::\n\n sage: D = AffinePermutationGroup(['D',4,1])\n sage: p=D([1,-6,5,-2])\n sage: p.apply_simple_reflection_left(0)\n Type D affine permutation with window [-2, -6, 5, 1]\n sage: p.apply_simple_reflection_left(1)\n Type D affine permutation with window [2, -6, 5, -1]\n sage: p.apply_simple_reflection_left(4)\n Type D affine permutation with window [1, -4, 3, -2]\n " if (i not in self.parent().index_set()): raise ValueError('index not in index set') j = (self.N - i) l = [] if (i and (i != self.k)): for m in range(self.k): res = (self[m] % self.N) if (res == i): l.append((self[m] + 1)) elif (res == (i + 1)): l.append((self[m] - 1)) elif (res == j): l.append((self[m] - 1)) elif (res == (j - 1)): l.append((self[m] + 1)) else: l.append(self[m]) elif (i == 0): for m in range(self.k): res = (self[m] % self.N) if (res == 1): l.append((self[m] - 3)) elif (res == (self.N - 2)): l.append((self[m] + 3)) elif (res == 2): l.append((self[m] - 3)) elif (res == (self.N - 1)): l.append((self[m] + 3)) else: l.append(self[m]) elif (i == self.k): for m in range(self.k): res = (self[m] % self.N) if (res == self.k): l.append((self[m] + 2)) elif (res == (self.k + 2)): l.append((self[m] - 2)) elif (res == (self.k - 1)): l.append((self[m] + 2)) elif (res == (self.k + 1)): l.append((self[m] - 2)) else: l.append(self[m]) return type(self)(self.parent(), l, check=False) def has_right_descent(self, i) -> bool: "\n Determine whether there is a descent at index ``i``.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: D = AffinePermutationGroup(['D',4,1])\n sage: p=D([1,-6,5,-2])\n sage: [p.has_right_descent(i) for i in D.index_set()]\n [True, True, False, True, False]\n " if (i == 0): return (self.value((- 2)) > self.value(1)) if (i == self.k): return (self.value(i) > self.value((i + 2))) return (self.value(i) > self.value((i + 1))) def has_left_descent(self, i) -> bool: "\n Determine whether there is a descent at ``i``.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: D = AffinePermutationGroup(['D',4,1])\n sage: p=D([1,-6,5,-2])\n sage: [p.has_left_descent(i) for i in D.index_set()]\n [True, True, False, True, True]\n " if (i == 0): return (self.position((- 2)) > self.position(1)) if (i == self.k): return (self.position(i) > self.position((i + 2))) return (self.position(i) > self.position((i + 1)))
class AffinePermutationTypeG(AffinePermutation): def check(self): "\n Check that ``self`` is an affine permutation.\n\n EXAMPLES::\n\n sage: G = AffinePermutationGroup(['G',2,1])\n sage: p = G([2, 10, -5, 12, -3, 5])\n sage: p\n Type G affine permutation with window [2, 10, -5, 12, -3, 5]\n " if (not self): return if (not (len(self) == 6)): raise ValueError('length of list must be 6') s = sum((((i // 6) - ((i % 6) == 0)) for i in self if (i > 6))) if (s % 2): raise ValueError('type G affine permutations have an even number of entries greater than 6 to the left of the 7th position') s = sum(((((- i) // 6) + 1) for i in self if (i <= 0))) if (s % 2): raise ValueError('type G affine permutations have an even number of entries less than 0 to the right of the 0th position') def value(self, i, base_window=False): "\n Return the image of the integer ``i`` under this permutation.\n\n INPUT:\n\n - ``base_window`` -- boolean indicating whether ``i`` is between 1 and\n `k+1`; if ``True``, will run a bit faster, but the method will screw\n up if ``i`` is not actually in the index set\n\n EXAMPLES::\n\n sage: G = AffinePermutationGroup(['G',2,1])\n sage: p=G([2, 10, -5, 12, -3, 5])\n sage: [p.value(i) for i in [1..12]]\n [2, 10, -5, 12, -3, 5, 8, 16, 1, 18, 3, 11]\n " N = 6 if base_window: self[(i - 1)] window = ((i - 1) // N) return (self[((i - 1) % N)] + (window * N)) def position(self, i): "\n Find the position ``j`` such the ``self.value(j) == i``.\n\n EXAMPLES::\n\n sage: G = AffinePermutationGroup(['G',2,1])\n sage: p = G([2, 10, -5, 12, -3, 5])\n sage: [p.position(i) for i in p]\n [1, 2, 3, 4, 5, 6]\n " N = 6 for r in range(N): if ((self[r] % N) == (i % N)): diff = ((i - self[r]) // N) return ((r + (diff * N)) + 1) return False def apply_simple_reflection_right(self, i): "\n Apply the simple reflection indexed by ``i`` on positions.\n\n EXAMPLES::\n\n sage: G = AffinePermutationGroup(['G',2,1])\n sage: p = G([2, 10, -5, 12, -3, 5])\n sage: p.apply_simple_reflection_right(0)\n Type G affine permutation with window [-9, -1, -5, 12, 8, 16]\n sage: p.apply_simple_reflection_right(1)\n Type G affine permutation with window [10, 2, 12, -5, 5, -3]\n sage: p.apply_simple_reflection_right(2)\n Type G affine permutation with window [2, -5, 10, -3, 12, 5]\n " if (i not in self.parent().index_set()): raise ValueError('index not in index set') j = i l = self[:] if (j == 1): l[0] = self(2) l[1] = self(1) l[2] = self(4) l[3] = self(3) l[4] = self(6) l[5] = self(5) elif (j == 2): l[1] = self(3) l[2] = self(2) l[3] = self(5) l[4] = self(4) elif (j == 0): l[0] = self((- 1)) l[1] = self(0) l[4] = self(7) l[5] = self(8) return type(self)(self.parent(), l, check=False) def apply_simple_reflection_left(self, i): "\n Apply simple reflection indexed by `i` on values.\n\n EXAMPLES::\n\n sage: G = AffinePermutationGroup(['G',2,1])\n sage: p=G([2, 10, -5, 12, -3, 5])\n sage: p.apply_simple_reflection_left(0)\n Type G affine permutation with window [0, 10, -7, 14, -3, 7]\n sage: p.apply_simple_reflection_left(1)\n Type G affine permutation with window [1, 9, -4, 11, -2, 6]\n sage: p.apply_simple_reflection_left(2)\n Type G affine permutation with window [3, 11, -5, 12, -4, 4]\n " if (i not in self.parent().index_set()): raise ValueError('index not in index set') l = [] if (i == 1): for m in range(6): res = (self[m] % 6) if ((res == 1) or (res == 3) or (res == 5)): l.append((self[m] + 1)) elif ((res == 2) or (res == 4) or (res == 0)): l.append((self[m] - 1)) else: l.append(self[m]) elif (i == 2): for m in range(6): res = (self[m] % 6) if ((res == 2) or (res == 4)): l.append((self[m] + 1)) elif ((res == 3) or (res == 5)): l.append((self[m] - 1)) else: l.append(self[m]) elif (i == 0): for m in range(6): res = (self[m] % 6) if ((res == 1) or (res == 2)): l.append((self[m] - 2)) elif ((res == 5) or (res == 0)): l.append((self[m] + 2)) else: l.append(self[m]) return type(self)(self.parent(), l, check=False) def has_right_descent(self, i) -> bool: "\n Determines whether there is a descent at index `i`.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: G = AffinePermutationGroup(['G',2,1])\n sage: p = G([2, 10, -5, 12, -3, 5])\n sage: [p.has_right_descent(i) for i in G.index_set()]\n [False, False, True]\n " if (i not in self.parent().index_set()): raise ValueError('index not in index set') if (i == 0): return (self.value(0) > self.value(2)) return (self.value(i) > self.value((i + 1))) def has_left_descent(self, i) -> bool: "\n Determines whether there is a descent at ``i``.\n\n INPUT:\n\n - ``i`` -- an integer\n\n EXAMPLES::\n\n sage: G = AffinePermutationGroup(['G',2,1])\n sage: p = G([2, 10, -5, 12, -3, 5])\n sage: [p.has_left_descent(i) for i in G.index_set()]\n [False, True, False]\n " if (i not in self.parent().index_set()): raise ValueError('index not in index set') if (i == 0): return (self.position(0) > self.position(2)) return (self.position(i) > self.position((i + 1))) def to_type_a(self): "\n Return an embedding of ``self`` into the affine permutation group of\n type A.\n\n EXAMPLES::\n\n sage: G = AffinePermutationGroup(['G',2,1])\n sage: p = G([2, 10, -5, 12, -3, 5])\n sage: p.to_type_a()\n Type A affine permutation with window [2, 10, -5, 12, -3, 5]\n " A = AffinePermutationGroup(['A', 5, 1]) return A(self)
def AffinePermutationGroup(cartan_type): "\n Wrapper function for specific affine permutation groups.\n\n These are combinatorial implementations of the affine Weyl groups of\n types `A`, `B`, `C`, `D`, and `G` as permutations of the set of all integers.\n the basic algorithms are derived from [BB2005]_ and [Eri1995]_.\n\n EXAMPLES::\n\n sage: ct = CartanType(['A',7,1])\n sage: A = AffinePermutationGroup(ct)\n sage: A\n The group of affine permutations of type ['A', 7, 1]\n\n We define an element of ``A``::\n\n sage: p = A([3, -1, 0, 6, 5, 4, 10, 9])\n sage: p\n Type A affine permutation with window [3, -1, 0, 6, 5, 4, 10, 9]\n\n We find the value `p(1)`, considering `p` as a bijection on the integers.\n This is the same as calling the\n :meth:`~sage.combinat.affine_permutation.AffinePermutation.value` method::\n\n sage: p.value(1)\n 3\n sage: p(1) == p.value(1)\n True\n\n We can also find the position of the integer 3 in `p` considered as a\n sequence, equivalent to finding `p^{-1}(3)`::\n\n sage: p.position(3)\n 1\n sage: (p^-1)(3)\n 1\n\n Since the affine permutation group is a group, we demonstrate its\n group properties::\n\n sage: A.one()\n Type A affine permutation with window [1, 2, 3, 4, 5, 6, 7, 8]\n\n sage: q = A([0, 2, 3, 4, 5, 6, 7, 9])\n sage: p * q\n Type A affine permutation with window [1, -1, 0, 6, 5, 4, 10, 11]\n sage: q * p\n Type A affine permutation with window [3, -1, 1, 6, 5, 4, 10, 8]\n\n sage: p^-1\n Type A affine permutation with window [0, -1, 1, 6, 5, 4, 10, 11]\n sage: p^-1 * p == A.one()\n True\n sage: p * p^-1 == A.one()\n True\n\n If we decide we prefer the Weyl Group implementation of the affine Weyl\n group, we can easily get it::\n\n sage: p.to_weyl_group_element()\n [ 0 -1 0 1 0 0 1 0]\n [ 1 -1 0 1 0 0 1 -1]\n [ 1 -1 0 1 0 0 0 0]\n [ 0 0 0 1 0 0 0 0]\n [ 0 0 0 1 0 -1 1 0]\n [ 0 0 0 1 -1 0 1 0]\n [ 0 0 0 0 0 0 1 0]\n [ 0 -1 1 0 0 0 1 0]\n\n We can find a reduced word and do all of the other things one expects in\n a Coxeter group::\n\n sage: p.has_right_descent(1)\n True\n sage: p.apply_simple_reflection(1)\n Type A affine permutation with window [-1, 3, 0, 6, 5, 4, 10, 9]\n sage: p.apply_simple_reflection(0)\n Type A affine permutation with window [1, -1, 0, 6, 5, 4, 10, 11]\n sage: p.reduced_word()\n [0, 7, 4, 1, 0, 7, 5, 4, 2, 1]\n sage: p.length()\n 10\n\n The following methods are particular to type `A`.\n We can check if the element is fully commutative::\n\n sage: p.is_fully_commutative()\n False\n sage: q.is_fully_commutative()\n True\n\n We can also compute the affine Lehmer code of the permutation,\n a weak composition with `k + 1` entries::\n\n sage: p.to_lehmer_code()\n [0, 3, 3, 0, 1, 2, 0, 1]\n\n Once we have the Lehmer code, we can obtain a `k`-bounded partition by\n sorting the Lehmer code, and then reading the row lengths.\n There is a unique 0-Grassmanian (dominant) affine permutation associated\n to this `k`-bounded partition, and a `k`-core as well. ::\n\n sage: p.to_bounded_partition()\n [5, 3, 2]\n sage: p.to_dominant()\n Type A affine permutation with window [-2, -1, 1, 3, 4, 8, 10, 13]\n sage: p.to_core()\n [5, 3, 2]\n\n Finally, we can take a reduced word for `p` and insert it to find a\n standard composition tableau associated uniquely to that word::\n\n sage: p.tableau_of_word(p.reduced_word())\n [[], [1, 6, 9], [2, 7, 10], [], [3], [4, 8], [], [5]]\n\n We can also form affine permutation groups in types `B`, `C`, `D`,\n and `G`::\n\n sage: B = AffinePermutationGroup(['B',4,1])\n sage: B.an_element()\n Type B affine permutation with window [-1, 3, 4, 11]\n\n sage: C = AffinePermutationGroup(['C',4,1])\n sage: C.an_element()\n Type C affine permutation with window [2, 3, 4, 10]\n\n sage: D = AffinePermutationGroup(['D',4,1])\n sage: D.an_element()\n Type D affine permutation with window [-1, 3, 11, 5]\n\n sage: G = AffinePermutationGroup(['G',2,1])\n sage: G.an_element()\n Type G affine permutation with window [0, 4, -1, 8, 3, 7]\n " ct = CartanType(cartan_type) if (ct.letter == 'A'): return AffinePermutationGroupTypeA(ct) if (ct.letter == 'B'): return AffinePermutationGroupTypeB(ct) if (ct.letter == 'C'): return AffinePermutationGroupTypeC(ct) if (ct.letter == 'D'): return AffinePermutationGroupTypeD(ct) if (ct.letter == 'G'): return AffinePermutationGroupTypeG(ct) raise NotImplementedError('Cartan type provided is not implemented as an affine permutation group')