Beispiel #1
0
        def semigroup_generators(self):
            """
            Return the generators of ``self`` as a semigroup.

            The generators of a monoid `M` as a semigroup are the generators
            of `M` as a monoid and the unit.

            EXAMPLES::

                sage: M = Monoids().free([1,2,3])
                sage: M.semigroup_generators()
                Family (1, F[1], F[2], F[3])
            """
            G = self.monoid_generators()
            from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
            if G not in FiniteEnumeratedSets():
                raise NotImplementedError("currently only implemented for finitely generated monoids")
            from sage.sets.family import Family
            return Family((self.one(),) + tuple(G))
Beispiel #2
0
    def __init__(self, shape, weight):
        r"""
        Initializes the parent class of Littlewood-Richardson tableaux.

        INPUT:

        - ``shape`` -- the shape of the Littlewood-Richardson tableaux
        - ``weight`` -- the weight is a sequence of partitions

        TESTS::

            sage: LR = LittlewoodRichardsonTableaux([3,2,1],[[2,1],[2,1]])
            sage: TestSuite(LR).run()
        """
        self._shape = shape
        self._weight = weight
        self._heights = [a.length() for a in self._weight]
        super(LittlewoodRichardsonTableaux,
              self).__init__(category=FiniteEnumeratedSets())
    def __init__(self, R, P, prefix='I'):
        """
        Initialize ``self``.

        TESTS::

            sage: P = posets.BooleanLattice(4)
            sage: I = P.incidence_algebra(QQ)
            sage: TestSuite(I).run()  # long time
        """
        cat = Algebras(R).WithBasis()
        if P in FiniteEnumeratedSets():
            cat = cat.FiniteDimensional()
        self._poset = P
        CombinatorialFreeModule.__init__(self,
                                         R,
                                         map(tuple, P.intervals()),
                                         prefix=prefix,
                                         category=cat)
Beispiel #4
0
    def __init__(self, s, k):
        """
        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(3,2)
            sage: TestSuite(S).run(skip=["_test_elements"])
        """
        CombinatorialClass.__init__(self, category=FiniteEnumeratedSets())
        self.s = Set(s)
        self.k = k
Beispiel #5
0
    def __contains__(self, x):
        """
        EXAMPLES::

            sage: from sage.sets.family import LazyFamily
            sage: f = LazyFamily([3,4,7], lambda i: 2*i)
            sage: 3 in f, 14 in f
            (False, True)

        By default this expands the lazy family, which is only done for
        families known to be finite::

            sage: 5 in LazyFamily(NonNegativeIntegers(), lambda i: 2*i)
            Traceback (most recent call last):
            ...
            ValueError: family must be finite to check containment
        """
        if self not in FiniteEnumeratedSets():
            raise ValueError('family must be finite to check containment')
        return x in iter(self)
Beispiel #6
0
    def __init__(self, elements, facade=True):
        """
        Initialize ``self``.

        TESTS::

            sage: TestSuite(TotallyOrderedFiniteSet([1,2,3])).run()
            sage: TestSuite(TotallyOrderedFiniteSet([1,2,3],facade=False)).run()
            sage: TestSuite(TotallyOrderedFiniteSet([1,3,2],facade=False)).run()
            sage: TestSuite(TotallyOrderedFiniteSet([])).run()
        """
        Parent.__init__(self,
                        facade=facade,
                        category=(Posets(), FiniteEnumeratedSets()))
        self._elements = elements
        if facade:
            self._facade_elements = None
        else:
            self._facade_elements = self._elements
            self._elements = [self.element_class(self, x) for x in elements]
Beispiel #7
0
    def __init__(self, R, L):
        """
        Initialize ``self``.

        TESTS::

            sage: L = posets.BooleanLattice(4)
            sage: M = L.moebius_algebra(QQ)
            sage: TestSuite(M).run()
        """
        if not L.is_lattice():
            raise ValueError("L must be a lattice")
        cat = Algebras(R).Commutative().WithBasis()
        if L in FiniteEnumeratedSets():
            cat = cat.FiniteDimensional()
        self._lattice = L
        self._category = cat
        Parent.__init__(self,
                        base=R,
                        category=self._category.WithRealizations())
