Example #1
0
    def strongly_finer(self):
        """
        Return the set of ordered set partitions which are strongly
        finer than ``self``.

        See :meth:`is_strongly_finer` for the definition of "strongly
        finer".

        EXAMPLES::

            sage: C = OrderedSetPartition([[1, 3], [2]]).strongly_finer()
            sage: C.cardinality()
            2
            sage: C.list()
            [[{1}, {3}, {2}], [{1, 3}, {2}]]

            sage: OrderedSetPartition([]).strongly_finer()
            {[]}

            sage: W = OrderedSetPartition([[4, 9], [-1, 2]])
            sage: W.strongly_finer().list()
            [[{4}, {9}, {-1}, {2}],
             [{4}, {9}, {-1, 2}],
             [{4, 9}, {-1}, {2}],
             [{4, 9}, {-1, 2}]]
        """
        par = parent(self)
        if not self:
            return FiniteEnumeratedSet([self])
        else:
            buo = OrderedSetPartition.bottom_up_osp
            return FiniteEnumeratedSet([par(sum((list(P) for P in C), []))
                    for C in cartesian_product([[buo(X, comp) for comp in Compositions(len(X))] for X in self])])
Example #2
0
    def basis(self):
        r"""
        Return the basis of ``self``.

        EXAMPLES::

            sage: g = LieAlgebra(QQ, cartan_type=['D',4,1])
            sage: B = g.basis()
            sage: al = RootSystem(['D',4]).root_lattice().simple_roots()
            sage: B[al[1]+al[2]+al[4],4]
            (E[alpha[1] + alpha[2] + alpha[4]])#t^4
            sage: B[-al[1]-2*al[2]-al[3]-al[4],2]
            (E[-alpha[1] - 2*alpha[2] - alpha[3] - alpha[4]])#t^2
            sage: B[al[4],-2]
            (E[alpha[4]])#t^-2
            sage: B['c']
            c
            sage: B['d']
            d
        """
        K = cartesian_product([self._g.basis().keys(), ZZ])
        from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
        c = FiniteEnumeratedSet(['c'])
        if self._kac_moody:
            d = FiniteEnumeratedSet(['d'])
            keys = DisjointUnionEnumeratedSets([c, d, K])
        else:
            keys = DisjointUnionEnumeratedSets([c, K])
        return Family(keys, self.monomial)
Example #3
0
    def __init__(self, s):
        """
        TESTS::

            sage: s = Subsets(Set([1]))
            sage: e = s.first()
            sage: isinstance(e, s.element_class)
            True

        In the following "_test_elements" is temporarily disabled
        until :class:`sage.sets.set.Set_object_enumerated` objects
        pass the category tests::

            sage: S = Subsets([1,2,3])
            sage: TestSuite(S).run(skip=["_test_elements"])

            sage: S = sage.sets.set.Set_object_enumerated([1,2])
            sage: TestSuite(S).run()         # todo: not implemented
        """
        Parent.__init__(self, category=EnumeratedSets().Finite())
        if s not in EnumeratedSets():
            from sage.misc.misc import uniq
            from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
            s = list(s)
            us = uniq(s)
            if len(us) == len(s):
                s = FiniteEnumeratedSet(s)
            else:
                s = FiniteEnumeratedSet(us)
        self._s = s
Example #4
0
    def __init__(self, R, A):
        """
        Initialize ``self``.

        TESTS::

            sage: C4 = graphs.CycleGraph(4)
            sage: A = groups.misc.RightAngledArtin(C4)
            sage: H = A.cohomology()
            sage: TestSuite(H).run()
        """
        if R not in Fields():
            raise NotImplementedError(
                "only implemented with coefficients in a field")
        self._group = A

        names = tuple(['e' + name[1:] for name in A.variable_names()])
        from sage.graphs.independent_sets import IndependentSets
        from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
        indices = [tuple(ind_set) for ind_set in IndependentSets(A._graph)]
        indices = FiniteEnumeratedSet(indices)
        cat = AlgebrasWithBasis(
            R.category()).Super().Graded().FiniteDimensional()
        CombinatorialFreeModule.__init__(self,
                                         R,
                                         indices,
                                         category=cat,
                                         prefix='H')
        self._assign_names(names)
    def _element_constructor_(self, data):
        r"""
        Build an element of that set from ``data``.

        EXAMPLES::

            sage: S1 = TotallyOrderedFiniteSet([1,2,3])
            sage: x = S1(1); x  # indirect doctest
            1
            sage: x.parent()
            Integer Ring


            sage: S2 = TotallyOrderedFiniteSet([3,2,1], facade=False)
            sage: y = S2(1); y  # indirect doctest
            1
            sage: y.parent()
            {3, 2, 1}
            sage: y in S2
            True
            sage: S2(y) is y
            True
        """
        if self._facade_elements is None:
            return FiniteEnumeratedSet._element_constructor_(self, data)

        try:
            i = self._facade_elements.index(data)
        except ValueError:
            raise ValueError("%s not in %s"%(data, self))

        return self._elements[i]
