Navigation

Source code for sympy.categories.baseclasses

from__future__importprint_function,divisionfromsympy.coreimportS,Basic,Dict,Symbol,Tuple,sympifyfromsympy.core.compatibilityimportrange,iterablefromsympy.setsimportSet,FiniteSet,EmptySetclassClass(Set):r""" The base class for any kind of class in the set-theoretic sense. In axiomatic set theories, everything is a class. A class which can be a member of another class is a set. A class which is not a member of another class is a proper class. The class `\{1, 2\}` is a set; the class of all sets is a proper class. This class is essentially a synonym for :class:`sympy.core.Set`. The goal of this class is to assure easier migration to the eventual proper implementation of set theory. """is_proper=False

[docs]classObject(Symbol):""" The base class for any kind of object in an abstract category. While technically any instance of :class:`Basic` will do, this class is the recommended way to create abstract objects in abstract categories. """

[docs]classMorphism(Basic):""" The base class for any morphism in an abstract category. In abstract categories, a morphism is an arrow between two category objects. The object where the arrow starts is called the domain, while the object where the arrow ends is called the codomain. Two morphisms between the same pair of objects are considered to be the same morphisms. To distinguish between morphisms between the same objects use :class:`NamedMorphism`. It is prohibited to instantiate this class. Use one of the derived classes instead. See Also ======== IdentityMorphism, NamedMorphism, CompositeMorphism """def__new__(cls,domain,codomain):raise(NotImplementedError("Cannot instantiate Morphism. Use derived classes instead."))@propertydefdomain(self):""" Returns the domain of the morphism. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> f = NamedMorphism(A, B, "f") >>> f.domain Object("A") """returnself.args[0]@propertydefcodomain(self):""" Returns the codomain of the morphism. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> f = NamedMorphism(A, B, "f") >>> f.codomain Object("B") """returnself.args[1]

def__mul__(self,other):r""" Composes self with the supplied morphism. The semantics of this operation is given by the following equation: ``g * f == g.compose(f)`` for composable morphisms ``g`` and ``f``. See Also ======== compose """returnself.compose(other)

[docs]classNamedMorphism(Morphism):""" Represents a morphism which has a name. Names are used to distinguish between morphisms which have the same domain and codomain: two named morphisms are equal if they have the same domains, codomains, and names. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> f = NamedMorphism(A, B, "f") >>> f NamedMorphism(Object("A"), Object("B"), "f") >>> f.name 'f' See Also ======== Morphism """def__new__(cls,domain,codomain,name):ifnotname:raiseValueError("Empty morphism names not allowed.")returnBasic.__new__(cls,domain,codomain,Symbol(name))@propertydefname(self):""" Returns the name of the morphism. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> f = NamedMorphism(A, B, "f") >>> f.name 'f' """returnself.args[2].name

[docs]classCompositeMorphism(Morphism):r""" Represents a morphism which is a composition of other morphisms. Two composite morphisms are equal if the morphisms they were obtained from (components) are the same and were listed in the same order. The arguments to the constructor for this class should be listed in diagram order: to obtain the composition `g\circ f` from the instances of :class:`Morphism` ``g`` and ``f`` use ``CompositeMorphism(f, g)``. Examples ======== >>> from sympy.categories import Object, NamedMorphism, CompositeMorphism >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> g * f CompositeMorphism((NamedMorphism(Object("A"), Object("B"), "f"), NamedMorphism(Object("B"), Object("C"), "g"))) >>> CompositeMorphism(f, g) == g * f True """@staticmethoddef_add_morphism(t,morphism):""" Intelligently adds ``morphism`` to tuple ``t``. If ``morphism`` is a composite morphism, its components are added to the tuple. If ``morphism`` is an identity, nothing is added to the tuple. No composability checks are performed. """ifisinstance(morphism,CompositeMorphism):# ``morphism`` is a composite morphism; we have to# denest its components.returnt+morphism.componentselifisinstance(morphism,IdentityMorphism):# ``morphism`` is an identity. Nothing happens.returntelse:returnt+Tuple(morphism)def__new__(cls,*components):ifcomponentsandnotisinstance(components[0],Morphism):# Maybe the user has explicitly supplied a list of# morphisms.returnCompositeMorphism.__new__(cls,*components[0])normalised_components=Tuple()# TODO: Fix the unpythonicity.foriinrange(len(components)-1):current=components[i]following=components[i+1]ifnotisinstance(current,Morphism)or \
notisinstance(following,Morphism):raiseTypeError("All components must be morphisms.")ifcurrent.codomain!=following.domain:raiseValueError("Uncomposable morphisms.")normalised_components=CompositeMorphism._add_morphism(normalised_components,current)# We haven't added the last morphism to the list of normalised# components. Add it now.normalised_components=CompositeMorphism._add_morphism(normalised_components,components[-1])ifnotnormalised_components:# If ``normalised_components`` is empty, only identities# were supplied. Since they all were composable, they are# all the same identities.returncomponents[0]eliflen(normalised_components)==1:# No sense to construct a whole CompositeMorphism.returnnormalised_components[0]returnBasic.__new__(cls,normalised_components)@propertydefcomponents(self):""" Returns the components of this composite morphism. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> (g * f).components (NamedMorphism(Object("A"), Object("B"), "f"), NamedMorphism(Object("B"), Object("C"), "g")) """returnself.args[0]@propertydefdomain(self):""" Returns the domain of this composite morphism. The domain of the composite morphism is the domain of its first component. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> (g * f).domain Object("A") """returnself.components[0].domain@propertydefcodomain(self):""" Returns the codomain of this composite morphism. The codomain of the composite morphism is the codomain of its last component. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> (g * f).codomain Object("C") """returnself.components[-1].codomain