Beispiel #8
0
    def __init__(self, s):
        """
        Constructs the combinatorial class of the sub multisets of s.

        EXAMPLES::

            sage: S = Subsets([1,2,2,3], submultiset=True)
            sage: Subsets([1,2,3,3], submultiset=True).cardinality()
            12
        """
        CombinatorialClass.__init__(self, category=FiniteEnumeratedSets())

        s = sorted(list(s))
        indices = list(sorted(Set([s.index(a) for a in s])))
        multiplicities = [len([a for a in s if a == s[i]])
                          for i in indices]

        self._s = s
        self._indices = indices
        self._multiplicities = multiplicities
    def __init__(self, row_sums, column_sums):
        r"""
        Constructor of this class; for documentation, see
        :class:`IntegerMatrices`.

        INPUT:

        - ``row_sums`` -- Composition
        - ``column_sums`` -- Composition

        TESTS::

            sage: from sage.combinat.integer_matrices import IntegerMatrices
            sage: IM = IntegerMatrices([3,2,2], [2,5]); IM
            Non-negative integer matrices with row sums [3, 2, 2] and column sums [2, 5]
            sage: TestSuite(IM).run()
        """
        self._row_sums = row_sums
        self._col_sums = column_sums
        Parent.__init__(self, category=FiniteEnumeratedSets())
    def __init__(self, G, d, max_part, sgs=None):
        r"""
        TESTS::

            sage: I = IntegerVectorsModPermutationGroup(PermutationGroup([[(1,2,3,4)]]), 6, max_part=4)
        """
        SearchForest.__init__(self, algorithm = 'breadth', category = (FiniteEnumeratedSets(), FiniteEnumeratedSets().Quotients()))
        self._permgroup = G
        self.n = G.degree()
        self._sum = d
        if max_part is None:
            self._max_part = -1
        else:
            self._max_part = max_part

        # self.sgs: strong_generating_system
        if sgs is None:
            self._sgs = G.strong_generating_system()
        else:
            self._sgs = [list(x) for x in list(sgs)]
Beispiel #11
0
    def __init__(self, ambient, predicate, maximal = False, element_class = Set_object_enumerated):
        """
        TESTS::

            sage: from sage.combinat.subsets_pairwise import PairwiseCompatibleSubsets
            sage: def predicate(x,y): return gcd(x,y) == 1
            sage: P = PairwiseCompatibleSubsets( [4,5,6,8,9], predicate); P
            An enumerated set with a forest structure
            sage: import __main__; __main__.predicate = predicate
            sage: TestSuite(P).run()

        """
        self._ambient = set(ambient)
        self._roots = ( ((), tuple(reversed(ambient))), )
        self._predicate = predicate
        self._maximal = maximal
        # TODO: use self.element_class for consistency
        # At this point (2011/03) TestSuite fails if we do so
        self._element_class = element_class
        SearchForest.__init__(self, algorithm = 'depth', category = FiniteEnumeratedSets())
Beispiel #12
0
    def __init__(self, dictionary, keys=None):
        """
        TESTS::

            sage: from sage.sets.family import FiniteFamily
            sage: f = FiniteFamily({3: 'a', 4: 'b', 7: 'd'})
            sage: TestSuite(f).run()

        Check for bug :trac:`5538`::

            sage: d = {1:"a", 3:"b", 4:"c"}
            sage: f = Family(d)
            sage: d[2] = 'DD'
            sage: f
            Finite family {1: 'a', 3: 'b', 4: 'c'}
            """
        # TODO: use keys to specify the order of the elements
        Parent.__init__(self, category=FiniteEnumeratedSets())
        self._dictionary = dict(dictionary)
        self._keys = keys
Beispiel #13
0
    def __init__(self, group, element):
        r"""
        Generic conjugacy classes for elements in a group.
        This is the default fall-back implementation to be used whenever
        GAP cannot handle the group.

        EXAMPLES::

            sage: G = SymmetricGroup(4)
            sage: g = G((1,2,3,4))
            sage: ConjugacyClass(G,g)
            Conjugacy class of (1,2,3,4) in Symmetric group of order 4! as a
            permutation group
            sage: TestSuite(G).run()
        """
        self._parent = group
        self._representative = element
        if group.is_finite():
            Parent.__init__(self, category=FiniteEnumeratedSets())
        else:  # If the group is not finite, then we do not know if we are finite or not
            Parent.__init__(self, category=EnumeratedSets())
Beispiel #14
0
    def basis(self, region=None):
        if hasattr(self, "_domain"):
            # hack: we're grading a Steenrod algebra module
            gb = []
            for idx in range(0, len(self._summands)):

                def mkfam(emb, xx):
                    return xx.map(lambda u: emb(u))

                x = self._summands[idx].basis(region)
                gb.append(mkfam(self._domain.summand_embedding(idx), x))
            if all(fam.cardinality() < Infinity for fam in gb):
                category = FiniteEnumeratedSets()
            else:
                category = EnumeratedSets()
            return DisjointUnionEnumeratedSets(gb,
                                               keepkey=False,
                                               category=category)

        # this is probably a sample grading...
        return set.union(*[x.basis(region) for x in self._summands])
