This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
sets_cat.py
2908 lines (2280 loc) · 112 KB
/
sets_cat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
r"""
Sets
"""
#*****************************************************************************
# Copyright (C) 2005 David Kohel <kohel@maths.usyd.edu>
# William Stein <wstein@math.ucsd.edu>
# 2008 Teresa Gomez-Diaz (CNRS) <Teresa.Gomez-Diaz@univ-mlv.fr>
# 2008-2014 Nicolas M. Thiery <nthiery at users.sf.net>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#******************************************************************************
from __future__ import print_function, absolute_import
from six.moves import range
from sage.misc.cachefunc import cached_method
from sage.misc.sage_unittest import TestSuite
from sage.misc.abstract_method import abstract_method
from sage.misc.lazy_attribute import lazy_attribute
from sage.misc.lazy_import import lazy_import, LazyImport
from sage.misc.lazy_format import LazyFormat
from sage.misc.superseded import deprecated_function_alias
from sage.categories.category import Category
from sage.categories.category_singleton import Category_singleton
# Do not use sage.categories.all here to avoid initialization loop
from sage.categories.morphism import SetMorphism
from sage.categories.sets_with_partial_maps import SetsWithPartialMaps
from sage.categories.subquotients import SubquotientsCategory
from sage.categories.quotients import QuotientsCategory
from sage.categories.subobjects import SubobjectsCategory
from sage.categories.isomorphic_objects import IsomorphicObjectsCategory
from sage.categories.algebra_functor import AlgebrasCategory
from sage.categories.cartesian_product import CartesianProductsCategory, CartesianProductFunctor
from sage.categories.realizations import RealizationsCategory, Category_realization_of_parent
from sage.categories.with_realizations import WithRealizationsCategory
from sage.categories.category_with_axiom import CategoryWithAxiom
lazy_import('sage.sets.cartesian_product', 'CartesianProduct')
def print_compare(x, y):
"""
Helper method used in
:meth:`Sets.ParentMethods._test_elements_eq_symmetric`,
:meth:`Sets.ParentMethods._test_elements_eq_tranisitive`.
INPUT:
- ``x`` -- an element
- ``y`` -- an element
EXAMPLES::
sage: from sage.categories.sets_cat import print_compare
sage: print_compare(1,2)
1 != 2
sage: print_compare(1,1)
1 == 1
"""
if x == y:
return LazyFormat("%s == %s")%(x, y)
else:
return LazyFormat("%s != %s")%(x, y)
class EmptySetError(ValueError):
"""
Exception raised when some operation can't be performed on the empty set.
EXAMPLES::
sage: def first_element(st):
....: if not st: raise EmptySetError("no elements")
....: else: return st[0]
sage: first_element(Set((1,2,3)))
1
sage: first_element(Set([]))
Traceback (most recent call last):
...
EmptySetError: no elements
"""
pass
class Sets(Category_singleton):
r"""
The category of sets.
The base category for collections of elements with = (equality).
This is also the category whose objects are all parents.
EXAMPLES::
sage: Sets()
Category of sets
sage: Sets().super_categories()
[Category of sets with partial maps]
sage: Sets().all_super_categories()
[Category of sets, Category of sets with partial maps, Category of objects]
Let us consider an example of set::
sage: P = Sets().example("inherits")
sage: P
Set of prime numbers
See ``P??`` for the code.
P is in the category of sets::
sage: P.category()
Category of sets
and therefore gets its methods from the following classes::
sage: for cl in P.__class__.mro(): print(cl)
<class 'sage.categories.examples.sets_cat.PrimeNumbers_Inherits_with_category'>
<class 'sage.categories.examples.sets_cat.PrimeNumbers_Inherits'>
<class 'sage.categories.examples.sets_cat.PrimeNumbers_Abstract'>
<class 'sage.structure.unique_representation.UniqueRepresentation'>
<class 'sage.structure.unique_representation.CachedRepresentation'>
<type 'sage.misc.fast_methods.WithEqualityById'>
<type 'sage.structure.parent.Parent'>
<type 'sage.structure.category_object.CategoryObject'>
<type 'sage.structure.sage_object.SageObject'>
<class 'sage.categories.sets_cat.Sets.parent_class'>
<class 'sage.categories.sets_with_partial_maps.SetsWithPartialMaps.parent_class'>
<class 'sage.categories.objects.Objects.parent_class'>
<... 'object'>
We run some generic checks on P::
sage: TestSuite(P).run(verbose=True)
running ._test_an_element() . . . pass
running ._test_cardinality() . . . pass
running ._test_category() . . . pass
running ._test_elements() . . .
Running the test suite of self.an_element()
running ._test_category() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_pickling() . . . pass
pass
running ._test_elements_eq_reflexive() . . . pass
running ._test_elements_eq_symmetric() . . . pass
running ._test_elements_eq_transitive() . . . pass
running ._test_elements_neq() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_pickling() . . . pass
running ._test_some_elements() . . . pass
Now, we manipulate some elements of P::
sage: P.an_element()
47
sage: x = P(3)
sage: x.parent()
Set of prime numbers
sage: x in P, 4 in P
(True, False)
sage: x.is_prime()
True
They get their methods from the following classes::
sage: for cl in x.__class__.mro(): print(cl)
<class 'sage.categories.examples.sets_cat.PrimeNumbers_Inherits_with_category.element_class'>
<class 'sage.categories.examples.sets_cat.PrimeNumbers_Inherits.Element'>
<type 'sage.rings.integer.IntegerWrapper'>
<type 'sage.rings.integer.Integer'>
<type 'sage.structure.element.EuclideanDomainElement'>
<type 'sage.structure.element.PrincipalIdealDomainElement'>
<type 'sage.structure.element.DedekindDomainElement'>
<type 'sage.structure.element.IntegralDomainElement'>
<type 'sage.structure.element.CommutativeRingElement'>
<type 'sage.structure.element.RingElement'>
<type 'sage.structure.element.ModuleElement'>
<class 'sage.categories.examples.sets_cat.PrimeNumbers_Abstract.Element'>
<type 'sage.structure.element.Element'>
<type 'sage.structure.sage_object.SageObject'>
<class 'sage.categories.sets_cat.Sets.element_class'>
<class 'sage.categories.sets_with_partial_maps.SetsWithPartialMaps.element_class'>
<class 'sage.categories.objects.Objects.element_class'>
<... 'object'>
FIXME: Objects.element_class is not very meaningful ...
TESTS::
sage: TestSuite(Sets()).run()
"""
def super_categories(self):
r"""
We include SetsWithPartialMaps between Sets and Objects so that we
can define morphisms between sets that are only partially defined.
This is also to have the Homset constructor not complain that
SetsWithPartialMaps is not a supercategory of Fields, for example.
EXAMPLES::
sage: Sets().super_categories()
[Category of sets with partial maps]
"""
return [SetsWithPartialMaps()]
def _call_(self, X, enumerated_set=False):
r"""
Construct an object in this category from the data ``X``.
INPUT:
- ``X`` -- an object to be converted into a set
- ``enumerated_set`` -- if set to ``True`` and the input is either a
Python tuple or a Python list then the output will be a finite
enumerated set.
EXAMPLES::
sage: Sets()(ZZ)
Integer Ring
sage: Sets()([1, 2, 3])
{1, 2, 3}
sage: S = Sets()([1, 2, 3]); S.category()
Category of finite sets
sage: S = Sets()([1, 2, 3], enumerated_set=True); S.category()
Category of facade finite enumerated sets
.. NOTE::
Using ``Sets()(A)`` used to implement some sort of forgetful functor
into the ``Sets()`` category. This feature has been removed, because
it was not consistent with the semantic of :meth:`Category.__call__`.
Proper forgetful functors will eventually be implemented, with
another syntax.
"""
if enumerated_set and type(X) in (tuple,list,range):
from sage.categories.enumerated_sets import EnumeratedSets
return EnumeratedSets()(X)
from sage.sets.set import Set
return Set(X)
def example(self, choice = None):
"""
Returns examples of objects of ``Sets()``, as per
:meth:`Category.example()
<sage.categories.category.Category.example>`.
EXAMPLES::
sage: Sets().example()
Set of prime numbers (basic implementation)
sage: Sets().example("inherits")
Set of prime numbers
sage: Sets().example("facade")
Set of prime numbers (facade implementation)
sage: Sets().example("wrapper")
Set of prime numbers (wrapper implementation)
"""
if choice is None:
from sage.categories.examples.sets_cat import PrimeNumbers
return PrimeNumbers()
elif choice == "inherits":
from sage.categories.examples.sets_cat import PrimeNumbers_Inherits
return PrimeNumbers_Inherits()
elif choice == "facade":
from sage.categories.examples.sets_cat import PrimeNumbers_Facade
return PrimeNumbers_Facade()
elif choice == "wrapper":
from sage.categories.examples.sets_cat import PrimeNumbers_Wrapper
return PrimeNumbers_Wrapper()
else:
raise ValueError("Unkown choice")
class SubcategoryMethods:
@cached_method
def CartesianProducts(self):
r"""
Return the full subcategory of the objects of ``self``
constructed as Cartesian products.
.. SEEALSO::
- :class:`.cartesian_product.CartesianProductFunctor`
- :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction`
EXAMPLES::
sage: Sets().CartesianProducts()
Category of Cartesian products of sets
sage: Semigroups().CartesianProducts()
Category of Cartesian products of semigroups
sage: EuclideanDomains().CartesianProducts()
Category of Cartesian products of commutative rings
"""
return CartesianProductsCategory.category_of(self)
@cached_method
def Subquotients(self):
r"""
Return the full subcategory of the objects of ``self``
constructed as subquotients.
Given a concrete category ``self == As()`` (i.e. a subcategory
of ``Sets()``), ``As().Subquotients()`` returns the category
of objects of ``As()`` endowed with a distinguished
description as subquotient of some other object of ``As()``.
EXAMPLES::
sage: Monoids().Subquotients()
Category of subquotients of monoids
A parent `A` in ``As()`` is further in
``As().Subquotients()`` if there is a distinguished parent
`B` in ``As()``, called the *ambient set*, a subobject
`B'` of `B`, and a pair of maps:
.. MATH::
l: A \to B' \text{ and } r: B' \to A
called respectively the *lifting map* and *retract map*
such that `r \circ l` is the identity of `A` and `r` is a
morphism in ``As()``.
.. TODO:: Draw the typical commutative diagram.
It follows that, for each operation `op` of the category,
we have some property like:
.. MATH::
op_A(e) = r(op_B(l(e))), \text{ for all } e\in A
This allows for implementing the operations on `A` from
those on `B`.
The two most common use cases are:
- *homomorphic images* (or *quotients*), when `B'=B`,
`r` is an homomorphism from `B` to `A` (typically a
canonical quotient map), and `l` a section of it (not
necessarily a homomorphism); see :meth:`Quotients`;
- *subobjects* (up to an isomorphism), when `l` is an
embedding from `A` into `B`; in this case, `B'` is
typically isomorphic to `A` through the inverse
isomorphisms `r` and `l`; see :meth:`Subobjects`;
.. NOTE::
- The usual definition of "subquotient"
(:wikipedia:`Subquotient`) does not involve the
lifting map `l`. This map is required in Sage's
context to make the definition constructive. It is
only used in computations and does not affect their
results. This is relatively harmless since the
category is a concrete category (i.e., its objects
are sets and its morphisms are set maps).
- In mathematics, especially in the context of
quotients, the retract map `r` is often referred to
as a *projection map* instead.
- Since `B'` is not specified explicitly, it is
possible to abuse the framework with situations
where `B'` is not quite a subobject and `r` not
quite a morphism, as long as the lifting and retract
maps can be used as above to compute all the
operations in `A`. Use at your own risk!
Assumptions:
- For any category ``As()``, ``As().Subquotients()`` is a
subcategory of ``As()``.
Example: a subquotient of a group is a group (e.g., a left
or right quotient of a group by a non-normal subgroup is
not in this category).
- This construction is covariant: if ``As()`` is a
subcategory of ``Bs()``, then ``As().Subquotients()`` is a
subcategory of ``Bs().Subquotients()``.
Example: if `A` is a subquotient of `B` in the category of
groups, then it is also a subquotient of `B` in the category
of monoids.
- If the user (or a program) calls ``As().Subquotients()``,
then it is assumed that subquotients are well defined in
this category. This is not checked, and probably never will
be. Note that, if a category ``As()`` does not specify
anything about its subquotients, then its subquotient
category looks like this::
sage: EuclideanDomains().Subquotients()
Join of Category of euclidean domains
and Category of subquotients of monoids
Interface: the ambient set `B` of `A` is given by
``A.ambient()``. The subset `B'` needs not be specified, so
the retract map is handled as a partial map from `B` to `A`.
The lifting and retract map are implemented
respectively as methods ``A.lift(a)`` and ``A.retract(b)``.
As a shorthand for the former, one can use alternatively
``a.lift()``::
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(3).lift().parent()
An example of a semigroup: the left zero semigroup
sage: S(3) * S(1) == S.retract( S(3).lift() * S(1).lift() )
True
See ``S?`` for more.
.. TODO:: use a more interesting example, like `\ZZ/n\ZZ`.
.. SEEALSO::
- :meth:`Quotients`, :meth:`Subobjects`, :meth:`IsomorphicObjects`
- :class:`.subquotients.SubquotientsCategory`
- :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction`
TESTS::
sage: TestSuite(Sets().Subquotients()).run()
"""
return SubquotientsCategory.category_of(self)
@cached_method
def Quotients(self):
r"""
Return the full subcategory of the objects of ``self``
constructed as quotients.
Given a concrete category ``As()`` (i.e. a subcategory of
``Sets()``), ``As().Quotients()`` returns the category of
objects of ``As()`` endowed with a distinguished
description as quotient (in fact homomorphic image) of
some other object of ``As()``.
Implementing an object of ``As().Quotients()`` is done in
the same way as for ``As().Subquotients()``; namely by
providing an ambient space and a lift and a retract
map. See :meth:`Subquotients` for detailed instructions.
.. SEEALSO::
- :meth:`Subquotients` for background
- :class:`.quotients.QuotientsCategory`
- :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction`
EXAMPLES::
sage: C = Semigroups().Quotients(); C
Category of quotients of semigroups
sage: C.super_categories()
[Category of subquotients of semigroups, Category of quotients of sets]
sage: C.all_super_categories()
[Category of quotients of semigroups,
Category of subquotients of semigroups,
Category of semigroups,
Category of subquotients of magmas,
Category of magmas,
Category of quotients of sets,
Category of subquotients of sets,
Category of sets,
Category of sets with partial maps,
Category of objects]
The caller is responsible for checking that the given category
admits a well defined category of quotients::
sage: EuclideanDomains().Quotients()
Join of Category of euclidean domains
and Category of subquotients of monoids
and Category of quotients of semigroups
TESTS::
sage: TestSuite(C).run()
"""
return QuotientsCategory.category_of(self)
@cached_method
def Subobjects(self):
r"""
Return the full subcategory of the objects of ``self``
constructed as subobjects.
Given a concrete category ``As()`` (i.e. a subcategory of
``Sets()``), ``As().Subobjects()`` returns the category of
objects of ``As()`` endowed with a distinguished embedding
into some other object of ``As()``.
Implementing an object of ``As().Subobjects()`` is done in
the same way as for ``As().Subquotients()``; namely by
providing an ambient space and a lift and a retract
map. In the case of a trivial embedding, the two maps will
typically be identity maps that just change the parent of
their argument. See :meth:`Subquotients` for detailed
instructions.
.. SEEALSO::
- :meth:`Subquotients` for background
- :class:`.subobjects.SubobjectsCategory`
- :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction`
EXAMPLES::
sage: C = Sets().Subobjects(); C
Category of subobjects of sets
sage: C.super_categories()
[Category of subquotients of sets]
sage: C.all_super_categories()
[Category of subobjects of sets,
Category of subquotients of sets,
Category of sets,
Category of sets with partial maps,
Category of objects]
Unless something specific about subobjects is implemented for this
category, one actually gets an optimized super category::
sage: C = Semigroups().Subobjects(); C
Join of Category of subquotients of semigroups
and Category of subobjects of sets
The caller is responsible for checking that the given category
admits a well defined category of subobjects.
TESTS::
sage: Semigroups().Subobjects().is_subcategory(Semigroups().Subquotients())
True
sage: TestSuite(C).run()
"""
return SubobjectsCategory.category_of(self)
@cached_method
def IsomorphicObjects(self):
r"""
Return the full subcategory of the objects of ``self``
constructed by isomorphism.
Given a concrete category ``As()`` (i.e. a subcategory of
``Sets()``), ``As().IsomorphicObjects()`` returns the category of
objects of ``As()`` endowed with a distinguished description as
the image of some other object of ``As()`` by an isomorphism in
this category.
See :meth:`Subquotients` for background.
EXAMPLES:
In the following example, `A` is defined as the image by `x\mapsto
x^2` of the finite set `B = \{1,2,3\}`::
sage: A = FiniteEnumeratedSets().IsomorphicObjects().example(); A
The image by some isomorphism of An example of a finite enumerated set: {1,2,3}
Since `B` is a finite enumerated set, so is `A`::
sage: A in FiniteEnumeratedSets()
True
sage: A.cardinality()
3
sage: A.list()
[1, 4, 9]
The isomorphism from `B` to `A` is available as::
sage: A.retract(3)
9
and its inverse as::
sage: A.lift(9)
3
It often is natural to declare those morphisms as coercions so
that one can do ``A(b)`` and ``B(a)`` to go back and forth between
`A` and `B` (TODO: refer to a category example where the maps are
declared as a coercion). This is not done by default. Indeed, in
many cases one only wants to transport part of the structure of
`B` to `A`. Assume for example, that one wants to construct the
set of integers `B=ZZ`, endowed with ``max`` as addition, and
``+`` as multiplication instead of the usual ``+`` and ``*``. One
can construct `A` as isomorphic to `B` as an infinite enumerated
set. However `A` is *not* isomorphic to `B` as a ring; for
example, for `a\in A` and `a\in B`, the expressions `a+A(b)` and
`B(a)+b` give completely different results; hence we would not want
the expression `a+b` to be implicitly resolved to any one of above
two, as the coercion mechanism would do.
Coercions also cannot be used with facade parents (see
:class:`Sets.Facade`) like in the example above.
We now look at a category of isomorphic objects::
sage: C = Sets().IsomorphicObjects(); C
Category of isomorphic objects of sets
sage: C.super_categories()
[Category of subobjects of sets, Category of quotients of sets]
sage: C.all_super_categories()
[Category of isomorphic objects of sets,
Category of subobjects of sets,
Category of quotients of sets,
Category of subquotients of sets,
Category of sets,
Category of sets with partial maps,
Category of objects]
Unless something specific about isomorphic objects is implemented
for this category, one actually get an optimized super category::
sage: C = Semigroups().IsomorphicObjects(); C
Join of Category of quotients of semigroups
and Category of isomorphic objects of sets
.. SEEALSO::
- :meth:`Subquotients` for background
- :class:`.isomorphic_objects.IsomorphicObjectsCategory`
- :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction`
TESTS::
sage: TestSuite(Sets().IsomorphicObjects()).run()
"""
return IsomorphicObjectsCategory.category_of(self)
@cached_method
def Topological(self):
"""
Return the subcategory of the topological objects of ``self``.
TESTS::
sage: TestSuite(Sets().Topological()).run()
"""
from sage.categories.topological_spaces import TopologicalSpacesCategory
return TopologicalSpacesCategory.category_of(self)
@cached_method
def Metric(self):
"""
Return the subcategory of the metric objects of ``self``.
TESTS::
sage: TestSuite(Sets().Metric()).run()
"""
from sage.categories.metric_spaces import MetricSpacesCategory
return MetricSpacesCategory.category_of(self)
@cached_method
def Algebras(self, base_ring):
"""
Return the category of objects constructed as algebras of
objects of ``self`` over ``base_ring``.
INPUT:
- ``base_ring`` -- a ring
See :meth:`Sets.ParentMethods.algebra` for the precise
meaning in Sage of the *algebra of an object*.
EXAMPLES::
sage: Monoids().Algebras(QQ)
Category of monoid algebras over Rational Field
sage: Groups().Algebras(QQ)
Category of group algebras over Rational Field
sage: AdditiveMagmas().AdditiveAssociative().Algebras(QQ)
Category of additive semigroup algebras over Rational Field
sage: Monoids().Algebras(Rings())
Category of monoid algebras over Category of rings
.. SEEALSO::
- :class:`.algebra_functor.AlgebrasCategory`
- :class:`~.covariant_functorial_construction.CovariantFunctorialConstruction`
TESTS::
sage: TestSuite(Groups().Finite().Algebras(QQ)).run()
"""
from sage.categories.rings import Rings
assert base_ring in Rings or (isinstance(base_ring, Category)
and base_ring.is_subcategory(Rings()))
return AlgebrasCategory.category_of(self, base_ring)
@cached_method
def Finite(self):
"""
Return the full subcategory of the finite objects of ``self``.
EXAMPLES::
sage: Sets().Finite()
Category of finite sets
sage: Rings().Finite()
Category of finite rings
TESTS::
sage: TestSuite(Sets().Finite()).run()
sage: Rings().Finite.__module__
'sage.categories.sets_cat'
"""
return self._with_axiom('Finite')
@cached_method
def Infinite(self):
"""
Return the full subcategory of the infinite objects of ``self``.
EXAMPLES::
sage: Sets().Infinite()
Category of infinite sets
sage: Rings().Infinite()
Category of infinite rings
TESTS::
sage: TestSuite(Sets().Infinite()).run()
sage: Rings().Infinite.__module__
'sage.categories.sets_cat'
"""
return self._with_axiom('Infinite')
@cached_method
def Enumerated(self):
"""
Return the full subcategory of the enumerated objects of ``self``.
An enumerated object can be iterated to get its elements.
EXAMPLES::
sage: Sets().Enumerated()
Category of enumerated sets
sage: Rings().Finite().Enumerated()
Category of finite enumerated rings
sage: Rings().Infinite().Enumerated()
Category of infinite enumerated rings
TESTS::
sage: TestSuite(Sets().Enumerated()).run()
sage: Rings().Enumerated.__module__
'sage.categories.sets_cat'
"""
return self._with_axiom('Enumerated')
def Facade(self):
r"""
Return the full subcategory of the facade objects of ``self``.
.. _facade-sets:
.. RUBRIC:: What is a facade set?
Recall that, in Sage, :ref:`sets are modelled by *parents*
<category-primer-parents-elements-categories>`, and their
elements know which distinguished set they belong to. For
example, the ring of integers `\ZZ` is modelled by the
parent :obj:`ZZ`, and integers know that they belong to
this set::
sage: ZZ
Integer Ring
sage: 42.parent()
Integer Ring
Sometimes, it is convenient to represent the elements of a
parent ``P`` by elements of some other parent. For
example, the elements of the set of prime numbers are
represented by plain integers::
sage: Primes()
Set of all prime numbers: 2, 3, 5, 7, ...
sage: p = Primes().an_element(); p
43
sage: p.parent()
Integer Ring
In this case, ``P`` is called a *facade set*.
This feature is advertised through the category of `P`::
sage: Primes().category()
Category of facade infinite enumerated sets
sage: Sets().Facade()
Category of facade sets
Typical use cases include modeling a subset of an existing
parent::
sage: Set([4,6,9]) # random
{4, 6, 9}
sage: Sets().Facade().example()
An example of facade set: the monoid of positive integers
or the union of several parents::
sage: Sets().Facade().example("union")
An example of a facade set: the integers completed by +-infinity
or endowing an existing parent with more (or less!)
structure::
sage: Posets().example("facade")
An example of a facade poset: the positive integers ordered by divisibility
Let us investigate in detail a close variant of this last
example: let `P` be set of divisors of `12` partially
ordered by divisibility. There are two options for
representing its elements:
1. as plain integers::
sage: P = Poset((divisors(12), attrcall("divides")), facade=True)
2. as integers, modified to be aware that their parent is `P`::
sage: Q = Poset((divisors(12), attrcall("divides")), facade=False)
The advantage of option 1. is that one needs not do
conversions back and forth between `P` and `\ZZ`. The
disadvantage is that this introduces an ambiguity when
writing `2 < 3`: does this compare `2` and `3` w.r.t. the
natural order on integers or w.r.t. divisibility?::
sage: 2 < 3
True
To raise this ambiguity, one needs to explicitly specify
the underlying poset as in `2 <_P 3`::
sage: P = Posets().example("facade")
sage: P.lt(2,3)
False
On the other hand, with option 2. and once constructed,
the elements know unambiguously how to compare
themselves::
sage: Q(2) < Q(3)
False
sage: Q(2) < Q(6)
True
Beware that ``P(2)`` is still the integer `2`. Therefore
``P(2) < P(3)`` still compares `2` and `3` as integers!::
sage: P(2) < P(3)
True
In short `P` being a facade parent is one of the programmatic
counterparts (with e.g. coercions) of the usual mathematical idiom:
"for ease of notation, we identify an element of `P` with the
corresponding integer". Too many identifications lead to
confusion; the lack thereof leads to heavy, if not obfuscated,
notations. Finding the right balance is an art, and even though
there are common guidelines, it is ultimately up to the writer to
choose which identifications to do. This is no different in code.
.. SEEALSO::
The following examples illustrate various ways to
implement subsets like the set of prime numbers; look
at their code for details::
sage: Sets().example("facade")
Set of prime numbers (facade implementation)
sage: Sets().example("inherits")
Set of prime numbers
sage: Sets().example("wrapper")
Set of prime numbers (wrapper implementation)
.. RUBRIC:: Specifications
A parent which is a facade must either:
- call :meth:`Parent.__init__` using the ``facade`` parameter to
specify a parent, or tuple thereof.
- overload the method :meth:`~Sets.Facade.ParentMethods.facade_for`.
.. NOTE::
The concept of facade parents was originally introduced
in the computer algebra system MuPAD.
TESTS:
Check that multiple categories initialisation
works (:trac:`13801`)::
sage: class A(Parent):
....: def __init__(self):
....: Parent.__init__(self, category=(FiniteEnumeratedSets(),Monoids()), facade=True)
sage: a = A()
sage: Posets().Facade()
Category of facade posets
sage: Posets().Facade().Finite() is Posets().Finite().Facade()
True
"""
return self._with_axiom('Facade')
Facades = deprecated_function_alias(17073, Facade)
class ParentMethods:
# TODO: simplify the _element_constructor_ definition logic
# TODO: find a nicer mantra for conditionally defined methods
@lazy_attribute
def _element_constructor_(self):
r"""
TESTS::
sage: S = Sets().example()
sage: S._element_constructor_(17)
17
sage: S(17) # indirect doctest
17
sage: A = FreeModule(QQ, 3)
sage: A.element_class
<type 'sage.modules.vector_rational_dense.Vector_rational_dense'>
sage: A._element_constructor_
<bound method FreeModule_ambient_field_with_category._element_constructor_ of Vector space of dimension 3 over Rational Field>
sage: B = SymmetricGroup(3).algebra(ZZ)
sage: B.element_class
<...SymmetricGroupAlgebra_n_with_category.element_class'>
sage: B._element_constructor_
<bound method SymmetricGroupAlgebra_n_with_category._element_constructor_
of Symmetric group algebra of order 3 over Integer Ring>
"""
if hasattr(self, "element_class"):
return self._element_constructor_from_element_class
else:
return NotImplemented
def _element_constructor_from_element_class(self, *args, **keywords):
"""
The default constructor for elements of this parent ``self``.
Among other things, it is called upon ``self(data)`` when
the coercion model did not find a way to coerce ``data`` into
this parent.
This default implementation for
:meth:`_element_constructor_` calls the constructor of the
element class, passing ``self`` as first argument.
EXAMPLES::
sage: S = Sets().example("inherits")
sage: s = S._element_constructor_from_element_class(17); s
17
sage: type(s)
<class 'sage.categories.examples.sets_cat.PrimeNumbers_Inherits_with_category.element_class'>
"""
return self.element_class(self, *args, **keywords)
def is_parent_of(self, element):
"""
Return whether ``self`` is the parent of ``element``.