Example #6
0
    def strongly_fatter(self):
        """
        Return the set of ordered set partitions which are strongly fatter
        than ``self``.

        See :meth:`strongly_finer` for the definition of "strongly fatter".

        EXAMPLES::

            sage: C = OrderedSetPartition([[2, 5], [1], [3, 4]]).strongly_fatter()
            sage: C.cardinality()
            2
            sage: sorted(C)
            [[{2, 5}, {1, 3, 4}],
             [{2, 5}, {1}, {3, 4}]]

            sage: OrderedSetPartition([[4, 9], [-1, 2]]).strongly_fatter().list()
            [[{4, 9}, {-1, 2}]]

        Some extreme cases::

            sage: list(OrderedSetPartition([[5]]).strongly_fatter())
            [[{5}]]
            sage: list(OrderedSetPartition([]).strongly_fatter())
            [[]]
            sage: sorted(OrderedSetPartition([[1], [2], [3], [4]]).strongly_fatter())
            [[{1, 2, 3, 4}],
             [{1, 2, 3}, {4}],
             [{1, 2}, {3, 4}],
             [{1, 2}, {3}, {4}],
             [{1}, {2, 3, 4}],
             [{1}, {2, 3}, {4}],
             [{1}, {2}, {3, 4}],
             [{1}, {2}, {3}, {4}]]
            sage: sorted(OrderedSetPartition([[1], [3], [2], [4]]).strongly_fatter())
            [[{1, 3}, {2, 4}],
             [{1, 3}, {2}, {4}],
             [{1}, {3}, {2, 4}],
             [{1}, {3}, {2}, {4}]]
            sage: sorted(OrderedSetPartition([[4], [1], [5], [3]]).strongly_fatter())
            [[{4}, {1, 5}, {3}], [{4}, {1}, {5}, {3}]]
        """
        c = [sorted(X) for X in self]
        l = len(c)
        g = [-1] + [i
                    for i in range(l - 1) if c[i][-1] > c[i + 1][0]] + [l - 1]
        # g lists the positions of the blocks that cannot be merged
        # with their right neighbors.
        subcomps = [
            OrderedSetPartition(c[g[i] + 1:g[i + 1] + 1])
            for i in range(len(g) - 1)
        ]
        # Now, self is the concatenation of the entries of subcomps.
        # We can fatten each of the ordered set partitions setcomps
        # arbitrarily, and then concatenate the results.
        fattenings = [list(subcomp.fatter()) for subcomp in subcomps]
        return FiniteEnumeratedSet([
            OrderedSetPartition(sum([list(gg) for gg in fattening], []))
            for fattening in cartesian_product(fattenings)
        ])
    def __init__(self, n, k, q, F):
        r"""
        Initialize ``self``.

        EXAMPLES::

            sage: Cl = algebras.QuantumClifford(1,2)
            sage: TestSuite(Cl).run(elements=Cl.basis())

            sage: Cl = algebras.QuantumClifford(1,3)
            sage: TestSuite(Cl).run(elements=Cl.basis())  # long time

            sage: Cl = algebras.QuantumClifford(3)  # long time
            sage: elts = Cl.some_elements() + list(Cl.algebra_generators())  # long time
            sage: TestSuite(Cl).run(elements=elts)  # long time

            sage: Cl = algebras.QuantumClifford(2,4)  # long time
            sage: elts = Cl.some_elements() + list(Cl.algebra_generators())  # long time
            sage: TestSuite(Cl).run(elements=elts)  # long time
        """
        self._n = n
        self._k = k
        self._q = q
        self._psi = cartesian_product([(-1,0,1)]*n)
        self._w_poly = PolynomialRing(F, n, 'w')
        indices = [(tuple(psi), tuple(w))
                   for psi in self._psi
                   for w in product(*[list(range((4-2*abs(psi[i]))*k)) for i in range(n)])]
        indices = FiniteEnumeratedSet(indices)

        cat = Algebras(F).FiniteDimensional().WithBasis()
        CombinatorialFreeModule.__init__(self, F, indices, category=cat)
        self._assign_names(self.algebra_generators().keys())
Example #8
0
    def _element_constructor_(self, data):
        r"""
        Build an element of that set from ``data``.

        EXAMPLES::

            sage: S1 = TotallyOrderedFiniteSet([1,2,3])
            sage: x = S1(1); x  # indirect doctest
            1
            sage: x.parent()
            Integer Ring


            sage: S2 = TotallyOrderedFiniteSet([3,2,1], facade=False)
            sage: y = S2(1); y  # indirect doctest
            1
            sage: y.parent()
            {3, 2, 1}
            sage: y in S2
            True
            sage: S2(y) is y
            True
        """
        if self._facade_elements is None:
            return FiniteEnumeratedSet._element_constructor_(self, data)

        try:
            i = self._facade_elements.index(data)
        except ValueError:
            raise ValueError("%s not in %s" % (data, self))

        return self._elements[i]
Example #9
0
    def graded_component(self, grade):
        r"""
        Return the component with grade ``grade``.

        EXAMPLES::

            sage: N = SetsWithGrading().example()
            sage: N.graded_component(65)
            {65}
        """
        return FiniteEnumeratedSet([grade])