Beispiel #15
0
    def __init__(
        self,
        elements=None,
        tdegree=None,
        edegree=None,
        sdegree=None,
        tesfunc=None,
        **kwargs
    ):
        """
        Construct a finite yacop graded set from the given elements and degrees.

        EXAMPLE::

            sage: from yacop.utils.finite_graded_set import FiniteGradedSet
            sage: F=FiniteGradedSet((0,1,2),tdegree=lambda i:2*i,sdegree = lambda n:(n&1))
            sage: list(F)
            [0, 1, 2]
            sage: F.degree(1)
            region(e = 0, s = 1, t = 2)
            sage: F.bbox()
            region(e = 0, 0 <= s <= 1, 0 <= t <= 4)

        """
        self._list = kwargs.pop("elemlist")
        self._elems = []
        self._degs = dict()
        self._gb = dict()
        for (el, i, e, s) in self._list:
            self._elems.append(el)
            self._degs[el] = (i, e, s)
            try:
                x = self._gb[(i, e, s)]
            except KeyError:
                x = []
            x.append(el)
            self._gb[(i, e, s)] = x
        # category = (FiniteEnumeratedSets(),YacopGradedObjects())
        category = (FiniteEnumeratedSets(), YacopGradedSets())
        Parent.__init__(self, category=category)
Beispiel #16
0
    def __init__(self, L, q=None):
        """
        Initialize ``self``.

        TESTS::

            sage: L = posets.BooleanLattice(4)
            sage: M = L.quantum_moebius_algebra()
            sage: TestSuite(M).run() # long time
        """
        if not L.is_lattice():
            raise ValueError("L must be a lattice")
        if q is None:
            q = LaurentPolynomialRing(ZZ, 'q').gen()
        self._q = q
        R = q.parent()
        cat = Algebras(R).WithBasis()
        if L in FiniteEnumeratedSets():
            cat = cat.Commutative().FiniteDimensional()
        self._lattice = L
        self._category = cat
        Parent.__init__(self, base=R, category=self._category.WithRealizations())
Beispiel #17
0
    def __init__(self, m, n, category=None):
        """
        Initialize ``self``.

        EXAMPLES::

            sage: C = ColoredPermutations(4, 3)
            sage: TestSuite(C).run()
            sage: C = ColoredPermutations(2, 3)
            sage: TestSuite(C).run()
            sage: C = ColoredPermutations(1, 3)
            sage: TestSuite(C).run()
        """
        if m <= 0:
            raise ValueError("m must be a positive integer")
        self._m = m
        self._n = n
        self._C = IntegerModRing(self._m)
        self._P = Permutations(self._n)
        if category is None:
            category = (Groups(), FiniteEnumeratedSets())
        Parent.__init__(self, category=category)
    def __init__(self, family, facade=True, keepkey=False, category = None):
        """
        TESTS::

            sage: U = DisjointUnionEnumeratedSets({1: FiniteEnumeratedSet([1,2,3]),
            ....:                                  2: FiniteEnumeratedSet([4,5,6])})
            sage: TestSuite(U).run()
        """
        self._family = family
        self._facade  = facade
        self._keepkey = keepkey
        if self._is_category_initialized():
            return
        if category is None:
            # try to guess if the result is infinite or not.
            if self._family in InfiniteEnumeratedSets():
                category = InfiniteEnumeratedSets()
            elif self._family.last().cardinality() == Infinity:
                category = InfiniteEnumeratedSets()
            else:
                category = FiniteEnumeratedSets()
        Parent.__init__(self, category = category)
Beispiel #19
0
    def __getattr__(self, name):
        r"""
        If the attribute '_elements' is called then it is set to '_alphabet'.

        EXAMPLES::

            sage: from sage.combinat.words.alphabet import OrderedAlphabet
            sage: O = OrderedAlphabet()
            doctest:...: DeprecationWarning: OrderedAlphabet is deprecated; use Alphabet instead.
            See http://trac.sagemath.org/8920 for details.
            sage: O._alphabet = ['a', 'b']
            sage: O._elements
            ('a', 'b')
        """
        if name == '_elements':
            if not hasattr(self, '_alphabet'):
                raise AttributeError("no attribute '_elements'")
            self._elements = tuple(self._alphabet)
            from sage.structure.parent import Parent
            from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
            Parent.__init__(self, category=FiniteEnumeratedSets(), facade=True)
            return self._elements
        raise AttributeError("no attribute %s"%name)
Beispiel #20
0
    def __init__(self, n, k, strict):
        """
        Initialize ``self``.

        EXAMPLES::

            sage: G = GelfandTsetlinPatterns()
            sage: TestSuite(G).run()
            sage: G = GelfandTsetlinPatterns(3)
            sage: TestSuite(G).run()
            sage: G = GelfandTsetlinPatterns(3, 3)
            sage: TestSuite(G).run()
            sage: G = GelfandTsetlinPatterns(3, 3, strict=True)
            sage: TestSuite(G).run()
        """
        self._n = n
        self._k = k
        self._strict = strict
        # Note - if a top row is given, then n and k are not None
        if k is not None and (n is not None or strict):
            Parent.__init__(self, category=FiniteEnumeratedSets())
        else:
            Parent.__init__(self, category=InfiniteEnumeratedSets())
