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') category = Sets() if X in Sets().Finite() or isinstance(X, (tuple, list, set, frozenset)): category = Sets().Finite() Parent.__init__(self, category=category) self.__object = X
def __call__(self, args, **kwds): r""" Functorial construction application. This specializes the generic ``__call__`` from :class:`CovariantFunctorialConstruction` to: - handle the following plain Python containers as input: :class:`frozenset`, :class:`list`, :class:`set`, :class:`tuple`, and :class:`xrange` (Python3 ``range``). - handle the empty list of factors. See the examples below. EXAMPLES:: sage: cartesian_product([[0,1], ('a','b','c')]) The Cartesian product of ({0, 1}, {'a', 'b', 'c'}) sage: _.category() Category of Cartesian products of finite enumerated sets sage: cartesian_product([set([0,1,2]), [0,1]]) The Cartesian product of ({0, 1, 2}, {0, 1}) sage: _.category() Category of Cartesian products of sets Check that the empty product is handled correctly: sage: C = cartesian_product([]) sage: C The Cartesian product of () sage: C.cardinality() 1 sage: C.an_element() () sage: C.category() Category of Cartesian products of sets Check that Python3 ``range`` is handled correctly:: sage: from six.moves import range as py3range sage: C = cartesian_product([py3range(2), py3range(2)]) sage: list(C) [(0, 0), (0, 1), (1, 0), (1, 1)] sage: C.category() Category of Cartesian products of finite enumerated sets """ if any(type(arg) in native_python_containers for arg in args): from sage.categories.sets_cat import Sets S = Sets() args = [S(a, enumerated_set=True) for a in args] elif not args: from sage.categories.sets_cat import Sets from sage.sets.cartesian_product import CartesianProduct return CartesianProduct((), Sets().CartesianProducts()) return super(CartesianProductFunctor, self).__call__(args, **kwds)
def __init__(self): r""" Constructor. See :class:`CartesianProductFunctor` for details. TESTS:: sage: from sage.categories.cartesian_product import CartesianProductFunctor sage: CartesianProductFunctor() The cartesian_product functorial construction """ CovariantFunctorialConstruction.__init__(self) from sage.categories.sets_cat import Sets MultivariateConstructionFunctor.__init__(self, Sets(), Sets())
def __init__(self, K): r""" Initialize a derivation from `K` to `K`. INPUT: - ``K`` -- function field EXAMPLES:: sage: K.<x> = FunctionField(QQ) sage: d = K.derivation() sage: TestSuite(d).run(skip=['_test_category', '_test_pickling']) .. TODO:: Make the caching done at the map by subclassing ``UniqueRepresentation``, which will then implement a valid equality check. Then this will pass the pickling test. """ from .function_field import is_FunctionField if not is_FunctionField(K): raise ValueError("K must be a function field") self.__field = K from sage.categories.homset import Hom from sage.categories.sets_cat import Sets Map.__init__(self, Hom(K,K,Sets()))
def underlying_class(P): r""" Return the underlying class (class without the attached categories) of the given instance. OUTPUT: A class. EXAMPLES:: sage: from sage.rings.asymptotic.misc import underlying_class sage: type(QQ) <class 'sage.rings.rational_field.RationalField_with_category'> sage: underlying_class(QQ) <class 'sage.rings.rational_field.RationalField'> """ cls = type(P) if not hasattr(P, '_is_category_initialized') or not P._is_category_initialized(): return cls from sage.structure.misc import is_extension_type if is_extension_type(cls): return cls from sage.categories.sets_cat import Sets Sets_parent_class = Sets().parent_class while issubclass(cls, Sets_parent_class): cls = cls.__base__ return cls
def __init__(self, gr, compute_reduced=False): self._gradings = [gr] self._isomorphisms = {} self._reduced = compute_reduced C = Sets() Parent.__init__(self, category=C)
def __init__(self): """ TESTS:: sage: P = Sets().example("inherits") """ Parent.__init__(self, category=Sets())
def __init__(self): """ TESTS:: sage: P = Sets().example("inherits") """ Parent.__init__(self, facade=IntegerRing(), category=Sets())
def _coerce_map_from_(self, S): """ Return ``True`` if a coercion from ``S`` exists. EXAMPLES:: sage: L = LazyLaurentSeriesRing(GF(2), 'z') sage: L.has_coerce_map_from(ZZ) True sage: L.has_coerce_map_from(GF(2)) True """ if self.base_ring().has_coerce_map_from(S): return True if isinstance(S, (PolynomialRing_general, LaurentPolynomialRing_generic)) and S.ngens() == 1: def make_series_from(poly): op = LazyLaurentSeriesOperator_polynomial(self, poly) a = poly.valuation() c = (self.base_ring().zero(), poly.degree() + 1) return self.element_class(self, coefficient=op, valuation=a, constant=c) return SetMorphism(Hom(S, self, Sets()), make_series_from) return False
def __init__(self, *intervals): """ A subset of the real line INPUT: Arguments defining a real set. Possibilities are either two real numbers to construct an open set or a list/tuple/iterable of intervals. The individual intervals can be specified by either a :class:`RealInterval`, a tuple of two real numbers (constructing an open interval), or a list of two number (constructing a closed interval). EXAMPLES:: sage: RealSet(0,1) # open set from two numbers (0, 1) sage: i = RealSet(0,1)[0] sage: RealSet(i) # interval (0, 1) sage: RealSet(i, (3,4)) # tuple of two numbers = open set (0, 1) + (3, 4) sage: RealSet(i, [3,4]) # list of two numbers = closed set (0, 1) + [3, 4] """ Parent.__init__(self, category = Sets()) self._intervals = intervals
def __init__(self, R, index_set=None, central_elements=None, category=None, element_class=None, prefix=None, names=None, latex_names=None, **kwds): """ Initialize self. TESTS:: sage: V = lie_conformal_algebras.Virasoro(QQ) sage: TestSuite(V).run() """ default_category = LieConformalAlgebras(R).FinitelyGenerated() try: category = default_category.or_subcategory(category) except ValueError: category = default_category.Super().or_subcategory(category) from sage.categories.sets_cat import Sets if index_set not in Sets().Finite(): raise TypeError("index_set must be a finite set") super(FinitelyFreelyGeneratedLCA,self).__init__(R, index_set=index_set, central_elements=central_elements, category=category, element_class=element_class, prefix=prefix, **kwds) self._ngens = len(self._generators) self._names = names self._latex_names = latex_names
def __init__(self, precision): Parent.__init__(self) self._precision = precision self.register_coercion(MorphismToSPN(ZZ, self, self._precision)) self.register_coercion(MorphismToSPN(QQ, self, self._precision)) to_SR = Hom(self, SR, Sets())(lambda x: SR(x.sage())) SR.register_coercion(to_SR)
def extra_super_categories(self): """ Implement the fact that a finite dimensional module over a finite ring is finite. EXAMPLES:: sage: Modules(IntegerModRing(4)).FiniteDimensional().extra_super_categories() [Category of finite sets] sage: Modules(ZZ).FiniteDimensional().extra_super_categories() [] sage: Modules(GF(5)).FiniteDimensional().is_subcategory(Sets().Finite()) True sage: Modules(ZZ).FiniteDimensional().is_subcategory(Sets().Finite()) False sage: Modules(Rings().Finite()).FiniteDimensional().is_subcategory(Sets().Finite()) True sage: Modules(Rings()).FiniteDimensional().is_subcategory(Sets().Finite()) False """ base_ring = self.base_ring() FiniteSets = Sets().Finite() if (isinstance(base_ring, Category) and base_ring.is_subcategory(FiniteSets)) or \ base_ring in FiniteSets: return [FiniteSets] else: return []
def section(self): r""" This method returns a section map of self by use of :meth:`lift`. See :meth:`section` of :class:`sage.categories.map.Map`, as well. OUTPUT: an instance of :class:`sage.categories.morphism.SetMorphism` mapping an element of the codomain of self to one of its preimages EXAMPLES:: sage: G = GU(3,2) sage: P = PGU(3,2) sage: pr = Hom(G, P).natural_map() sage: sect = pr.section() sage: sect(P.an_element()) [a + 1 a a] [ 1 1 0] [ a 0 0] """ from sage.categories.homset import Hom from sage.categories.sets_cat import Sets H = Hom(self.codomain(), self.domain(), category=Sets()) return H(lambda x: self.lift(x))
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() if indices in Sets().Finite(): category = category.FinitelyGeneratedAsMagma() 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 rank(self, sub): """ Returns the rank of sub as a subset of s. EXAMPLES:: sage: Subsets(3).rank([]) 0 sage: Subsets(3).rank([1,2]) 4 sage: Subsets(3).rank([1,2,3]) 7 sage: Subsets(3).rank([2,3,4]) Traceback (most recent call last): ... ValueError: {2, 3, 4} is not a subset of {1, 2, 3} """ if sub not in Sets(): ssub = Set(sub) if len(sub) != len(ssub): raise ValueError("repeated elements in {}".format(sub)) sub = ssub try: index_list = sorted(self._s.rank(x) for x in sub) except (ValueError, IndexError): raise ValueError("{} is not a subset of {}".format( Set(sub), self._s)) n = self._s.cardinality() r = sum(binomial(n, i) for i in xrange(len(index_list))) return r + choose_nk.rank(index_list, n)
def _create_(k, R): """ Initialization. We have to implement this as a static method in order to call ``__make_element_class__``. INPUT: - ``k`` -- the residue field of ``R``, or a residue ring of ``R``. - ``R`` -- a `p`-adic ring or field. EXAMPLES:: sage: f = Zp(3).convert_map_from(Zmod(81)) sage: TestSuite(f).run() """ from sage.categories.sets_cat import Sets from sage.categories.homset import Hom kfield = R.residue_field() N = k.cardinality() q = kfield.cardinality() n = N.exact_log(q) if N != q**n: raise RuntimeError("N must be a power of q") H = Hom(k, R, Sets()) f = H.__make_element_class__(ResidueLiftingMap)(H) f._n = n return f
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): """ EXAMPLES:: sage: R = RibbonTableaux() sage: TestSuite(R).run() """ Parent.__init__(self, category=Sets())
def super_categories(self): """ EXAMPLES:: sage: EnumeratedSets().super_categories() [Category of sets] """ return [Sets()]
def super_categories(self): """ EXAMPLES:: sage: SetsWithGrading().super_categories() [Category of sets] """ return [Sets()]
def super_categories(self): """ EXAMPLES:: sage: AdditiveMagmas().super_categories() [Category of sets] """ return [Sets()]
def __init__(self, category=None): r""" Constructor. See :class:`CartesianProductFunctor` for details. TESTS:: sage: from sage.categories.cartesian_product import CartesianProductFunctor sage: CartesianProductFunctor() The cartesian_product functorial construction """ CovariantFunctorialConstruction.__init__(self) self._forced_category = category from sage.categories.sets_cat import Sets if self._forced_category is not None: codomain = self._forced_category else: codomain = Sets() MultivariateConstructionFunctor.__init__(self, Sets(), codomain)
def extra_super_categories(self): """ EXAMPLES:: sage: Rings().hom_category().extra_super_categories() [Category of sets] """ from sage.categories.sets_cat import Sets return [Sets()]
def __init__(self): """ EXAMPLES:: sage: sage.misc.nested_class_test.TestParent3() <sage.misc.nested_class_test.TestParent3_with_category object at ...> """ from sage.categories.sets_cat import Sets Parent.__init__(self, category=Sets())
def super_categories(self): """ EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: CWComplexes().super_categories() [Category of topological spaces] """ return [Sets().Topological()]
def super_categories(self): """ EXAMPLES:: sage: from sage.categories.simplicial_sets import SimplicialSets sage: SimplicialSets().super_categories() [Category of sets] """ return [Sets()]
def __init__(self, category=None): """ TESTS:: sage: TestSuite(LabelledOrderedTrees()).run() """ if category is None: category = Sets() Parent.__init__(self, category=category)
def super_categories(self): """ EXAMPLES:: sage: from oriented_matroids import OrientedMatroids sage: OrientedMatroids().super_categories() [Category of sets] """ return [Sets()]
def super_categories(self): """ EXAMPLES:: sage: from sage.categories.manifolds import Manifolds sage: Manifolds(RR).super_categories() [Category of topological spaces] """ return [Sets().Topological()]