Example #10
0
 def basis(self, reg=None):
     if reg is None:
         reg = region()
     b = self._other.basis(reg + self._neg)
     if b.cardinality() == 0:
         return FiniteEnumeratedSet(())
     x = next(iter(b))
     dom = suspension(x.parent(), **self._kwargs)
     mapfunc = lambda x: x.suspend(**self._kwargs)
     unmapfunc = lambda x: x.suspend(
         t=self._neg.t, e=self._neg.e, s=self._neg.s)
     return SetOfElements(dom, b, b.cardinality(), mapfunc, unmapfunc)
Example #11
0
    def __classcall_private__(cls,
                              domain,
                              codomain=None,
                              action="left",
                              category=None):
        """
        TESTS::

            sage: FiniteSetMaps(3)
            Maps from {0, 1, 2} to itself
            sage: FiniteSetMaps(4, 2)
            Maps from {0, 1, 2, 3} to {0, 1}
            sage: FiniteSetMaps(4, ["a","b","c"])
            Maps from {0, 1, 2, 3} to {'a', 'b', 'c'}
            sage: FiniteSetMaps([1,2], ["a","b","c"])
            Maps from {1, 2} to {'a', 'b', 'c'}
            sage: FiniteSetMaps([1,2,4], 3)
            Maps from {1, 2, 4} to {0, 1, 2}
        """
        if codomain is None:
            if isinstance(domain, (int, Integer)):
                return FiniteSetEndoMaps_N(domain, action, category)
            else:
                if domain not in Sets():
                    domain = FiniteEnumeratedSet(domain)
                return FiniteSetEndoMaps_Set(domain, action, category)

        if isinstance(domain, (int, Integer)):
            if isinstance(codomain, (int, Integer)):
                return FiniteSetMaps_MN(domain, codomain, category)
            else:
                domain = IntegerRange(domain)
        if isinstance(codomain, (int, Integer)):
            codomain = IntegerRange(codomain)

        if domain not in Sets():
            domain = FiniteEnumeratedSet(domain)
        if codomain not in Sets():
            codomain = FiniteEnumeratedSet(codomain)
        return FiniteSetMaps_Set(domain, codomain, category)
Example #12
0
    def __init__(self):
        r"""
        TESTS::

            sage: from sage.rings.valuation.value_group import DiscreteValuationCodomain
            sage: isinstance(QQ.valuation(2).codomain(), DiscreteValuationCodomain)
            True

        """
        from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
        from sage.categories.additive_monoids import AdditiveMonoids
        UniqueRepresentation.__init__(self)
        Parent.__init__(self, facade=(QQ, FiniteEnumeratedSet([infinity, -infinity])), category=AdditiveMonoids())
Example #13
0
    def __classcall__(cls, indices, prefix="F", **kwds):
        """
        TESTS::

            sage: F = FreeAbelianMonoid(index_set=['a','b','c'])
            sage: G = FreeAbelianMonoid(index_set=('a','b','c'))
            sage: H = FreeAbelianMonoid(index_set=tuple('abc'))
            sage: F is G and F is H
            True

            sage: F = FreeAbelianMonoid(index_set=['a','b','c'], latex_bracket=['LEFT', 'RIGHT'])
            sage: F.print_options()['latex_bracket']
            ('LEFT', 'RIGHT')
            sage: F is G
            False
            sage: Groups.Commutative.free()
            Traceback (most recent call last):
            ...
            ValueError: no index set specified
        """
        if isinstance(indices, str):
            indices = FiniteEnumeratedSet(list(indices))
        elif isinstance(indices, (list, tuple)):
            indices = FiniteEnumeratedSet(indices)
        elif indices is None:
            if kwds.get('names', None) is None:
                raise ValueError("no index set specified")
            indices = FiniteEnumeratedSet(kwds['names'])

        # bracket or latex_bracket might be lists, so convert
        # them to tuples so that they're hashable.
        bracket = kwds.get('bracket', None)
        if isinstance(bracket, list):
            kwds['bracket'] = tuple(bracket)
        latex_bracket = kwds.get('latex_bracket', None)
        if isinstance(latex_bracket, list):
            kwds['latex_bracket'] = tuple(latex_bracket)
        return super(IndexedMonoid, cls).__classcall__(cls, indices, prefix,
                                                       **kwds)
Example #14
0
    def __init__(self, R, cartan_matrix, wt, prefix):
        """
        Initialize ``self``.
        """
        self._cartan_matrix = cartan_matrix
        self._weight = wt
        self._d = sum(wt)

        # Reduced words
        #red_words = Family(Permutations(self._d), lambda p: tuple(p.reduced_word()))
        red_words = FiniteEnumeratedSet([tuple(p.reduced_word())
                                         for p in Permutations(self._d)])
        red_words.rename("reduced words of S_{}".format(self._d))
        # The monomials
        M = FreeAbelianMonoid(self._d, names=['x%s'%i for i in range(1, self._d+1)])
        # Idempotents (i.e. the colors of the strands)
        index_set = self._cartan_matrix.index_set()
        P = Permutations(sum([[index_set[i]]*v for i,v in enumerate(wt)],[]))
        I = cartesian_product([red_words, M, P])
        CombinatorialFreeModule.__init__(self, R, I, prefix=prefix,
                                         monomial_key=KLRAlgebra._monomial_key,
                                         category=Algebras(R).WithBasis().Graded())