Beispiel #21
0
    def __init__(self, abvar, field_of_definition=QQ):
        """
        Initialize ``self``.

        TESTS::

            sage: A = J0(11)
            sage: G = A.torsion_subgroup(2)
            sage: TestSuite(G).run() # long time
        """
        from sage.categories.category import Category
        from sage.categories.fields import Fields
        from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
        from sage.categories.modules import Modules
        from .abvar import is_ModularAbelianVariety
        if field_of_definition not in Fields():
            raise TypeError("field_of_definition must be a field")
        if not is_ModularAbelianVariety(abvar):
            raise TypeError("abvar must be a modular abelian variety")
        category = Category.join((Modules(ZZ), FiniteEnumeratedSets()))
        Module.__init__(self, ZZ, category=category)
        self.__abvar = abvar
        self.__field_of_definition = field_of_definition
Beispiel #22
0
        def affine_grassmannian_elements_of_given_length(self, k):
            """
            Return the affine Grassmannian elements of length `k`.

            This is returned as a finite enumerated set.

            EXAMPLES::

                sage: W = WeylGroup(['A',3,1])
                sage: [x.reduced_word() for x in W.affine_grassmannian_elements_of_given_length(3)]
                [[2, 1, 0], [3, 1, 0], [2, 3, 0]]

            .. SEEALSO::

                :meth:`AffineWeylGroups.ElementMethods.is_affine_grassmannian`
            """
            from sage.combinat.backtrack import SearchForest

            def select_length(pair):
                u, length = pair
                if length == k:
                    return u

            def succ(pair):
                u, length = pair
                for i in u.descents(positive=True, side="left"):
                    u1 = u.apply_simple_reflection(i, "left")
                    if (length < k and i == u1.first_descent(side="left")
                            and u1.is_affine_grassmannian()):
                        yield (u1, length + 1)
                return

            return SearchForest(((self.one(), 0), ),
                                succ,
                                algorithm='breadth',
                                category=FiniteEnumeratedSets(),
                                post_process=select_length)
Beispiel #23
0
    def __init__(self, cartan_type, shape):
        """
        Initialize ``self``.

        EXAMPLES::

            sage: T = crystals.Tableaux(['Q',3], shape=[4,2])
            sage: TestSuite(T).run()
            sage: T = crystals.Tableaux(['Q',4], shape=[4,1])
            sage: TestSuite(T).run()  # long time
        """
        from sage.categories.regular_supercrystals import RegularSuperCrystals
        from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
        Parent.__init__(self,
                        category=(RegularSuperCrystals(),
                                  FiniteEnumeratedSets()))
        self.shape = shape
        self._cartan_type = cartan_type
        self.letters = CrystalOfLetters(cartan_type)
        n = cartan_type.rank() + 1
        data = sum(([self.letters(n - i)] * row_len
                    for i, row_len in enumerate(shape)), [])
        mg = self.element_class(self, list=data)
        self.module_generators = (mg, )
Beispiel #24
0
    def __init__(self, dictionary, keys=None):
        """
        TESTS::

            sage: from sage.sets.family import FiniteFamily
            sage: f = FiniteFamily({3: 'a', 4: 'b', 7: 'd'})
            sage: TestSuite(f).run()

        Check for bug #5538::

            sage: d = {1:"a", 3:"b", 4:"c"}
            sage: f = Family(d)
            sage: d[2] = 'DD'
            sage: f
            Finite family {1: 'a', 3: 'b', 4: 'c'}
            """
        # TODO: use keys to specify the order of the elements
        Parent.__init__(self, category=FiniteEnumeratedSets())
        self._dictionary = dict(dictionary)
        self._keys = keys
        if keys is None:
            # Note: this overrides the two methods keys and values!
            self.keys = dictionary.keys
            self.values = dictionary.values
Beispiel #25
0
        def monoid_generators(self):
            r"""
            Return the generators of ``self`` as a monoid.

            Let `G` be a group with generating set `X`. In general, the
            generating set of `G` as a monoid is given by `X \cup X^{-1}`,
            where `X^{-1}` is the set of inverses of `X`. If `G` is a finite
            group, then the generating set as a monoid is `X`.

            EXAMPLES::

                sage: A = AlternatingGroup(4)
                sage: A.monoid_generators()
                Family ((2,3,4), (1,2,3))
                sage: F.<x,y> = FreeGroup()
                sage: F.monoid_generators()
                Family (x, y, x^-1, y^-1)
            """
            G = self.group_generators()
            from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
            if G not in FiniteEnumeratedSets():
                raise NotImplementedError("currently only implemented for finitely generated groups")
            from sage.sets.family import Family
            return Family(tuple(G) + tuple(~x for x in G))