[docs]defflatten(self,new_name):""" Forgets the composite structure of this morphism. If ``new_name`` is not empty, returns a :class:`NamedMorphism` with the supplied name, otherwise returns a :class:`Morphism`. In both cases the domain of the new morphism is the domain of this composite morphism and the codomain of the new morphism is the codomain of this composite morphism. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> (g * f).flatten("h") NamedMorphism(Object("A"), Object("C"), "h") """returnNamedMorphism(self.domain,self.codomain,new_name)

[docs]classDiagram(Basic):r""" Represents a diagram in a certain category. Informally, a diagram is a collection of objects of a category and certain morphisms between them. A diagram is still a monoid with respect to morphism composition; i.e., identity morphisms, as well as all composites of morphisms included in the diagram belong to the diagram. For a more formal approach to this notion see [Pare1970]. The components of composite morphisms are also added to the diagram. No properties are assigned to such morphisms by default. A commutative diagram is often accompanied by a statement of the following kind: "if such morphisms with such properties exist, then such morphisms which such properties exist and the diagram is commutative". To represent this, an instance of :class:`Diagram` includes a collection of morphisms which are the premises and another collection of conclusions. ``premises`` and ``conclusions`` associate morphisms belonging to the corresponding categories with the :class:`FiniteSet`'s of their properties. The set of properties of a composite morphism is the intersection of the sets of properties of its components. The domain and codomain of a conclusion morphism should be among the domains and codomains of the morphisms listed as the premises of a diagram. No checks are carried out of whether the supplied object and morphisms do belong to one and the same category. Examples ======== >>> from sympy.categories import Object, NamedMorphism, Diagram >>> from sympy import FiniteSet, pprint, default_sort_key >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g]) >>> premises_keys = sorted(d.premises.keys(), key=default_sort_key) >>> pprint(premises_keys, use_unicode=False) [g*f:A-->C, id:A-->A, id:B-->B, id:C-->C, f:A-->B, g:B-->C] >>> pprint(d.premises, use_unicode=False) {g*f:A-->C: EmptySet(), id:A-->A: EmptySet(), id:B-->B: EmptySet(), id:C-->C: EmptySet(), f:A-->B: EmptySet(), g:B-->C: EmptySet()} >>> d = Diagram([f, g], {g * f: "unique"}) >>> pprint(d.conclusions) {g*f:A-->C: {unique}} References ========== [Pare1970] B. Pareigis: Categories and functors. Academic Press, 1970. """@staticmethoddef_set_dict_union(dictionary,key,value):""" If ``key`` is in ``dictionary``, set the new value of ``key`` to be the union between the old value and ``value``. Otherwise, set the value of ``key`` to ``value. Returns ``True`` if the key already was in the dictionary and ``False`` otherwise. """ifkeyindictionary:dictionary[key]=dictionary[key]|valuereturnTrueelse:dictionary[key]=valuereturnFalse@staticmethoddef_add_morphism_closure(morphisms,morphism,props,add_identities=True,recurse_composites=True):""" Adds a morphism and its attributes to the supplied dictionary ``morphisms``. If ``add_identities`` is True, also adds the identity morphisms for the domain and the codomain of ``morphism``. """ifnotDiagram._set_dict_union(morphisms,morphism,props):# We have just added a new morphism.ifisinstance(morphism,IdentityMorphism):ifprops:# Properties for identity morphisms don't really# make sense, because very much is known about# identity morphisms already, so much that they# are trivial. Having properties for identity# morphisms would only be confusing.raiseValueError("Instances of IdentityMorphism cannot have properties.")returnifadd_identities:empty=EmptySet()id_dom=IdentityMorphism(morphism.domain)id_cod=IdentityMorphism(morphism.codomain)Diagram._set_dict_union(morphisms,id_dom,empty)Diagram._set_dict_union(morphisms,id_cod,empty)forexisting_morphism,existing_propsinlist(morphisms.items()):new_props=existing_props&propsifmorphism.domain==existing_morphism.codomain:left=morphism*existing_morphismDiagram._set_dict_union(morphisms,left,new_props)ifmorphism.codomain==existing_morphism.domain:right=existing_morphism*morphismDiagram._set_dict_union(morphisms,right,new_props)ifisinstance(morphism,CompositeMorphism)andrecurse_composites:# This is a composite morphism, add its components as# well.empty=EmptySet()forcomponentinmorphism.components:Diagram._add_morphism_closure(morphisms,component,empty,add_identities)def__new__(cls,*args):""" Construct a new instance of Diagram. If no arguments are supplied, an empty diagram is created. If at least an argument is supplied, ``args[0]`` is interpreted as the premises of the diagram. If ``args[0]`` is a list, it is interpreted as a list of :class:`Morphism`'s, in which each :class:`Morphism` has an empty set of properties. If ``args[0]`` is a Python dictionary or a :class:`Dict`, it is interpreted as a dictionary associating to some :class:`Morphism`'s some properties. If at least two arguments are supplied ``args[1]`` is interpreted as the conclusions of the diagram. The type of ``args[1]`` is interpreted in exactly the same way as the type of ``args[0]``. If only one argument is supplied, the diagram has no conclusions. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> from sympy.categories import IdentityMorphism, Diagram >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g]) >>> IdentityMorphism(A) in d.premises.keys() True >>> g * f in d.premises.keys() True >>> d = Diagram([f, g], {g * f: "unique"}) >>> d.conclusions[g * f] {unique} """premises={}conclusions={}# Here we will keep track of the objects which appear in the# premises.objects=EmptySet()iflen(args)>=1:# We've got some premises in the arguments.premises_arg=args[0]ifisinstance(premises_arg,list):# The user has supplied a list of morphisms, none of# which have any attributes.empty=EmptySet()formorphisminpremises_arg:objects|=FiniteSet(morphism.domain,morphism.codomain)Diagram._add_morphism_closure(premises,morphism,empty)elifisinstance(premises_arg,dict)orisinstance(premises_arg,Dict):# The user has supplied a dictionary of morphisms and# their properties.formorphism,propsinpremises_arg.items():objects|=FiniteSet(morphism.domain,morphism.codomain)Diagram._add_morphism_closure(premises,morphism,FiniteSet(*props)ifiterable(props)elseFiniteSet(props))iflen(args)>=2:# We also have some conclusions.conclusions_arg=args[1]ifisinstance(conclusions_arg,list):# The user has supplied a list of morphisms, none of# which have any attributes.empty=EmptySet()formorphisminconclusions_arg:# Check that no new objects appear in conclusions.if((sympify(objects.contains(morphism.domain))isS.true)and(sympify(objects.contains(morphism.codomain))isS.true)):# No need to add identities and recurse# composites this time.Diagram._add_morphism_closure(conclusions,morphism,empty,add_identities=False,recurse_composites=False)elifisinstance(conclusions_arg,dict)or \
isinstance(conclusions_arg,Dict):# The user has supplied a dictionary of morphisms and# their properties.formorphism,propsinconclusions_arg.items():# Check that no new objects appear in conclusions.if(morphism.domaininobjects)and \
(morphism.codomaininobjects):# No need to add identities and recurse# composites this time.Diagram._add_morphism_closure(conclusions,morphism,FiniteSet(*props)ifiterable(props)elseFiniteSet(props),add_identities=False,recurse_composites=False)returnBasic.__new__(cls,Dict(premises),Dict(conclusions),objects)@propertydefpremises(self):""" Returns the premises of this diagram. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> from sympy.categories import IdentityMorphism, Diagram >>> from sympy import pretty >>> A = Object("A") >>> B = Object("B") >>> f = NamedMorphism(A, B, "f") >>> id_A = IdentityMorphism(A) >>> id_B = IdentityMorphism(B) >>> d = Diagram([f]) >>> print(pretty(d.premises, use_unicode=False)) {id:A-->A: EmptySet(), id:B-->B: EmptySet(), f:A-->B: EmptySet()} """returnself.args[0]@propertydefconclusions(self):""" Returns the conclusions of this diagram. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> from sympy.categories import IdentityMorphism, Diagram >>> from sympy import FiniteSet >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g]) >>> IdentityMorphism(A) in d.premises.keys() True >>> g * f in d.premises.keys() True >>> d = Diagram([f, g], {g * f: "unique"}) >>> d.conclusions[g * f] == FiniteSet("unique") True """returnself.args[1]@propertydefobjects(self):""" Returns the :class:`FiniteSet` of objects that appear in this diagram. Examples ======== >>> from sympy.categories import Object, NamedMorphism, Diagram >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g]) >>> d.objects {Object("A"), Object("B"), Object("C")} """returnself.args[2]