Example #15
0
    def finer(self):
        """
        Return the set of ordered set partitions which are finer
        than ``self``.

        See :meth:`is_finer` for the definition of "finer".

        EXAMPLES::

            sage: C = OrderedSetPartition([[1, 3], [2]]).finer()
            sage: C.cardinality()
            3
            sage: C.list()
            [[{1}, {3}, {2}], [{3}, {1}, {2}], [{1, 3}, {2}]]

            sage: OrderedSetPartition([]).finer()
            {[]}

            sage: W = OrderedSetPartition([[4, 9], [-1, 2]])
            sage: W.finer().list()
            [[{9}, {4}, {2}, {-1}],
             [{9}, {4}, {-1}, {2}],
             [{9}, {4}, {-1, 2}],
             [{4}, {9}, {2}, {-1}],
             [{4}, {9}, {-1}, {2}],
             [{4}, {9}, {-1, 2}],
             [{4, 9}, {2}, {-1}],
             [{4, 9}, {-1}, {2}],
             [{4, 9}, {-1, 2}]]
        """
        par = parent(self)
        if not self:
            return FiniteEnumeratedSet([self])
        else:
            return FiniteEnumeratedSet([
                par(sum((list(i) for i in C), [])) for C in cartesian_product(
                    [OrderedSetPartitions(X) for X in self])
            ])
Example #16
0
    def __init__(self, R):
        """
        Initialize ``self``.

        EXAMPLES::

            sage: O = lie_algebras.OnsagerAlgebra(QQ)
            sage: TestSuite(O).run()
        """
        cat = LieAlgebras(R).WithBasis()
        from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
        IndexedGenerators.__init__(self, FiniteEnumeratedSet([0,1]))
        LieAlgebraWithGenerators.__init__(self, R, index_set=self._indices,
                                          names=('A0', 'A1'), category=cat)
Example #17
0
    def _indices(self):
        r"""
        Return the set of indices for the basis of ``self``.

        EXAMPLES::

            sage: L.<x,y,z> = LieAlgebra(QQ, abelian=True)
            sage: S = L.subalgebra([x, y])
            sage: S._indices
            {0, 1}
            sage: [S.basis()[k] for k in S._indices]
            [x, y]
        """
        return FiniteEnumeratedSet(self.basis().keys())
Example #18
0
    def __init__(self):
        r"""
        TESTS::

            sage: sys.path.append(os.getcwd()); from mac_lane import * # optional: standalone
            sage: isinstance(pAdicValuation(QQ, 2).codomain(), DiscreteValuationCodomain)
            True

        """
        from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
        from sage.categories.additive_monoids import AdditiveMonoids
        UniqueRepresentation.__init__(self)
        Parent.__init__(self,
                        facade=(QQ, FiniteEnumeratedSet([infinity,
                                                         -infinity])),
                        category=AdditiveMonoids())
Example #19
0
    def __classcall__(cls, *args):
        """
        TESTS::

            sage: from sage.sets.integer_range import IntegerRangeEmpty
            sage: I = IntegerRangeEmpty(); I
            {}
            sage: I.category()
            Category of facade finite enumerated sets
            sage: TestSuite(I).run()
            sage: I(0)
            Traceback (most recent call last):
            ...
            ValueError: 0 not in {}
        """
        return FiniteEnumeratedSet.__classcall__(cls, ())
Example #20
0
    def __classcall__(cls, *args):
        """
        TESTS::

            sage: from sage.sets.integer_range import IntegerRangeEmpty
            sage: I = IntegerRangeEmpty(); I
            {}
            sage: I.category()
            Category of facade finite enumerated sets
            sage: TestSuite(I).run()
            sage: I(0)
            Traceback (most recent call last):
            ...
            ValueError: 0 not in {}
        """
        return FiniteEnumeratedSet.__classcall__(cls, ())
Example #21
0
    def _domain(self):
        r"""
        The integers labeling the roots on which this Galois group acts.

        EXAMPLES::

            sage: R.<x> = ZZ[]
            sage: K.<a> = NumberField(x^5-2)
            sage: G = K.galois_group(gc_numbering=False); G
            Galois group 5T3 (5:4) with order 20 of x^5 - 2
            sage: G._domain
            {1, 2, 3, 4, 5}
            sage: G = K.galois_group(gc_numbering=True); G._domain
            {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
        """
        return FiniteEnumeratedSet(range(1, self._deg + 1))