Beispiel #26
0
    def __init__(self, Q):
        """
        Initialize ``self``.

        INPUT:

        - a :class:`~sage.graphs.digraph.DiGraph`.

        EXAMPLES:

        Note that usually a path semigroup is created using
        :meth:`sage.graphs.digraph.DiGraph.path_semigroup`. Here, we
        demonstrate the direct construction::

            sage: Q = DiGraph({1:{2:['a','b'], 3:['c']}, 2:{3:['d']}}, immutable=True)
            sage: from sage.quivers.path_semigroup import PathSemigroup
            sage: P = PathSemigroup(Q)
            sage: P is DiGraph({1:{2:['a','b'], 3:['c']}, 2:{3:['d']}}).path_semigroup() # indirect doctest
            True
            sage: P
            Partial semigroup formed by the directed paths of Multi-digraph on 3 vertices

        While hardly of any use, it is possible to construct the path
        semigroup of an empty quiver (it is, of course, empty)::

            sage: D = DiGraph({})
            sage: A = D.path_semigroup(); A
            Partial semigroup formed by the directed paths of Digraph on 0 vertices
            sage: A.list()
            []

        .. TODO::

            When the graph has more than one edge, the proper category would be
            a "partial semigroup" or a "semigroupoid" but definitely not a
            semigroup!
        """
        #########
        ## Verify that the graph labels are acceptable for this implementation ##
        # Check that edges are labelled with nonempty strings and don't begin
        # with 'e_' or contain '*'
        labels = Q.edge_labels()
        if len(set(labels)) != len(labels):
            raise ValueError("edge labels of the digraph must be unique")
        for x in labels:
            if not isinstance(x, str) or x == '':
                raise ValueError("edge labels of the digraph must be nonempty strings")
            if x[0:2] == 'e_':
                raise ValueError("edge labels of the digraph must not begin with 'e_'")
            if x.find('*') != -1:
                raise ValueError("edge labels of the digraph must not contain '*'")

        # Check validity of input: vertices have to be labelled 1,2,3,... and
        # edge labels must be unique
        for v in Q:
            if not isinstance(v, integer_types + (Integer,)):
                raise ValueError("vertices of the digraph must be labelled by integers")

        ## Determine the category which this (partial) semigroup belongs to
        if Q.is_directed_acyclic():
            cat = FiniteEnumeratedSets()
        else:
            cat = InfiniteEnumeratedSets()
        self._sorted_edges = tuple(sorted(Q.edges(), key=lambda x:x[2]))
        self._labels = tuple([x[2] for x in self._sorted_edges])
        self._label_index = {s[2]: i for i,s in enumerate(self._sorted_edges)}
        self._nb_arrows = max(len(self._sorted_edges), 1)
        names = ['e_{0}'.format(v) for v in Q.vertices()] + list(self._labels)
        self._quiver = Q
        if Q.num_verts() == 1:
            cat = cat.join([cat,Monoids()])
        else:
            cat = cat.join([cat,Semigroups()])
        Parent.__init__(self, names=names, category=cat)
Beispiel #27
0
        sage: is_IntegerModRing(GF(13))
        True
        sage: is_IntegerModRing(GF(4, 'a'))
        False
        sage: is_IntegerModRing(10)
        False
        sage: is_IntegerModRing(ZZ)
        False
    """
    return isinstance(x, IntegerModRing_generic)


from sage.categories.commutative_rings import CommutativeRings
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
from sage.categories.category import JoinCategory
default_category = JoinCategory((CommutativeRings(), FiniteEnumeratedSets()))
ZZ = integer_ring.IntegerRing()


def _unit_gens_primepowercase(p, r):
    r"""
    Return a list of generators for `(\ZZ/p^r\ZZ)^*` and their orders.

    EXAMPLES::

        sage: from sage.rings.finite_rings.integer_mod_ring import _unit_gens_primepowercase
        sage: _unit_gens_primepowercase(2, 3)
        [(7, 2), (5, 2)]
        sage: _unit_gens_primepowercase(17, 1)
        [(3, 16)]
        sage: _unit_gens_primepowercase(3, 3)
