def __init__(self, poset, facade): """ TESTS:: sage: from sage.combinat.posets.linear_extensions import LinearExtensionsOfPoset sage: P = Poset(([1,2,3],[[1,2],[1,3]])) sage: L = P.linear_extensions() sage: L is LinearExtensionsOfPoset(P) True sage: L._poset is P True sage: L._linear_extensions_of_hasse_diagram Linear extensions of Hasse diagram of a poset containing 3 elements sage: TestSuite(L).run() sage: P = Poset((divisors(15), attrcall("divides"))) sage: L = P.linear_extensions() sage: TestSuite(L).run() sage: P = Poset((divisors(15), attrcall("divides")), facade=True) sage: L = P.linear_extensions() sage: TestSuite(L).run() sage: L = P.linear_extensions(facade = True) sage: TestSuite(L).run(skip="_test_an_element") """ self._poset = poset self._linear_extensions_of_hasse_diagram = sage.graphs.linearextensions.LinearExtensions(poset._hasse_diagram) self._is_facade = facade if facade: facade = (list,) Parent.__init__(self, category = FiniteEnumeratedSets(), facade=facade)
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() sage: X = DisjointUnionEnumeratedSets({i: Partitions(i) for i in range(5)}) sage: TestSuite(X).run() """ self._family = family self._facade = facade if facade: if family in FiniteEnumeratedSets(): self._facade_for = tuple(family) else: # This allows the test suite to pass its tests by essentially # stating that this is a facade for any parent. Technically # this is wrong, but in practice, it will not have much # of an effect. self._facade_for = True 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, facade=facade, category=category)
def __init__(self, x, degree=None): """ EXAMPLES:: sage: R.<x> = PolynomialRing(QQ) sage: f = x^4 - 17*x^3 - 2*x + 1 sage: G = f.galois_group(pari_group=True); G PARI group [24, -1, 5, "S4"] of degree 4 sage: G.category() Category of finite groups Caveat: fix those tests and/or document precisely that this is an abstract group without explicit elements:: sage: TestSuite(G).run(skip = ["_test_an_element", ....: "_test_associativity", ....: "_test_elements", ....: "_test_elements_eq_reflexive", ....: "_test_elements_eq_symmetric", ....: "_test_elements_eq_transitive", ....: "_test_elements_neq", ....: "_test_enumerated_set_contains", ....: "_test_enumerated_set_iter_cardinality", ....: "_test_enumerated_set_iter_list", ....: "_test_inverse", ....: "_test_one", ....: "_test_prod", ....: "_test_some_elements"]) """ if not isinstance(x, pari_gen): raise TypeError("x (=%s) must be a PARI gen" % x) self.__x = x self.__degree = degree from sage.categories.finite_groups import FiniteGroups Parent.__init__(self, category=FiniteGroups())
def __init__(self, A, names=None): """ Initialize ``self``. TESTS:: sage: F.<x,y,z> = FreeAlgebra(QQ) sage: J = JordanAlgebra(F) sage: TestSuite(J).run() sage: J.category() Category of commutative unital algebras with basis over Rational Field """ R = A.base_ring() C = MagmaticAlgebras(R) if A not in C.Associative(): raise ValueError("A is not an associative algebra") self._A = A cat = C.Commutative() if A in C.Unital(): cat = cat.Unital() self._no_generic_basering_coercion = True # Remove the preceding line once trac #16492 is fixed # Removing this line will also break some of the input formats, # see trac #16054 if A in C.WithBasis(): cat = cat.WithBasis() if A in C.FiniteDimensional(): cat = cat.FiniteDimensional() Parent.__init__(self, base=R, names=names, category=cat)
def __init__(self): """ TESTS:: sage: P = Sets().example("inherits") """ Parent.__init__(self, category = Sets())
def __init__(self, cartan_type, r, s): r""" Initialize the KirillovReshetikhinTableaux class. INPUT: - ``cartan_type`` -- The Cartan type - ``r`` -- The number of rows - ``s`` -- The number of columns EXAMPLES:: sage: KRT = KirillovReshetikhinTableaux(['A', 4, 1], 2, 3); KRT Kirillov-Reshetikhin tableaux of type ['A', 4, 1] and shape (2, 3) sage: TestSuite(KRT).run() # long time (4s on sage.math, 2013) sage: KRT = KirillovReshetikhinTableaux(['D', 4, 1], 2, 3); KRT Kirillov-Reshetikhin tableaux of type ['D', 4, 1] and shape (2, 3) sage: TestSuite(KRT).run() # long time (53s on sage.math, 2013) sage: KRT = KirillovReshetikhinTableaux(['D', 4, 1], 4, 1); KRT Kirillov-Reshetikhin tableaux of type ['D', 4, 1] and shape (4, 1) sage: TestSuite(KRT).run() """ self._r = r self._s = s Parent.__init__(self, category=FiniteCrystals()) self.rename("Kirillov-Reshetikhin tableaux of type %s and shape (%d, %d)" % (cartan_type, r, s)) self._cartan_type = cartan_type.classical() self.letters = CrystalOfLetters(self._cartan_type) self.module_generators = self._build_module_generators()
def __init__(self, base, prec, names, element_class, category=None): """ Initializes self. EXAMPLES:: sage: R = Zp(5) #indirect doctest sage: R.precision_cap() 20 In :trac:`14084`, the category framework has been implemented for p-adic rings:: sage: TestSuite(R).run() sage: K = Qp(7) sage: TestSuite(K).run() TESTS:: sage: R = Zp(5, 5, 'fixed-mod') sage: R._repr_option('element_is_atomic') False """ self._prec = prec self.Element = element_class default_category = getattr(self, '_default_category', None) if self.is_field(): category = CompleteDiscreteValuationFields() else: category = CompleteDiscreteValuationRings() if default_category is not None: category = check_default_category(default_category, category) Parent.__init__(self, base, names=(names,), normalize=False, category=category, element_constructor=element_class)
def __init__(self, crystals, weight, P): """ Initialize ``self``. EXAMPLES:: sage: B = crystals.KirillovReshetikhin(['A',2,1], 1,1) sage: La = RootSystem(['A',2,1]).weight_lattice().fundamental_weights() sage: C = crystals.KyotoPathModel(B, La[0]) sage: TestSuite(C).run() # long time """ Parent.__init__(self, category=(HighestWeightCrystals(), InfiniteEnumeratedSets())) self._cartan_type = crystals[0].cartan_type() self._weight = weight if weight.parent().is_extended(): # public for TensorProductOfCrystals self.crystals = tuple([C.affinization() for C in crystals]) self._epsilon_dicts = [{b.Epsilon(): self.crystals[i](b, 0) for b in B} for i,B in enumerate(crystals)] self._phi_dicts = [{b.Phi(): self.crystals[i](b, 0) for b in B} for i,B in enumerate(crystals)] else: # public for TensorProductOfCrystals self.crystals = tuple(crystals) self._epsilon_dicts = [{b.Epsilon(): b for b in B} for B in crystals] self._phi_dicts = [{b.Phi(): b for b in B} for B in crystals] self.module_generators = (self.element_class(self, [self._phi_dicts[0][weight]]),)
def __init__(self, base_ring, ambient_dim): """ The Python constructor. EXAMPLES:: sage: from sage.geometry.polyhedron.parent import Polyhedra sage: Polyhedra(QQ, 3) Polyhedra in QQ^3 TESTS:: sage: from sage.geometry.polyhedron.parent import Polyhedra sage: P = Polyhedra(QQ, 3) sage: TestSuite(P).run(skip='_test_pickling') """ self._ambient_dim = ambient_dim from sage.categories.polyhedra import PolyhedralSets Parent.__init__(self, base=base_ring, category=PolyhedralSets(base_ring)) self._Inequality_pool = [] self._Equation_pool = [] self._Vertex_pool = [] self._Ray_pool = [] self._Line_pool = []
def __init__(self, ct, element_class, case): """ EXAMPLES:: sage: E = CrystalOfSpinsMinus(['D',4]) sage: TestSuite(E).run() """ self._cartan_type = CartanType(ct) if case == "spins": self.rename("The crystal of spins for type %s"%ct) elif case == "plus": self.rename("The plus crystal of spins for type %s"%ct) else: self.rename("The minus crystal of spins for type %s"%ct) self.Element = element_class # super(GenericCrystalOfSpins, self).__init__(category = FiniteEnumeratedSets()) Parent.__init__(self, category = ClassicalCrystals()) if case == "minus": generator = [1]*(ct[1]-1) generator.append(-1) else: generator = [1]*ct[1] self.module_generators = [self(generator)] self._list = list(self) # self._digraph = ClassicalCrystal.digraph(self) self._digraph = super(GenericCrystalOfSpins, self).digraph() self._digraph_closure = self.digraph().transitive_closure()
def __init__(self, R): """ Initialize ``self``. EXAMPLES:: sage: NCSymD1 = SymmetricFunctionsNonCommutingVariablesDual(FiniteField(23)) sage: NCSymD2 = SymmetricFunctionsNonCommutingVariablesDual(Integers(23)) sage: TestSuite(SymmetricFunctionsNonCommutingVariables(QQ).dual()).run() """ # change the line below to assert(R in Rings()) once MRO issues from #15536, #15475 are resolved assert(R in Fields() or R in Rings()) # side effect of this statement assures MRO exists for R self._base = R # Won't be needed once CategoryObject won't override base_ring category = GradedHopfAlgebras(R) # TODO: .Commutative() Parent.__init__(self, category=category.WithRealizations()) # Bases w = self.w() # Embedding of Sym in the homogeneous bases into DNCSym in the w basis Sym = SymmetricFunctions(self.base_ring()) Sym_h_to_w = Sym.h().module_morphism(w.sum_of_partitions, triangular='lower', inverse_on_support=w._set_par_to_par, codomain=w, category=category) Sym_h_to_w.register_as_coercion() self.to_symmetric_function = Sym_h_to_w.section()
def __init__(self, set, function, name=None): """ TESTS:: sage: from sage.sets.family import LazyFamily sage: f = LazyFamily([3,4,7], lambda i: 2*i); f Lazy family (<lambda>(i))_{i in [3, 4, 7]} sage: TestSuite(f).run() # __contains__ is not implemented Failure ... The following tests failed: _test_an_element, _test_enumerated_set_contains, _test_some_elements Check for bug #5538:: sage: l = [3,4,7] sage: f = LazyFamily(l, lambda i: 2*i); sage: l[1] = 18 sage: f Lazy family (<lambda>(i))_{i in [3, 4, 7]} """ from sage.combinat.combinat import CombinatorialClass # workaround #12482 if set in FiniteEnumeratedSets(): category = FiniteEnumeratedSets() elif set in InfiniteEnumeratedSets(): category = InfiniteEnumeratedSets() elif isinstance(set, (list, tuple, CombinatorialClass)): category = FiniteEnumeratedSets() else: category = EnumeratedSets() Parent.__init__(self, category = category) from copy import copy self.set = copy(set) self.function = function self.function_name = name
def __init__(self, sets, category, flatten=False): r""" INPUT: - ``sets`` -- a tuple of parents - ``category`` -- a subcategory of ``Sets().CartesianProducts()`` - ``flatten`` -- a boolean (default: ``False``) ``flatten`` is current ignored, and reserved for future use. No other keyword arguments (``kwargs``) are accepted. TESTS:: sage: from sage.sets.cartesian_product import CartesianProduct sage: C = CartesianProduct((QQ, ZZ, ZZ), category = Sets().CartesianProducts()) sage: C The Cartesian product of (Rational Field, Integer Ring, Integer Ring) sage: C.an_element() (1/2, 1, 1) sage: TestSuite(C).run() sage: cartesian_product([ZZ, ZZ], blub=None) Traceback (most recent call last): ... TypeError: __init__() got an unexpected keyword argument 'blub' """ self._sets = tuple(sets) Parent.__init__(self, category=category)
def __init__(self, begin, end, step=Integer(1), middle_point=Integer(1)): r""" TESTS:: sage: from sage.sets.integer_range import IntegerRangeFromMiddle sage: I = IntegerRangeFromMiddle(-100,100,10,0) sage: I.category() Category of facade finite enumerated sets sage: TestSuite(I).run() sage: I = IntegerRangeFromMiddle(Infinity,-Infinity,-37,0) sage: I.category() Category of facade infinite enumerated sets sage: TestSuite(I).run() sage: IntegerRange(0, 5, 1, -3) Traceback (most recent call last): ... ValueError: middle_point is not in the interval """ self._begin = begin self._end = end self._step = step self._middle_point = middle_point if not middle_point in self: raise ValueError("middle_point is not in the interval") if (begin != Infinity and begin != -Infinity) and \ (end != Infinity and end != -Infinity): Parent.__init__(self, facade = IntegerRing(), category = FiniteEnumeratedSets()) else: Parent.__init__(self, facade = IntegerRing(), category = InfiniteEnumeratedSets())
def __init__(self, wt, WLR): r""" Initialize ``self``. EXAMPLES:: sage: La = RootSystem(['A', 2]).weight_lattice().fundamental_weights() sage: RC = crystals.RiggedConfigurations(La[1] + La[2]) sage: TestSuite(RC).run() sage: La = RootSystem(['A', 2, 1]).weight_lattice().fundamental_weights() sage: RC = crystals.RiggedConfigurations(La[0]) sage: TestSuite(RC).run() # long time """ self._cartan_type = WLR.cartan_type() self._wt = wt self._rc_index = self._cartan_type.index_set() # We store the cartan matrix for the vacancy number calculations for speed self._cartan_matrix = self._cartan_type.cartan_matrix() if self._cartan_type.is_finite(): category = ClassicalCrystals() else: category = (RegularCrystals(), HighestWeightCrystals(), InfiniteEnumeratedSets()) Parent.__init__(self, category=category) n = self._cartan_type.rank() #== len(self._cartan_type.index_set()) self.module_generators = (self.element_class( self, partition_list=[[] for i in range(n)] ),)
def __init__(self, category = None): r""" This quotient of the left zero semigroup of integers obtained by setting `x=42` for any `x\geq 42`. EXAMPLES:: sage: S = Semigroups().Subquotients().example(); S An example of a (sub)quotient semigroup: a quotient of the left zero semigroup sage: S.ambient() An example of a semigroup: the left zero semigroup sage: S(100) 42 sage: S(100) == S(42) True sage: S(1)*S(2) == S(1) True TESTS:: sage: TestSuite(S).run() """ if category is None: category = Semigroups().Quotients() Parent.__init__(self, category = category)
def __init__(self, G, V, trivial_action = False): self._group = G self._coeffmodule = V self._trivial_action = trivial_action self._gen_pows = [] self._gen_pows_neg = [] if trivial_action: self._acting_matrix = lambda x, y: matrix(V.base_ring(),V.dimension(),V.dimension(),1) gens_local = [ (None, None) for g in G.gens() ] else: def acting_matrix(x,y): try: return V.acting_matrix(x,y) except: return V.acting_matrix(G.embed(x.quaternion_rep,V.base_ring().precision_cap()), y) self._acting_matrix = acting_matrix gens_local = [ (g, g**-1) for g in G.gens() ] onemat = G(1) try: dim = V.dimension() except AttributeError: dim = len(V.basis()) one = Matrix(V.base_ring(),dim,dim,1) for g, ginv in gens_local: A = self._acting_matrix(g, dim) self._gen_pows.append([one, A]) Ainv = self._acting_matrix(ginv, dim) self._gen_pows_neg.append([one, Ainv]) Parent.__init__(self) return
def __init__(self, cartan_type, B, biject_class): r""" Initialize all common elements for rigged configurations. INPUT: - ``cartan_type`` -- The Cartan type - ``B`` -- A list of dimensions `[r,s]` for rectangles of height `r` and width `s` - ``biject_class`` -- The class the bijection creates TESTS:: sage: RC = HighestWeightRiggedConfigurations(['A', 3, 1], [[3, 2], [1, 2], [1, 1]]) # indirect doctest sage: RC Highest weight rigged configurations of type ['A', 3, 1] and factors ((3, 2), (1, 2), (1, 1)) sage: RC = RiggedConfigurations(['A', 3, 1], [[3, 2], [1, 2], [1, 1]]) # indirect doctest sage: RC Rigged configurations of type ['A', 3, 1] and factors ((3, 2), (1, 2), (1, 1)) """ assert cartan_type.is_affine() self._affine_ct = cartan_type # Force to classical since we do not have e_0 and f_0 yet self._cartan_type = cartan_type.classical() self.dims = B self._bijection_class = biject_class self.rename("Rigged configurations of type %s and factors %s" % (cartan_type, B)) Parent.__init__(self, category=FiniteCrystals())
def __init__(self, crystals, **options): """ TESTS:: sage: from sage.combinat.crystals.tensor_product import FullTensorProductOfCrystals sage: C = CrystalOfLetters(['A',2]) sage: T = TensorProductOfCrystals(C,C) sage: isinstance(T, FullTensorProductOfCrystals) True sage: TestSuite(T).run() """ crystals = list(crystals) category = Category.meet([crystal.category() for crystal in crystals]) Parent.__init__(self, category = category) self.rename("Full tensor product of the crystals %s"%(crystals,)) self.crystals = crystals if options.has_key('cartan_type'): self._cartan_type = CartanType(options['cartan_type']) else: if len(crystals) == 0: raise ValueError, "you need to specify the Cartan type if the tensor product list is empty" else: self._cartan_type = crystals[0].cartan_type() self.cartesian_product = CartesianProduct(*self.crystals) self.module_generators = self
def __init__(self): """ TESTS:: sage: P = Sets().example("inherits") """ Parent.__init__(self, facade = IntegerRing(), category = Sets())
def __init__(self, cartan_type, classical_crystal, category = None): """ Input is an affine Cartan type 'cartan_type', a classical crystal 'classical_crystal', and automorphism and its inverse 'automorphism' and 'inverse_automorphism', and the Dynkin node 'dynkin_node' EXAMPLES:: sage: n = 1 sage: C = CrystalOfTableaux(['A',n],shape=[1]) sage: pr = attrcall("promotion") sage: pr_inverse = attrcall("promotion_inverse") sage: A = AffineCrystalFromClassicalAndPromotion(['A',n,1],C,pr,pr_inverse,1) # indirect doctest sage: A.list() [[[1]], [[2]]] sage: A.cartan_type() ['A', 1, 1] sage: A.index_set() (0, 1) Note: AffineCrystalFromClassical is an abstract class, so we can't test it directly. TESTS:: sage: TestSuite(A).run() """ if category is None: category = (RegularCrystals(), FiniteCrystals()) self._cartan_type = cartan_type Parent.__init__(self, category = category) self.classical_crystal = classical_crystal; self.module_generators = map( self.retract, self.classical_crystal.module_generators ) self.element_class._latex_ = lambda x: x.lift()._latex_()
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
def __init__(self, indices, prefix, category=None, names=None, **kwds): """ Initialize ``self``. EXAMPLES:: sage: F = FreeMonoid(index_set=ZZ) sage: TestSuite(F).run() sage: F = FreeMonoid(index_set=tuple('abcde')) sage: TestSuite(F).run() sage: F = FreeAbelianMonoid(index_set=ZZ) sage: TestSuite(F).run() sage: F = FreeAbelianMonoid(index_set=tuple('abcde')) sage: TestSuite(F).run() """ self._indices = indices category = Monoids().or_subcategory(category) if indices.cardinality() == 0: category = category.Finite() else: category = category.Infinite() Parent.__init__(self, names=names, category=category) # ignore the optional 'key' since it only affects CachedRepresentation kwds.pop("key", None) IndexedGenerators.__init__(self, indices, prefix, **kwds)
def __init__(self, m, n): """ 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 = ZZ(m) self._n = ZZ(n) self._C = IntegerModRing(self._m) self._P = Permutations(self._n) if self._m == 1 or self._m == 2: from sage.categories.finite_coxeter_groups import FiniteCoxeterGroups category = FiniteCoxeterGroups().Irreducible() else: from sage.categories.complex_reflection_groups import ComplexReflectionGroups category = ComplexReflectionGroups().Finite().Irreducible().WellGenerated() Parent.__init__(self, category=category)
def __init__(self, f, args=None, kwds=None, name=None, category=None, cache=False): """ TESTS:: sage: from sage.sets.set_from_iterator import EnumeratedSetFromIterator sage: S = EnumeratedSetFromIterator(xsrange, (1,200,-1), category=FiniteEnumeratedSets()) sage: TestSuite(S).run() """ if category is not None: Parent.__init__(self, facade = True, category = category) else: Parent.__init__(self, facade = True, category = EnumeratedSets()) if name is not None: self.rename(name) self._func = f if args is not None: self._args = args if kwds is not None: self._kwds = kwds if cache: self._cache = lazy_list(iter(self._func( *getattr(self, '_args', ()), **getattr(self, '_kwds', {}))))
def __init__(self, crystals, **options): """ TESTS:: sage: from sage.combinat.crystals.tensor_product import FullTensorProductOfCrystals sage: C = crystals.Letters(['A',2]) sage: T = crystals.TensorProduct(C,C) sage: isinstance(T, FullTensorProductOfCrystals) True sage: TestSuite(T).run() """ category = Category.meet([crystal.category() for crystal in crystals]) category = category.TensorProducts() if any(c in Sets().Infinite() for c in crystals): category = category.Infinite() Parent.__init__(self, category=category) self.crystals = crystals if 'cartan_type' in options: self._cartan_type = CartanType(options['cartan_type']) else: if not crystals: raise ValueError("you need to specify the Cartan type if the tensor product list is empty") else: self._cartan_type = crystals[0].cartan_type() self.cartesian_product = cartesian_product(self.crystals) self.module_generators = self
def __init__(self, base, parent_approximation, models=None, exact=Infinity, category=None, element_constructor=None, gens=None, names=None, normalize=True, facade=None): Parent.__init__(self,base,category=category,element_constructor=element_constructor, gens=gens, names=names, normalize=normalize, facade=facade) self._approximation = parent_approximation self._precision = ParentBigOh(self) if models is None: dimension = self.dimension() if dimension == 1: self._precision.add_model(ValuationBigOh) else: if self.dimension() < Infinity: self._precision.add_model(FlatBigOh) self._precision.add_model(JaggedBigOh) try: if self.indices_basis() is None: self._precision.add_model(FlatIntervalBigOh) self._precision.add_modelconversion(FlatIntervalBigOh,JaggedBigOh) except NotImplementedError: pass self._precision.add_modelconversion(FlatBigOh,JaggedBigOh,safemode=True) self._precision.add_modelconversion(FlatBigOh,FlatIntervalBigOh,safemode=True) else: for model in models.vertices(): self._precision.add_model(model) for (mfrom,mto,map) in models.edges(): self._precision.add_modelconversion(mfrom,mto,map) try: self._exact_precision = self._precision(exact) except PrecisionError: self._exact_precision = ExactBigOh(self._precision)
def __init__(self, space, name, short_name, bounded, conformal, dimension, isometry_group, isometry_group_is_projective): """ Initialize ``self``. EXAMPLES:: sage: UHP = HyperbolicPlane().UHP() sage: TestSuite(UHP).run() sage: PD = HyperbolicPlane().PD() sage: TestSuite(PD).run() sage: KM = HyperbolicPlane().KM() sage: TestSuite(KM).run() sage: HM = HyperbolicPlane().HM() sage: TestSuite(HM).run() """ self._name = name self._short_name = short_name self._bounded = bounded self._conformal = conformal self._dimension = dimension self._isometry_group = isometry_group self._isometry_group_is_projective = isometry_group_is_projective from sage.geometry.hyperbolic_space.hyperbolic_interface import HyperbolicModels Parent.__init__(self, category=HyperbolicModels(space))
def __init__(self, n, R, var='a', category = None): """ INPUT: - ``n`` - the degree - ``R`` - the base ring - ``var`` - variable used to define field of definition of actual matrices in this group. """ if not is_Ring(R): raise TypeError, "R (=%s) must be a ring"%R self._var = var self.__n = integer.Integer(n) if self.__n <= 0: raise ValueError, "The degree must be at least 1" self.__R = R if self.base_ring().is_finite(): default_category = FiniteGroups() else: # Should we ask GAP whether the group is finite? default_category = Groups() if category is None: category = default_category else: assert category.is_subcategory(default_category), \ "%s is not a subcategory of %s"%(category, default_category) Parent.__init__(self, category = category)
def __init__(self, X): """ Create a Set_object This function is called by the Set function; users shouldn't call this directly. EXAMPLES:: sage: type(Set(QQ)) <class 'sage.sets.set.Set_object_with_category'> TESTS:: sage: _a, _b = get_coercion_model().canonical_coercion(Set([0]), 0) Traceback (most recent call last): ... TypeError: no common canonical parent for objects with parents: '<class 'sage.sets.set.Set_object_enumerated_with_category'>' and 'Integer Ring' """ from sage.rings.integer import is_Integer if isinstance(X, (int,long)) or is_Integer(X): # The coercion model will try to call Set_object(0) raise ValueError('underlying object cannot be an integer') Parent.__init__(self, category=Sets()) self.__object = X
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
def __init__(self, linear_tensor_parent): """ The Python constructor INPUT: - ``linear_tensor_parent`` -- instance of :class:`LinearTensorParent_class`. TESTS:: sage: from sage.numerical.linear_functions import LinearFunctionsParent sage: LF = LinearFunctionsParent(RDF) sage: from sage.numerical.linear_tensor import LinearTensorParent sage: LT = LinearTensorParent(RDF^2, LF) sage: from sage.numerical.linear_tensor_constraints import LinearTensorConstraintsParent sage: LinearTensorConstraintsParent(LT) Linear constraints in the tensor product of Vector space of dimension 2 over Real Double Field and Linear functions over Real Double Field """ Parent.__init__(self) self._LT = linear_tensor_parent self._LF = linear_tensor_parent.linear_functions()
def __init__(self, roots=None, children=None, post_process=None, algorithm='depth', facade=None, category=None): r""" TESTS:: sage: S = SearchForest(NN, lambda x : [], lambda x: x^2 if x.is_prime() else None) sage: S.category() Category of enumerated sets """ if roots is not None: self._roots = roots if children is not None: self.children = children if post_process is not None: self.post_process = post_process self._algorithm = algorithm Parent.__init__(self, facade=facade, category=EnumeratedSets().or_subcategory(category))
def __init__(self, ct, shape): r""" Initialize ``self``. TESTS:: sage: T = crystals.Tableaux(['A', [1,1]], shape = [2,1]); T Crystal of BKK tableaux of shape [2, 1] of gl(2|2) sage: TestSuite(T).run() """ self._shape = shape self._cartan_type = ct m = ct.m + 1 C = CrystalOfBKKLetters(ct) tr = shape.conjugate() mg = [] for i, col_len in enumerate(tr): for j in range(col_len - m): mg.append(C(i + 1)) for j in range(max(0, m - col_len), m): mg.append(C(-j - 1)) mg = list(reversed(mg)) Parent.__init__(self, category=RegularSuperCrystals()) self.module_generators = (self.element_class(self, mg), )
def __init__(self, ambient, contained, generators, cartan_type, index_set, category): """ Initialize ``self``. EXAMPLES:: sage: B = crystals.Tableaux(['A',4], shape=[2,1]) sage: S = B.subcrystal(generators=(B(2,1,1), B(5,2,4)), index_set=[1,2]) sage: TestSuite(S).run() """ self._ambient = ambient self._contained = contained self._cardinality = None # ``None`` means currently unknown self._cartan_type = cartan_type self._index_set = tuple(index_set) Parent.__init__(self, category=category) self.module_generators = tuple( self.element_class(self, g) for g in generators if self._containing(g)) if isinstance(contained, frozenset): self._cardinality = Integer(len(contained)) self._list = [self.element_class(self, x) for x in contained]
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, )
def __init__(self, set, function, name=None): """ TESTS:: sage: from sage.sets.family import LazyFamily sage: f = LazyFamily([3,4,7], lambda i: 2*i); f Lazy family (<lambda>(i))_{i in [3, 4, 7]} sage: TestSuite(f).run() # __contains__ is not implemented Failure ... The following tests failed: _test_an_element, _test_enumerated_set_contains, _test_some_elements Check for bug #5538:: sage: l = [3,4,7] sage: f = LazyFamily(l, lambda i: 2*i); sage: l[1] = 18 sage: f Lazy family (<lambda>(i))_{i in [3, 4, 7]} """ from sage.combinat.combinat import CombinatorialClass # workaround #12482 if set in FiniteEnumeratedSets(): category = FiniteEnumeratedSets() elif set in InfiniteEnumeratedSets(): category = InfiniteEnumeratedSets() elif isinstance(set, (list, tuple, CombinatorialClass)): category = FiniteEnumeratedSets() else: category = EnumeratedSets() Parent.__init__(self, category=category) if name is not None: warn(name_warn_message) from copy import copy self.set = copy(set) self.function = function
def __init__(self, R, element_class=fraction_field_element.FractionFieldElement, category=QuotientFields()): """ Create the fraction field of the integral domain ``R``. INPUT: - ``R`` -- an integral domain EXAMPLES:: sage: Frac(QQ['x']) Fraction Field of Univariate Polynomial Ring in x over Rational Field sage: Frac(QQ['x,y']).variable_names() ('x', 'y') sage: category(Frac(QQ['x'])) Category of quotient fields """ self._R = R self._element_class = element_class self._element_init_pass_parent = False Parent.__init__(self, base=R, names=R._names, category=category)
def __init__(self, cartan_type, starting_weight): """ EXAMPLES:: sage: C = CrystalOfLSPaths(['A',2,1],[-1,0,1]); C The crystal of LS paths of type ['A', 2, 1] and weight (-1, 0, 1) sage: C.R Root system of type ['A', 2, 1] sage: C.weight -Lambda[0] + Lambda[2] sage: C.weight.parent() Extended weight space over the Rational Field of the Root system of type ['A', 2, 1] sage: C.module_generators [(-Lambda[0] + Lambda[2],)] """ self._cartan_type = CartanType(cartan_type) self.R = RootSystem(cartan_type) self._name = "The crystal of LS paths of type %s and weight %s" % ( cartan_type, starting_weight) if self._cartan_type.is_affine(): self.extended = True if all(i >= 0 for i in starting_weight): Parent.__init__(self, category=HighestWeightCrystals()) else: Parent.__init__(self, category=Crystals()) else: self.extended = False Parent.__init__(self, category=FiniteCrystals()) Lambda = self.R.weight_space(extended=self.extended).basis() offset = self.R.index_set()[Integer(0)] zero_weight = self.R.weight_space(extended=self.extended).zero() self.weight = sum([zero_weight] + [ starting_weight[j - offset] * Lambda[j] for j in self.R.index_set() ]) if self.weight == zero_weight: initial_element = self(tuple([])) else: initial_element = self(tuple([self.weight])) self.module_generators = [initial_element]
def __init__(self, family, facade=True, keepkey=False): """ 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 # try to guess if the result is infinite or not. if self._family.cardinality() == Infinity: Parent.__init__(self, category=InfiniteEnumeratedSets()) elif self._family.last().cardinality() == Infinity: Parent.__init__(self, category=InfiniteEnumeratedSets()) else: Parent.__init__(self, category=FiniteEnumeratedSets())
def __init__(self, ct, shape, format): """ EXAMPLES:: sage: C = crystals.FastRankTwo(['A',2],shape=[4,1]); C The fast crystal for A2 with shape [4,1] sage: TestSuite(C).run() """ Parent.__init__(self, category = ClassicalCrystals()) # super(FastCrystal, self).__init__(category = FiniteEnumeratedSets()) self._cartan_type = ct if ct[1] != 2: raise NotImplementedError l1 = shape[0] l2 = shape[1] # For safety, delpat and gampat should be immutable self.delpat = [] self.gampat = [] if ct[0] == 'A': self._type_a_init(l1, l2) elif ct[0] == 'B' or ct[0] == 'C': self._type_bc_init(l1, l2) else: raise NotImplementedError self.format = format self.size = len(self.delpat) self._rootoperators = [] self.shape = shape for i in range(self.size): target = [x for x in self.delpat[i]] target[0] = target[0]-1 e1 = None if target not in self.delpat else self.delpat.index(target) target[0] = target[0]+1+1 f1 = None if target not in self.delpat else self.delpat.index(target) target = [x for x in self.gampat[i]] target[0] = target[0]-1 e2 = None if target not in self.gampat else self.gampat.index(target) target[0] = target[0]+1+1 f2 = None if target not in self.gampat else self.gampat.index(target) self._rootoperators.append([e1,f1,e2,f2]) if int(2*l1)%2 == 0: l1_str = "%d"%l1 l2_str = "%d"%l2 else: assert self._cartan_type[0] == 'B' and int(2*l2)%2 == 1 l1_str = "%d/2"%int(2*l1) l2_str = "%d/2"%int(2*l2) self.rename("The fast crystal for %s2 with shape [%s,%s]"%(ct[0],l1_str,l2_str)) self.module_generators = [self(0)] # self._list = ClassicalCrystal.list(self) self._list = super(FastCrystal, self).list() # self._digraph = ClassicalCrystal.digraph(self) self._digraph = super(FastCrystal, self).digraph() self._digraph_closure = self.digraph().transitive_closure()
def __init__(self, q, level, info_magma=None, grouptype=None, magma=None, compute_presentation=True): from sage.modular.arithgroup.congroup_gamma import Gamma_constructor assert grouptype in ['SL2', 'PSL2'] self._grouptype = grouptype self._compute_presentation = compute_presentation self.magma = magma self.F = QQ self.q = ZZ(q) self.discriminant = ZZ(1) self.level = ZZ(level / self.q) if self.level != 1 and compute_presentation: raise NotImplementedError self._Gamma = Gamma_constructor(self.q) self._Gamma_farey = self._Gamma.farey_symbol() self.F_units = [] self._prec_inf = -1 self.B = MatrixSpace(QQ, 2, 2) # Here we initialize the non-split Cartan, properly self.GFq = FiniteField(self.q) if not self.GFq(-1).is_square(): self.eps = ZZ(-1) else: self.eps = ZZ(2) while self.GFq(self.eps).is_square(): self.eps += 1 epsinv = (self.GFq(self.eps)**-1).lift() N = self.level q = self.q self.Obasis = [ matrix(ZZ, 2, 2, v) for v in [[1, 0, 0, 1], [0, q, 0, 0], [0, N * epsinv, N, 0], [0, 0, 0, q]] ] x = QQ['x'].gen() K = FiniteField(self.q**2, 'z', modulus=x * x - self.eps) x = K.primitive_element() x1 = x while x1.multiplicative_order() != self.q + 1 or x1.norm() != 1: x1 *= x a, b = x1.polynomial().list() # represents a+b*sqrt(eps) a = a.lift() b = b.lift() self.extra_matrix = self.B( lift(matrix(ZZ, 2, 2, [a, b, b * self.eps, a]), self.q)) self.extra_matrix_inverse = ~self.extra_matrix if compute_presentation: self.Ugens = [] self._gens = [] temp_relation_words = [] I = SL2Z([1, 0, 0, 1]) E = SL2Z([-1, 0, 0, -1]) minus_one = [] for i, g in enumerate(self._Gamma_farey.generators()): newg = self.B([g.a(), g.b(), g.c(), g.d()]) if newg == I: continue self.Ugens.append(newg) self._gens.append( self.element_class(self, quaternion_rep=newg, word_rep=[i + 1], check=False)) if g.matrix()**2 == I.matrix(): temp_relation_words.append([i + 1, i + 1]) if minus_one is not None: temp_relation_words.append([-i - 1] + minus_one) else: minus_one = [i + 1] elif g.matrix()**2 == E.matrix(): temp_relation_words.append([i + 1, i + 1, i + 1, i + 1]) if minus_one is not None: temp_relation_words.append([-i - 1, -i - 1] + minus_one) else: minus_one = [i + 1, i + 1] elif g.matrix()**3 == I.matrix(): temp_relation_words.append([i + 1, i + 1, i + 1]) elif g.matrix()**3 == E.matrix(): temp_relation_words.append( [i + 1, i + 1, i + 1, i + 1, i + 1, i + 1]) if minus_one is not None: temp_relation_words.append([-i - 1, -i - 1, -i - 1] + minus_one) else: minus_one = [i + 1, i + 1, i + 1] else: assert g.matrix()**24 != I.matrix() # The extra matrix is added i = len(self.Ugens) self.extra_matrix_index = i self.Ugens.append(self.extra_matrix) self._gens.append( self.element_class(self, quaternion_rep=self.Ugens[i], word_rep=[i + 1], check=False)) # The new relations are also added w = self._get_word_rep_initial(self.extra_matrix**(self.q + 1)) temp_relation_words.append(w + ([-i - 1] * (self.q + 1))) for j, g in enumerate(self.Ugens[:-1]): g1 = self.extra_matrix_inverse * g * self.extra_matrix w = self._get_word_rep_initial(g1) new_rel = w + [-i - 1, -j - 1, i + 1] temp_relation_words.append(new_rel) self.F_unit_offset = len(self.Ugens) if minus_one is not None: self.minus_one_long = syllables_to_tietze(minus_one) self._relation_words = [] for rel in temp_relation_words: sign = multiply_out(rel, self.Ugens, self.B(1)) if sign == self.B(1) or 'P' in grouptype: self._relation_words.append(rel) else: assert sign == self.B(-1) newrel = rel + self.minus_one sign = multiply_out(newrel, self.Ugens, self.B(1)) assert sign == self.B(1) self._relation_words.append(newrel) ArithGroup_generic.__init__(self) Parent.__init__(self)
def __init__(self, gap_handle, category=Sets()): Parent.__init__(self, category=category.GAP()) GAPObject.__init__(self, gap_handle)
def __init__(self, X, RR): if not is_ProbabilitySpace(X): raise TypeError("Argument X (= %s) must be a probability space" % X) Parent.__init__(self, X) self._codomain = RR
def __init__(self, cartan_type, prefix, finite=True): r""" EXAMPLES:: sage: from sage.combinat.root_system.fundamental_group import FundamentalGroupOfExtendedAffineWeylGroup sage: F = FundamentalGroupOfExtendedAffineWeylGroup(['A',3,1]) sage: F in Groups().Commutative().Finite() True sage: TestSuite(F).run() """ def leading_support(beta): r""" Given a dictionary with one key, return this key """ supp = beta.support() assert len(supp) == 1 return supp[0] self._cartan_type = cartan_type self._prefix = prefix special_node = cartan_type.special_node() self._special_nodes = cartan_type.special_nodes() # initialize dictionaries with the entries for the # distinguished special node # dictionary of inverse elements inverse_dict = {} inverse_dict[special_node] = special_node # dictionary for the action of special automorphisms by # permutations of the affine Dynkin nodes auto_dict = {} for i in cartan_type.index_set(): auto_dict[special_node, i] = i # dictionary for the finite Weyl component of the special automorphisms reduced_words_dict = {} reduced_words_dict[0] = tuple([]) if cartan_type.dual().is_untwisted_affine(): # this combines the computations for an untwisted affine # type and its affine dual cartan_type = cartan_type.dual() if cartan_type.is_untwisted_affine(): cartan_type_classical = cartan_type.classical() I = [i for i in cartan_type_classical.index_set()] Q = RootSystem(cartan_type_classical).root_lattice() alpha = Q.simple_roots() omega = RootSystem( cartan_type_classical).weight_lattice().fundamental_weights() W = Q.weyl_group(prefix="s") for i in self._special_nodes: if i == special_node: continue antidominant_weight, reduced_word = omega[ i].to_dominant_chamber(reduced_word=True, positive=False) reduced_words_dict[i] = tuple(reduced_word) w0i = W.from_reduced_word(reduced_word) idual = leading_support(-antidominant_weight) inverse_dict[i] = idual auto_dict[i, special_node] = i for j in I: if j == idual: auto_dict[i, j] = special_node else: auto_dict[i, j] = leading_support(w0i.action(alpha[j])) self._action = Family( self._special_nodes, lambda i: Family(cartan_type.index_set(), lambda j: auto_dict[i, j])) self._dual_node = Family(self._special_nodes, inverse_dict.__getitem__) self._reduced_words = Family(self._special_nodes, reduced_words_dict.__getitem__) if finite: cat = Category.join( (Groups().Commutative().Finite(), EnumeratedSets())) else: cat = Groups().Commutative().Infinite() Parent.__init__(self, category=cat)
def __init__(self, R, S): r""" EXAMPLES:: sage: from sage.categories.examples.with_realizations import SubsetAlgebra sage: A = SubsetAlgebra(QQ, Set((1,2,3))); A The subset algebra of {1, 2, 3} over Rational Field sage: Sets().WithRealizations().example() is A True sage: TestSuite(A).run() TESTS:: sage: A = Sets().WithRealizations().example(); A The subset algebra of {1, 2, 3} over Rational Field sage: F, In, Out = A.realizations() sage: type(F.coerce_map_from(In)) <class 'sage.categories.modules_with_basis.TriangularModuleMorphism'> sage: type(In.coerce_map_from(F)) <class 'sage.categories.modules_with_basis.TriangularModuleMorphism'> sage: type(F.coerce_map_from(Out)) <class 'sage.categories.modules_with_basis.TriangularModuleMorphism'> sage: type(Out.coerce_map_from(F)) <class 'sage.categories.modules_with_basis.TriangularModuleMorphism'> sage: In.coerce_map_from(Out) Composite map: From: The subset algebra of {1, 2, 3} over Rational Field in the Out basis To: The subset algebra of {1, 2, 3} over Rational Field in the In basis Defn: Generic morphism: From: The subset algebra of {1, 2, 3} over Rational Field in the Out basis To: The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis then Generic morphism: From: The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis To: The subset algebra of {1, 2, 3} over Rational Field in the In basis sage: Out.coerce_map_from(In) Composite map: From: The subset algebra of {1, 2, 3} over Rational Field in the In basis To: The subset algebra of {1, 2, 3} over Rational Field in the Out basis Defn: Generic morphism: From: The subset algebra of {1, 2, 3} over Rational Field in the In basis To: The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis then Generic morphism: From: The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis To: The subset algebra of {1, 2, 3} over Rational Field in the Out basis """ assert (R in Rings()) self._base = R # Won't be needed when CategoryObject won't override anymore base_ring self._S = S Parent.__init__(self, category=Algebras(R).WithRealizations()) # Initializes the bases and change of bases of ``self`` category = self.Bases() F = self.F() In = self.In() Out = self.Out() In_to_F = In.module_morphism(F.sum_of_monomials * Subsets, codomain=F, category=category, triangular='upper', unitriangular=True, cmp=self.indices_cmp) In_to_F.register_as_coercion() (~In_to_F).register_as_coercion() F_to_Out = F.module_morphism(Out.sum_of_monomials * self.supsets, codomain=Out, category=category, triangular='lower', unitriangular=True, cmp=self.indices_cmp) F_to_Out.register_as_coercion() (~F_to_Out).register_as_coercion()
def __init__(self, cartan_type, B): r""" Construct a Kleber tree. INPUT: - ``cartan_type`` -- The Cartan type. - ``B`` -- A list of dimensions of rectangles by `[r, c]` where `r` is the number of rows and `c` is the number of columns. EXAMPLES:: sage: KT = KleberTree(['D', 3], [[1,1], [1,1]]); KT Kleber tree of Cartan type ['D', 3] and root weight [2, 0, 0] sage: TestSuite(KT).run(skip="_test_elements") """ Parent.__init__(self, category=FiniteEnumeratedSets()) self._cartan_type = cartan_type self.dims = B n = self._cartan_type.n # Create an empty node at first step self.root = KleberTreeNode( self, self._cartan_type.root_system().weight_space().zero(), self._cartan_type.root_system().root_space().zero()) full_list = [self.root] # The list of tree nodes # Convert the B values into an L matrix L = [] for i in range(0, n): L.append([0]) for dim in B: while len(L[0]) < dim[1]: # Add more columns if needed for row in L: row.append(0) L[dim[0] - 1][dim[1] - 1] += 1 # The -1 is b/c of indexing # Perform a special case of the algorithm for the root node weight_basis = self._cartan_type.root_system().weight_space().basis() for a in range(n): self.root.weight += sum( L[a]) * weight_basis[a + 1] # Add 1 for indexing new_children = [] for new_child in self._children_root_iter(): new_children.append(new_child) self.root.children.append(new_child) full_list.append(new_child) depth = 1 growth = True while growth: growth = False depth += 1 leaves = new_children new_children = [] if depth <= len(L[0]): for x in full_list: growth = True for a in range(n): for i in range(depth - 1, len(L[a])): # Subtract 1 for indexing x.weight += L[a][i] * weight_basis[ a + 1] # Add 1 for indexing if x in leaves: for new_child in self._children_iter(x): new_children.append(new_child) else: for x in leaves: for new_child in self._children_iter(x): new_children.append(new_child) # Connect the new children into the tree if len(new_children) > 0: growth = True for new_child in new_children: new_child.parent_node.children.append(new_child) full_list.append(new_child) self._set = full_list
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())
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)
def __init__(self, jmonoid): assert (jmonoid in Monoids().JTrivial().Finite()) self.jmonoid = jmonoid Parent.__init__(self, category=Semigroups().Finite())
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)
def __init__(self, X, Y, category=None, base=None, check=True): r""" TESTS:: sage: X = ZZ['x']; X.rename("X") sage: Y = ZZ['y']; Y.rename("Y") sage: class MyHomset(Homset): ....: def my_function(self, x): ....: return Y(x[0]) ....: def _an_element_(self): ....: return sage.categories.morphism.SetMorphism(self, self.my_function) sage: import __main__; __main__.MyHomset = MyHomset # fakes MyHomset being defined in a Python module sage: H = MyHomset(X, Y, category=Monoids(), base = ZZ) sage: H Set of Morphisms from X to Y in Category of monoids sage: TestSuite(H).run() sage: H = MyHomset(X, Y, category=1, base = ZZ) Traceback (most recent call last): ... TypeError: category (=1) must be a category sage: H Set of Morphisms from X to Y in Category of monoids sage: TestSuite(H).run() sage: H = MyHomset(X, Y, category=1, base = ZZ, check = False) Traceback (most recent call last): ... AttributeError: 'sage.rings.integer.Integer' object has no attribute 'Homsets' sage: P.<t> = ZZ[] sage: f = P.hom([1/2*t]) sage: f.parent().domain() Univariate Polynomial Ring in t over Integer Ring sage: f.domain() is f.parent().domain() True Test that ``base_ring`` is initialized properly:: sage: R = QQ['x'] sage: Hom(R, R).base_ring() Rational Field sage: Hom(R, R, category=Sets()).base_ring() sage: Hom(R, R, category=Modules(QQ)).base_ring() Rational Field sage: Hom(QQ^3, QQ^3, category=Modules(QQ)).base_ring() Rational Field For whatever it's worth, the ``base`` arguments takes precedence:: sage: MyHomset(ZZ^3, ZZ^3, base = QQ).base_ring() Rational Field """ self._domain = X self._codomain = Y if category is None: category = X.category() self.__category = category if check: if not isinstance(category, Category): raise TypeError("category (=%s) must be a category" % category) #if not X in category: # raise TypeError, "X (=%s) must be in category (=%s)"%(X, category) #if not Y in category: # raise TypeError, "Y (=%s) must be in category (=%s)"%(Y, category) if base is None and hasattr(category, "WithBasis"): # The above is a lame but fast check that category is a # subcategory of Modules(...). That will do until # CategoryObject.base_ring will be gone and not prevent # anymore from implementing base_ring in Modules.Homsets.ParentMethods. # See also #15801. base = X.base_ring() Parent.__init__( self, base=base, category=category.Endsets() if X is Y else category.Homsets())
def __init__(self, base, x,prec): self.__monoid=GeneralizedSeriesMonoid(base,x) self.Element = ContinuousGeneralizedSeriesMult self.__prec=NN(prec) Parent.__init__(self, base=base, names=(x,), category=Rings())
def __init__(self, is_finite=False): if is_finite is None: is_finite = self.cardinality() < Infinity cat = FiniteEnumeratedSets() if is_finite else InfiniteEnumeratedSets() Parent.__init__(self, category=(cat, YacopGradedSets()))
def __init__(self, starting_weight, starting_weight_parent): """ EXAMPLES:: sage: C = crystals.LSPaths(['A',2,1],[-1,0,1]); C The crystal of LS paths of type ['A', 2, 1] and weight -Lambda[0] + Lambda[2] sage: C.R Root system of type ['A', 2, 1] sage: C.weight -Lambda[0] + Lambda[2] sage: C.weight.parent() Extended weight space over the Rational Field of the Root system of type ['A', 2, 1] sage: C.module_generators [(-Lambda[0] + Lambda[2],)] TESTS:: sage: C = crystals.LSPaths(['A',2,1], [-1,0,1]) sage: TestSuite(C).run() # long time sage: C = crystals.LSPaths(['E',6], [1,0,0,0,0,0]) sage: TestSuite(C).run() sage: R = RootSystem(['C',3,1]) sage: La = R.weight_space().basis() sage: LaE = R.weight_space(extended=True).basis() sage: B = crystals.LSPaths(La[0]) sage: BE = crystals.LSPaths(LaE[0]) sage: B is BE False sage: B.weight_lattice_realization() Weight space over the Rational Field of the Root system of type ['C', 3, 1] sage: BE.weight_lattice_realization() Extended weight space over the Rational Field of the Root system of type ['C', 3, 1] """ cartan_type = starting_weight.parent().cartan_type() self.R = RootSystem(cartan_type) self.weight = starting_weight if not self.weight.parent().base_ring().has_coerce_map_from(QQ): raise ValueError( "Please use the weight space, rather than weight lattice for your weights" ) self._cartan_type = cartan_type self._name = "The crystal of LS paths of type %s and weight %s" % ( cartan_type, starting_weight) if cartan_type.is_affine(): if all(i >= 0 for i in starting_weight.coefficients()): Parent.__init__(self, category=(RegularCrystals(), HighestWeightCrystals(), InfiniteEnumeratedSets())) elif starting_weight.parent().is_extended(): Parent.__init__(self, category=(RegularCrystals(), InfiniteEnumeratedSets())) else: Parent.__init__(self, category=(RegularCrystals(), FiniteCrystals())) else: Parent.__init__(self, category=ClassicalCrystals()) if starting_weight == starting_weight.parent().zero(): initial_element = self(tuple([])) else: initial_element = self(tuple([starting_weight])) self.module_generators = [initial_element]
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())
def __init__(self, domain): Parent.__init__(self, base=SR, category=CommutativeAlgebras(SR)) self._domain = domain self._populate_coercion_lists_() self._zero = None # zero element (not constructed yet)
def __init__(self, sign_vectors): self._sign_vectors = sign_vectors from sage_semigroups.categories.finite_left_regular_bands import FiniteLeftRegularBands Parent.__init__(self, category = FiniteLeftRegularBands().FinitelyGenerated())
def __init__(self): from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets Parent.__init__(self, category=InfiniteEnumeratedSets())
def __init__(self, k, p=None, prec_cap=None, base=None, character=None, adjuster=None, act_on_left=False, dettwist=None, act_padic=False, implementation=None): """ See ``OverconvergentDistributions_abstract`` for full documentation. EXAMPLES:: sage: from sage.modular.pollack_stevens.distributions import OverconvergentDistributions sage: D = OverconvergentDistributions(2, 3, 5); D Space of 3-adic distributions with k=2 action and precision cap 5 sage: type(D) <class 'sage.modular.pollack_stevens.distributions.OverconvergentDistributions_class_with_category'> `p` must be a prime, but `p=6` below, which is not prime:: sage: OverconvergentDistributions(k=0, p=6, prec_cap=10) Traceback (most recent call last): ... ValueError: p must be prime """ if not isinstance(base, ring.Ring): raise TypeError("base must be a ring") #from sage.rings.padics.pow_computer import PowComputer # should eventually be the PowComputer on ZpCA once that uses longs. Dist, WeightKAction = get_dist_classes(p, prec_cap, base, self.is_symk(), implementation) self.Element = Dist # if Dist is Dist_long: # self.prime_pow = PowComputer(p, prec_cap, prec_cap, prec_cap) Parent.__init__(self, base, category=Modules(base)) self._k = k self._p = p self._prec_cap = prec_cap self._character = character self._adjuster = adjuster self._dettwist = dettwist if self.is_symk() or character is not None: self._act = WeightKAction(self, character, adjuster, act_on_left, dettwist, padic=act_padic) else: self._act = WeightKAction(self, character, adjuster, act_on_left, dettwist, padic=True) self._populate_coercion_lists_(action_list=[self._act])