Example #22
0
    def __init__(self):
        r"""
        EXAMPLES::

            sage: from sage.categories.examples.facade_sets import IntegersCompletion
            sage: S = IntegersCompletion(); S
            An example of a facade set: the integers completed by +-infinity

        TESTS::

            sage: TestSuite(S).run()

        """
        # We can't use InfinityRing, because this ring contains 3
        # elements besides +-infinity. We can't use Set either for the
        # moment, because Set([1,2])(1) raises an error
        Parent.__init__(self, facade = (ZZ, FiniteEnumeratedSet([-infinity, +infinity])), category = Sets())
    def __init__(self, R):
        r"""
        Initialize ``self``.

        EXAMPLES::

            sage: L = lie_algebras.RankTwoHeisenbergVirasoro(QQ)
            sage: TestSuite(L).run()
        """
        cat = LieAlgebras(R).WithBasis()
        self._KI = FiniteEnumeratedSet([1, 2, 3, 4])
        self._V = ZZ**2
        d = {'K': self._KI, 'E': self._V, 't': self._V}
        indices = DisjointUnionEnumeratedSets(d, keepkey=True, facade=True)
        InfinitelyGeneratedLieAlgebra.__init__(self,
                                               R,
                                               index_set=indices,
                                               category=cat)
        IndexedGenerators.__init__(self, indices, sorting_key=self._basis_key)
                def T_all(self):
                    """
                    Return the ring of characters of left/right-class modules

                    .. note:: This includes both regular and non regular
                        modules. So this is in general not isomorphic to
                        the other character rings, and the indexing set
                        may be completely unrelated.

                    .. todo:: add a good example, and find a good name

                    EXAMPLES::

                    """
                    from sage_semigroups.monoids.character_ring import CharacterRing
                    from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
                    return CharacterRing(self,
                                         prefix="T",
                                         modules="%s-class" % self.side(),
                                         index_set=FiniteEnumeratedSet(
                                             self.base().j_classes().keys()))
        def simple_modules_index_set(self):
            """
            Return an indexing set for the simple modules of ``self``

            This indexing set is sorted decreasingly along `J`-order.
            This default implementation uses the same indexing set as
            for the j_classes, as given by::
            :meth:`Semigroups.Finite.ParentMethods.regular_j_classes_keys`.

            EXAMPLES::

                sage: S = Monoids().HTrivial().Finite().example(5); S 
                The finite H-trivial monoid of order preserving maps on {1, 2, 3, 4, 5}
                sage: S.simple_modules_index_set()
                {0, 1, 2, 3, 4}
            """
            result = self.j_transversal_of_idempotents().keys()
            if isinstance(result, list):
                from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
                result = FiniteEnumeratedSet(result)
            return result
    def __init__(self, R, n):
        """
        Initialize ``self``.

        EXAMPLES::

            sage: g = lie_algebras.gl(QQ, 4)
            sage: TestSuite(g).run()

        TESTS:

        Check that :trac:`23266` is fixed::

            sage: gl2 = lie_algebras.gl(QQ, 2)
            sage: isinstance(gl2.basis().keys(), FiniteEnumeratedSet)
            True
            sage: Ugl2 = gl2.pbw_basis()
            sage: prod(Ugl2.gens())
            PBW['E_0_0']*PBW['E_0_1']*PBW['E_1_0']*PBW['E_1_1']
        """
        MS = MatrixSpace(R, n, sparse=True)
        one = R.one()
        names = []
        gens = []
        for i in range(n):
            for j in range(n):
                names.append('E_{0}_{1}'.format(i,j))
                mat = MS({(i,j):one})
                mat.set_immutable()
                gens.append(mat)
        self._n = n
        category = LieAlgebras(R).FiniteDimensional().WithBasis()
        from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
        index_set = FiniteEnumeratedSet(names)
        LieAlgebraFromAssociative.__init__(self, MS, tuple(gens),
                                           names=tuple(names),
                                           index_set=index_set,
                                           category=category)
    def __init__(self, R, ct, e, f, h):
        """
        Initialize ``self``.

        EXAMPLES::

            sage: g = lie_algebras.sl(QQ, 3, representation='matrix')
            sage: TestSuite(g).run()

        TESTS:

        Check that :trac:`23266` is fixed::

            sage: sl2 = lie_algebras.sl(QQ, 2, 'matrix')
            sage: isinstance(sl2.indices(), FiniteEnumeratedSet)
            True
        """
        n = len(e)
        names = ['e%s'%i for i in range(1, n+1)]
        names += ['f%s'%i for i in range(1, n+1)]
        names += ['h%s'%i for i in range(1, n+1)]
        category = LieAlgebras(R).FiniteDimensional().WithBasis()
        from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
        index_set = FiniteEnumeratedSet(names)
        LieAlgebraFromAssociative.__init__(self, e[0].parent(),
                                           gens=tuple(e + f + h),
                                           names=tuple(names),
                                           index_set=index_set,
                                           category=category)
        self._cartan_type = ct

        gens = tuple(self.gens())
        i_set = ct.index_set()
        self._e = Family(dict( (i, gens[c]) for c,i in enumerate(i_set) ))
        self._f = Family(dict( (i, gens[n+c]) for c,i in enumerate(i_set) ))
        self._h = Family(dict( (i, gens[2*n+c]) for c,i in enumerate(i_set) ))
 def polygon_labels(self):
     from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
     from sage.categories.cartesian_product import cartesian_product
     return cartesian_product(
         [self._words, FiniteEnumeratedSet([0, 1, 2, 3])])