Beispiel #28
0
    def __init__(self,
                 n,
                 length=None,
                 min_length=0,
                 max_length=float('+inf'),
                 floor=None,
                 ceiling=None,
                 min_part=0,
                 max_part=float('+inf'),
                 min_slope=float('-inf'),
                 max_slope=float('+inf'),
                 name=None,
                 element_constructor=None,
                 element_class=None,
                 global_options=None):
        """
        Initialize ``self``.

        TESTS::

            sage: C = IntegerListsLex(2, length=3)
            sage: C == loads(dumps(C))
            True
            sage: C == loads(dumps(C)) # this did fail at some point, really!
            True
            sage: C is loads(dumps(C)) # todo: not implemented
            True
            sage: C.cardinality().parent() is ZZ
            True
            sage: TestSuite(C).run()
        """
        # Convert to float infinity
        from sage.rings.infinity import infinity
        if max_slope == infinity:
            max_slope = float('+inf')
        if min_slope == -infinity:
            min_slope = float('-inf')
        if max_length == infinity:
            max_length = float('inf')
        if max_part == infinity:
            max_part = float('+inf')

        if floor is None:
            self.floor_list = []
        elif isinstance(floor, __builtin__.list):
            self.floor_list = floor
            # Make sure the floor list will make the list satisfy the constraints
            if max_slope != float('+inf'):
                for i in reversed(range(len(self.floor_list) - 1)):
                    self.floor_list[i] = max(
                        self.floor_list[i], self.floor_list[i + 1] - max_slope)
            if min_slope != float('-inf'):
                for i in range(1, len(self.floor_list)):
                    self.floor_list[i] = max(
                        self.floor_list[i], self.floor_list[i - 1] + min_slope)
        else:
            self.floor = floor
        if ceiling is None:
            self.ceiling_list = []
        elif isinstance(ceiling, __builtin__.list):
            self.ceiling_list = ceiling
            # Make sure the ceiling list will make the list satisfy the constraints
            if max_slope != float('+inf'):
                for i in range(1, len(self.ceiling_list)):
                    self.ceiling_list[i] = min(
                        self.ceiling_list[i],
                        self.ceiling_list[i - 1] + max_slope)
            if min_slope != float('-inf'):
                for i in reversed(range(len(self.ceiling_list) - 1)):
                    self.ceiling_list[i] = min(
                        self.ceiling_list[i],
                        self.ceiling_list[i + 1] - min_slope)
        else:
            self.ceiling = ceiling
        if length is not None:
            min_length = length
            max_length = length
        if name is not None:
            self.rename(name)
        if n in ZZ:
            self.n = n
            self.n_range = [n]
        else:
            self.n_range = n
        self.min_length = min_length
        self.max_length = max_length
        self.min_part = min_part
        self.max_part = max_part
        # FIXME: the internal functions currently assume that floor and ceiling start at 1
        # this is a workaround
        self.max_slope = max_slope
        self.min_slope = min_slope
        if element_constructor is not None:
            self._element_constructor_ = element_constructor
        if element_class is not None:
            self.Element = element_class
        if global_options is not None:
            self.global_options = global_options
        Parent.__init__(self, category=FiniteEnumeratedSets())
Beispiel #29
0
    def __init__(self, order, cache=None, category=None):
        """
        Create with the command IntegerModRing(order)
        
        INPUT:
        
        
        -  ``order`` - an integer 1

        - ``category`` - a subcategory of ``CommutativeRings()`` (the default)
          (currently only available for subclasses)

        OUTPUT:
        
        
        -  ``IntegerModRing`` - the ring of integers modulo
           N.
        
        
        EXAMPLES:
        
        First we compute with integers modulo `29`.
        
        ::
        
            sage: FF = IntegerModRing(29)
            sage: FF
            Ring of integers modulo 29
            sage: FF.category()
            Join of Category of commutative rings and Category of subquotients of monoids and Category of quotients of semigroups and Category of finite enumerated sets
            sage: FF.is_field()
            True
            sage: FF.characteristic()
            29
            sage: FF.order()
            29
            sage: gens = FF.unit_gens()
            sage: a = gens[0]
            sage: a
            2
            sage: a.is_square()
            False
            sage: def pow(i): return a**i
            sage: [pow(i) for i in range(16)]
            [1, 2, 4, 8, 16, 3, 6, 12, 24, 19, 9, 18, 7, 14, 28, 27]
            sage: TestSuite(FF).run()

        We have seen above that an integer mod ring is, by default, not
        initialised as an object in the category of fields. However, one
        can force it to be. Moreover, testing containment in the category
        of fields my re-initialise the category of the integer mod ring::

            sage: F19 = IntegerModRing(19, category = Fields())
            sage: F19.category().is_subcategory(Fields())
            True
            sage: F23 = IntegerModRing(23)
            sage: F23.category().is_subcategory(Fields())
            False
            sage: F23 in Fields()
            True
            sage: F23.category().is_subcategory(Fields())
            True
            sage: TestSuite(F19).run()
            sage: TestSuite(F23).run()
        
        Next we compute with the integers modulo `16`.
        
        ::
        
            sage: Z16 = IntegerModRing(16)
            sage: Z16.category()
            Join of Category of commutative rings and Category of subquotients of monoids and Category of quotients of semigroups and Category of finite enumerated sets
            sage: Z16.is_field()
            False
            sage: Z16.order()
            16
            sage: Z16.characteristic() 
            16
            sage: gens = Z16.unit_gens()
            sage: gens
            [15, 5]
            sage: a = gens[0]
            sage: b = gens[1]
            sage: def powa(i): return a**i
            sage: def powb(i): return b**i
            sage: gp_exp = FF.unit_group_exponent()
            sage: gp_exp
            28
            sage: [powa(i) for i in range(15)]
            [1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1]
            sage: [powb(i) for i in range(15)]
            [1, 5, 9, 13, 1, 5, 9, 13, 1, 5, 9, 13, 1, 5, 9]
            sage: a.multiplicative_order()
            2
            sage: b.multiplicative_order()
            4
            sage: TestSuite(Z16).run()
        
        Saving and loading::
        
            sage: R = Integers(100000)
            sage: TestSuite(R).run()  # long time (17s on sage.math, 2011)

        Testing ideals and quotients::

            sage: Z10 = Integers(10)
            sage: I = Z10.principal_ideal(0)
            sage: Z10.quotient(I) == Z10
            True
            sage: I = Z10.principal_ideal(2)
            sage: Z10.quotient(I) == Z10
            False
            sage: I.is_prime()
            True
        """
        order = ZZ(order)
        if order <= 0:
            raise ZeroDivisionError, "order must be positive"
        self.__order = order
        self._pyx_order = integer_mod.NativeIntStruct(order)
        self.__unit_group_exponent = None
        self.__factored_order = None
        self.__factored_unit_order = None
        if category is None:
            from sage.categories.commutative_rings import CommutativeRings
            from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
            from sage.categories.category import Category
            category = Category.join(
                [CommutativeRings(),
                 FiniteEnumeratedSets()])


#            category = default_category
# If the category is given then we trust that is it right.
# Give the generator a 'name' to make quotients work.  The
# name 'x' is used because it's also used for the ring of
# integers: see the __init__ method for IntegerRing_class in
# sage/rings/integer_ring.pyx.
        quotient_ring.QuotientRing_generic.__init__(self,
                                                    ZZ,
                                                    ZZ.ideal(order),
                                                    names=('x', ),
                                                    category=category)
        # Calling ParentWithGens is not needed, the job is done in
        # the quotient ring initialisation.
        #ParentWithGens.__init__(self, self, category = category)
        # We want that the ring is its own base ring.
        self._base = self
        if cache is None:
            cache = order < 500
        if cache:
            self._precompute_table()
        self._zero_element = integer_mod.IntegerMod(self, 0)
        self._one_element = integer_mod.IntegerMod(self, 1)
Beispiel #30
0
    def __init__(self,
                 n,
                 length=None,
                 min_length=0,
                 max_length=float('+inf'),
                 floor=None,
                 ceiling=None,
                 min_part=0,
                 max_part=float('+inf'),
                 min_slope=float('-inf'),
                 max_slope=float('+inf'),
                 name=None,
                 element_constructor=None,
                 element_class=None,
                 global_options=None):
        """
        Initialize ``self``.

        TESTS::

            sage: import sage.combinat.integer_list_old as integer_list
            sage: C = integer_list.IntegerListsLex(2, length=3)
            sage: C == loads(dumps(C))
            True
            sage: C == loads(dumps(C)) # this did fail at some point, really!
            True
            sage: C is loads(dumps(C)) # todo: not implemented
            True
            sage: C.cardinality().parent() is ZZ
            True
            sage: TestSuite(C).run()
        """
        stopgap(
            "The old implementation of IntegerListsLex does not allow for arbitrary input;"
            " non-allowed input can return wrong results,"
            " please see the documentation for IntegerListsLex for details.",
            17548)
        # Convert to float infinity
        from sage.rings.infinity import infinity
        if max_slope == infinity:
            max_slope = float('+inf')
        if min_slope == -infinity:
            min_slope = float('-inf')
        if max_length == infinity:
            max_length = float('inf')
        if max_part == infinity:
            max_part = float('+inf')

        if floor is None:
            self.floor_list = []
        else:
            try:
                # Is ``floor`` an iterable?
                # Not ``floor[:]`` because we want ``self.floor_list``
                #    mutable, and applying [:] to a tuple gives a tuple.
                self.floor_list = builtins.list(floor)
                # Make sure the floor list will make the list satisfy the constraints
                if min_slope != float('-inf'):
                    for i in range(1, len(self.floor_list)):
                        self.floor_list[i] = max(
                            self.floor_list[i],
                            self.floor_list[i - 1] + min_slope)

                # Some input checking
                for i in range(1, len(self.floor_list)):
                    if self.floor_list[i] - self.floor_list[i - 1] > max_slope:
                        raise ValueError(
                            "floor does not satisfy the max slope condition")
                if self.floor_list and min_part - self.floor_list[
                        -1] > max_slope:
                    raise ValueError(
                        "floor does not satisfy the max slope condition")
            except TypeError:
                self.floor = floor
        if ceiling is None:
            self.ceiling_list = []
        else:
            try:
                # Is ``ceiling`` an iterable?
                self.ceiling_list = builtins.list(ceiling)
                # Make sure the ceiling list will make the list satisfy the constraints
                if max_slope != float('+inf'):
                    for i in range(1, len(self.ceiling_list)):
                        self.ceiling_list[i] = min(
                            self.ceiling_list[i],
                            self.ceiling_list[i - 1] + max_slope)

                # Some input checking
                for i in range(1, len(self.ceiling_list)):
                    if self.ceiling_list[i] - self.ceiling_list[i -
                                                                1] < min_slope:
                        raise ValueError(
                            "ceiling does not satisfy the min slope condition")
                if self.ceiling_list and max_part - self.ceiling_list[
                        -1] < min_slope:
                    raise ValueError(
                        "ceiling does not satisfy the min slope condition")
            except TypeError:
                # ``ceiling`` is not an iterable.
                self.ceiling = ceiling
        if name is not None:
            self.rename(name)
        if n in ZZ:
            self.n = n
            self.n_range = [n]
        else:
            self.n_range = n
        if length is not None:
            min_length = length
            max_length = length
        self.min_length = min_length
        self.max_length = max_length
        self.min_part = min_part
        self.max_part = max_part
        # FIXME: the internal functions currently assume that floor and ceiling start at 1
        # this is a workaround
        self.max_slope = max_slope
        self.min_slope = min_slope
        if element_constructor is not None:
            self._element_constructor_ = element_constructor
        if element_class is not None:
            self.Element = element_class
        if global_options is not None:
            self.global_options = global_options
        Parent.__init__(self, category=FiniteEnumeratedSets())