Example #29
0
def standardize_names_index_set(names=None, index_set=None, ngens=None):
    """
    Standardize the ``names`` and ``index_set`` inputs.

    INPUT:

    - ``names`` -- (optional) the variable names
    - ``index_set`` -- (optional) the index set
    - ``ngens`` -- (optional) the number of generators

    If ``ngens`` is a negative number, then this does not check that
    the number of variable names matches the size of the index set.

    OUTPUT:

    A pair ``(names_std, index_set_std)``, where ``names_std`` is either
    ``None`` or a tuple of strings, and where ``index_set_std`` is a finite
    enumerated set.
    The purpose of ``index_set_std`` is to index the generators of some object
    (e.g., the basis of a module); the strings in ``names_std``, when they
    exist, are used for printing these indices. The ``ngens``

    If ``names`` contains exactly one name ``X`` and ``ngens`` is greater than
    1, then ``names_std`` are ``Xi`` for ``i`` in ``range(ngens)``.

    TESTS::

        sage: from sage.structure.indexed_generators import standardize_names_index_set
        sage: standardize_names_index_set('x,y')
        (('x', 'y'), {'x', 'y'})
        sage: standardize_names_index_set(['x','y'])
        (('x', 'y'), {'x', 'y'})
        sage: standardize_names_index_set(['x','y'], ['a','b'])
        (('x', 'y'), {'a', 'b'})
        sage: standardize_names_index_set('x,y', ngens=2)
        (('x', 'y'), {'x', 'y'})
        sage: standardize_names_index_set(index_set=['a','b'], ngens=2)
        (None, {'a', 'b'})
        sage: standardize_names_index_set('x', ngens=3)
        (('x0', 'x1', 'x2'), {'x0', 'x1', 'x2'})

        sage: standardize_names_index_set()
        Traceback (most recent call last):
        ...
        ValueError: the index_set, names, or number of generators must be specified
        sage: standardize_names_index_set(['x'], ['a', 'b'])
        Traceback (most recent call last):
        ...
        IndexError: the number of names must equal the size of the indexing set
        sage: standardize_names_index_set('x,y', ['a'])
        Traceback (most recent call last):
        ...
        IndexError: the number of names must equal the size of the indexing set
        sage: standardize_names_index_set('x,y,z', ngens=2)
        Traceback (most recent call last):
        ...
        IndexError: the number of names must equal the number of generators
        sage: standardize_names_index_set(index_set=['a'], ngens=2)
        Traceback (most recent call last):
        ...
        IndexError: the size of the indexing set must equal the number of generators
    """
    if names is not None:
        if ngens is None or ngens < 0:
            names = normalize_names(-1, names)
        else:
            names = normalize_names(ngens, names)

    if index_set is None:
        if names is None:
            # If neither is specified, we make range(ngens) the index set
            if ngens is None:
                raise ValueError("the index_set, names, or number of"
                                 " generators must be specified")
            index_set = tuple(range(ngens))
        else:
            # If only the names are specified, then we make the indexing set
            #   be the names
            index_set = tuple(names)

    from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
    if isinstance(index_set, dict): # dict of {name: index} -- not likely to be used
        if names is not None:
            raise ValueError("cannot give index_set as a dict and names")
        names = normalize_names(-1, tuple(index_set.keys()))
        index_set = FiniteEnumeratedSet([index_set[n] for n in names])
    elif isinstance(index_set, str):
        index_set = FiniteEnumeratedSet(list(index_set))
    elif isinstance(index_set, (tuple, list)):
        index_set = FiniteEnumeratedSet(index_set)

    if ngens is None or ngens >= 0:
        if names is not None:
            if len(names) != index_set.cardinality():
                raise IndexError("the number of names must equal"
                                 " the size of the indexing set")
            if ngens is not None and len(names) != ngens:
                raise IndexError("the number of names must equal the"
                                 " number of generators")
        elif ngens is not None and index_set.cardinality() != ngens:
            raise IndexError("the size of the indexing set must equal"
                             " the number of generators")

    return (names, index_set)
    def __init__(self, R, cartan_type):
        r"""
        Initialize ``self``.

        TESTS::

            sage: L = LieAlgebra(QQ, cartan_type=['A',2])
            sage: TestSuite(L).run()  # long time
        """
        self._cartan_type = cartan_type
        RL = cartan_type.root_system().root_lattice()
        alpha = RL.simple_roots()
        p_roots = list(RL.positive_roots_by_height())
        n_roots = [-x for x in p_roots]
        self._p_roots_index = {al: i for i,al in enumerate(p_roots)}
        alphacheck = RL.simple_coroots()
        roots = frozenset(RL.roots())
        num_sroots = len(alpha)
        one = R.one()

        # Determine the signs for the structure coefficients from the root system
        # We first create the special roots
        sp_sign = {}
        for i,a in enumerate(p_roots):
            for b in p_roots[i+1:]:
                if a + b not in p_roots:
                    continue

                # Compute the sign for the extra special pair
                x, y = (a + b).extraspecial_pair()

                if (x, y) == (a, b): # If it already is an extra special pair
                    if (x, y) not in sp_sign:
                        # This swap is so the structure coefficients match with GAP
                        if (sum(x.coefficients()) == sum(y.coefficients())
                            and str(x) > str(y)):
                            y,x = x,y
                        sp_sign[(x, y)] = -one
                        sp_sign[(y, x)] = one
                    continue

                if b - x in roots:
                    t1 = ((b-x).norm_squared() / b.norm_squared()
                          * sp_sign[(x, b-x)] * sp_sign[(a, y-a)])
                else:
                    t1 = 0
                if a - x in roots:
                    t2 = ((a-x).norm_squared() / a.norm_squared()
                          * sp_sign[(x, a-x)] * sp_sign[(b, y-b)])
                else:
                    t2 = 0

                if t1 - t2 > 0:
                    sp_sign[(a,b)] = -one
                elif t2 - t1 > 0:
                    sp_sign[(a,b)] = one
                sp_sign[(b,a)] = -sp_sign[(a,b)]

        # Function to construct the structure coefficients (up to sign)
        def e_coeff(r, s):
            p = 1
            while r - p*s in roots:
                p += 1
            return p

        # Now we can compute all necessary structure coefficients
        s_coeffs = {}
        for i,r in enumerate(p_roots):
            # [e_r, h_i] and [h_i, f_r]
            for ac in alphacheck:
                c = r.scalar(ac)
                if c == 0:
                    continue
                s_coeffs[(r, ac)] = {r: -c}
                s_coeffs[(ac, -r)] = {-r: -c}

            # [e_r, f_r]
            s_coeffs[(r, -r)] = {alphacheck[j]: c
                                 for j, c in r.associated_coroot()}

            # [e_r, e_s] and [e_r, f_s] with r != +/-s
            # We assume s is positive, as otherwise we negate
            #   both r and s and the resulting coefficient
            for j, s in enumerate(p_roots[i+1:]):
                j += i+1 # Offset
                # Since h(s) >= h(r), we have s - r > 0 when s - r is a root
                # [f_r, e_s]
                if s - r in p_roots:
                    c = e_coeff(r, -s)
                    a, b = s-r, r
                    if self._p_roots_index[a] > self._p_roots_index[b]: # Note a != b
                        c *= -sp_sign[(b, a)]
                    else:
                        c *= sp_sign[(a, b)]
                    s_coeffs[(-r, s)] = {a: -c}
                    s_coeffs[(r, -s)] = {-a: c}

                # [e_r, e_s]
                a = r + s
                if a in p_roots:
                    # (r, s) is a special pair
                    c = e_coeff(r, s) * sp_sign[(r, s)]
                    s_coeffs[(r, s)] = {a: c}
                    s_coeffs[(-r, -s)] = {-a: -c}

        # Lastly, make sure a < b for all (a, b) in the coefficients and flip if necessary
        for k in s_coeffs.keys():
            a,b = k[0], k[1]
            if self._basis_key(a) > self._basis_key(b):
                s_coeffs[(b,a)] = [(index, -v) for index,v in s_coeffs[k].items()]
                del s_coeffs[k]
            else:
                s_coeffs[k] = s_coeffs[k].items()

        names = ['e{}'.format(i) for i in range(1, num_sroots+1)]
        names += ['f{}'.format(i) for i in range(1, num_sroots+1)]
        names += ['h{}'.format(i) for i in range(1, num_sroots+1)]
        category = LieAlgebras(R).FiniteDimensional().WithBasis()
        index_set = p_roots + list(alphacheck) + n_roots
        names = tuple(names)
        from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
        index_set = FiniteEnumeratedSet(index_set)
        LieAlgebraWithStructureCoefficients.__init__(self, R, s_coeffs, names, index_set,
                                                     category, prefix='E', bracket='[',
                                                     sorting_key=self._basis_key)