Beispiel #31
0
    def __init__(self, Q):
        """
        Initialize ``self``.

        INPUT:

        - a :class:`~sage.graphs.digraph.DiGraph`.

        EXAMPLES:

        Note that usually a path semigroup is created using
        :meth:`sage.graphs.digraph.DiGraph.path_semigroup`. Here, we
        demonstrate the direct construction::

            sage: Q = DiGraph({1:{2:['a','b'], 3:['c']}, 2:{3:['d']}}, immutable=True)
            sage: from sage.quivers.path_semigroup import PathSemigroup
            sage: P = PathSemigroup(Q)
            sage: P is DiGraph({1:{2:['a','b'], 3:['c']}, 2:{3:['d']}}).path_semigroup() # indirect doctest
            True
            sage: P
            Partial semigroup formed by the directed paths of Multi-digraph on 3 vertices

        While hardly of any use, it is possible to construct the path
        semigroup of an empty quiver (it is, of course, empty)::

            sage: D = DiGraph({})
            sage: A = D.path_semigroup(); A
            Partial semigroup formed by the directed paths of Digraph on 0 vertices
            sage: A.list()
            []
        """
        #########
        ## Verify that the graph labels are acceptable for this implementation ##
        # Check that edges are labelled with nonempty strings and don't begin
        # with 'e_' or contain '*'
        for x in Q.edge_labels():
            if not isinstance(x, str) or x == '':
                raise ValueError("edge labels of the digraph must be nonempty strings")
            if x[0:2] == 'e_':
                raise ValueError("edge labels of the digraph must not begin with 'e_'")
            if x.find('*') != -1:
                raise ValueError("edge labels of the digraph must not contain '*'")
        # Check validity of input: vertices have to be labelled 1,2,3,... and
        # edge labels must be unique
        for v in Q:
            if v not in ZZ:
                raise ValueError("vertices of the digraph must be labelled by integers")
        if len(set(Q.edge_labels())) != Q.num_edges():
            raise ValueError("edge labels of the digraph must be unique")
        nvert = len(Q.vertices())
        ## Determine the category which this (partial) semigroup belongs to
        if Q.is_directed_acyclic() and not Q.has_loops():
            cat = FiniteEnumeratedSets()
        else:
            cat = InfiniteEnumeratedSets()
        names = ['e_{0}'.format(v) for v in Q.vertices()] + [e[2] for e in Q.edges()]
        self._quiver = Q
        if nvert == 1:
            cat = cat.join([cat,Monoids()])
        else:
            # TODO: Make this the category of "partial semigroups"
            cat = cat.join([cat,Semigroups()])
        Parent.__init__(self, names=names, category=cat)