Example #31
0
def standardize_names_index_set(names=None, index_set=None, ngens=None):
    """
    Standardize the ``names`` and ``index_set`` inputs.

    INPUT:

    - ``names`` -- (optional) the variable names
    - ``index_set`` -- (optional) the index set
    - ``ngens`` -- (optional) the number of generators

    If ``ngens`` is a negative number, then this does not check that
    the number of variable names matches the size of the index set.

    OUTPUT:

    A pair ``(names_std, index_set_std)``, where ``names_std`` is either
    ``None`` or a tuple of strings, and where ``index_set_std`` is a finite
    enumerated set.
    The purpose of ``index_set_std`` is to index the generators of some object
    (e.g., the basis of a module); the strings in ``names_std``, when they
    exist, are used for printing these indices. The ``ngens``

    If ``names`` contains exactly one name ``X`` and ``ngens`` is greater than
    1, then ``names_std`` are ``Xi`` for ``i`` in ``range(ngens)``.

    TESTS::

        sage: from sage.structure.indexed_generators import standardize_names_index_set
        sage: standardize_names_index_set('x,y')
        (('x', 'y'), {'x', 'y'})
        sage: standardize_names_index_set(['x','y'])
        (('x', 'y'), {'x', 'y'})
        sage: standardize_names_index_set(['x','y'], ['a','b'])
        (('x', 'y'), {'a', 'b'})
        sage: standardize_names_index_set('x,y', ngens=2)
        (('x', 'y'), {'x', 'y'})
        sage: standardize_names_index_set(index_set=['a','b'], ngens=2)
        (None, {'a', 'b'})
        sage: standardize_names_index_set('x', ngens=3)
        (('x0', 'x1', 'x2'), {'x0', 'x1', 'x2'})

        sage: standardize_names_index_set()
        Traceback (most recent call last):
        ...
        ValueError: the index_set, names, or number of generators must be specified
        sage: standardize_names_index_set(['x'], ['a', 'b'])
        Traceback (most recent call last):
        ...
        IndexError: the number of names must equal the size of the indexing set
        sage: standardize_names_index_set('x,y', ['a'])
        Traceback (most recent call last):
        ...
        IndexError: the number of names must equal the size of the indexing set
        sage: standardize_names_index_set('x,y,z', ngens=2)
        Traceback (most recent call last):
        ...
        IndexError: the number of names must equal the number of generators
        sage: standardize_names_index_set(index_set=['a'], ngens=2)
        Traceback (most recent call last):
        ...
        IndexError: the size of the indexing set must equal the number of generators
    """
    if names is not None:
        if ngens is None or ngens < 0:
            names = normalize_names(-1, names)
        else:
            names = normalize_names(ngens, names)

    if index_set is None:
        if names is None:
            # If neither is specified, we make range(ngens) the index set
            if ngens is None:
                raise ValueError("the index_set, names, or number of"
                                 " generators must be specified")
            index_set = tuple(range(ngens))
        else:
            # If only the names are specified, then we make the indexing set
            #   be the names
            index_set = tuple(names)

    from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
    if isinstance(index_set,
                  dict):  # dict of {name: index} -- not likely to be used
        if names is not None:
            raise ValueError("cannot give index_set as a dict and names")
        names = normalize_names(-1, tuple(index_set.keys()))
        index_set = FiniteEnumeratedSet([index_set[n] for n in names])
    elif isinstance(index_set, str):
        index_set = FiniteEnumeratedSet(list(index_set))
    elif isinstance(index_set, (tuple, list)):
        index_set = FiniteEnumeratedSet(index_set)

    if ngens is None or ngens >= 0:
        if names is not None:
            if len(names) != index_set.cardinality():
                raise IndexError("the number of names must equal"
                                 " the size of the indexing set")
            if ngens is not None and len(names) != ngens:
                raise IndexError("the number of names must equal the"
                                 " number of generators")
        elif ngens is not None and index_set.cardinality() != ngens:
            raise IndexError("the size of the indexing set must equal"
                             " the number of generators")

    return (names, index_set)
Example #32
0
def Subwords(w, k=None, element_constructor=None):
    """
    Return the set of subwords of ``w``.

    INPUT:

    - ``w`` -- a word (can be a list, a string, a tuple or a word)

    - ``k`` -- an optional integer to specify the length of subwords

    - ``element_constructor`` -- an optional function that will be used
      to build the subwords

    EXAMPLES::

        sage: S = Subwords(['a','b','c']); S
        Subwords of ['a', 'b', 'c']
        sage: S.first()
        []
        sage: S.last()
        ['a', 'b', 'c']
        sage: S.list()
        [[], ['a'], ['b'], ['c'], ['a', 'b'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]

    The same example using string, tuple or a word::

        sage: S = Subwords('abc'); S
        Subwords of 'abc'
        sage: S.list()
        ['', 'a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']

        sage: S = Subwords((1,2,3)); S
        Subwords of (1, 2, 3)
        sage: S.list()
        [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

        sage: w = Word([1,2,3])
        sage: S = Subwords(w); S
        Subwords of word: 123
        sage: S.list()
        [word: , word: 1, word: 2, word: 3, word: 12, word: 13, word: 23, word: 123]

    Using word with specified length::

        sage: S = Subwords(['a','b','c'], 2); S
        Subwords of ['a', 'b', 'c'] of length 2
        sage: S.list()
        [['a', 'b'], ['a', 'c'], ['b', 'c']]

    An example that uses the ``element_constructor`` argument::

        sage: p = Permutation([3,2,1])
        sage: Subwords(p, element_constructor=tuple).list()
        [(), (3,), (2,), (1,), (3, 2), (3, 1), (2, 1), (3, 2, 1)]
        sage: Subwords(p, 2, element_constructor=tuple).list()
        [(3, 2), (3, 1), (2, 1)]
    """
    if element_constructor is None:
        datatype = type(w)  # 'datatype' is the type of w
        if datatype is list or datatype is tuple:
            element_constructor = datatype
        elif datatype is str:
            element_constructor = _stringification
        else:
            from sage.combinat.words.words import Words
            try:
                alphabet = w.parent().alphabet()
                element_constructor = Words(alphabet)
            except AttributeError:
                element_constructor = list

    if k is None:
        return Subwords_w(w, element_constructor)
    if not isinstance(k, (int, Integer)):
        raise ValueError("k should be an integer")
    if k < 0 or k > len(w):
        return FiniteEnumeratedSet([])
    return Subwords_wk(w, k, element_constructor)