Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement iteration over more polynomial rings #39446

Open
wants to merge 21 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
a9a3660
Implement iteration over some polynomial rings
user202729 Jan 28, 2025
72cee9e
Make cardinality return Sage Integer
user202729 Feb 3, 2025
443dd01
Make category(GF(3)[x]) enumerated
user202729 Feb 3, 2025
a3b3e1f
Make Zmod(1)[x] enumerated and remove cardinality()
user202729 Feb 3, 2025
5fb4695
Temporarily remove Enumerated from LaurentPolynomialRing
user202729 Feb 3, 2025
1f354a1
Modify some_elements() to make tests pass
user202729 Feb 3, 2025
9ec9af8
Implement correct iteration through disjoint enumerated set for infin…
user202729 Feb 4, 2025
2dd9b21
Handle the case where is_finite is not available
user202729 Feb 4, 2025
8a91beb
Fix tests
user202729 Feb 4, 2025
c6fd715
Improve is_empty and is_finite in a few cases
user202729 Feb 4, 2025
a1b6d67
Merge branch 'union-enumerate-inf' into more-polynomial-ring-iter
user202729 Feb 4, 2025
4563c6b
Merge branch 'improve-category-empty-finite' into more-polynomial-rin…
user202729 Feb 4, 2025
bc5c6c1
Implement iteration over more polynomial rings
user202729 Feb 4, 2025
73ee001
Fix lint
user202729 Feb 4, 2025
31a802f
Implement is_empty() and is_finite() for a few more classes
user202729 Feb 4, 2025
ed25f5f
Undo adding is_empty to Parent and add it to FiniteWords
user202729 Feb 4, 2025
8a4e1ec
Fix more failing tests
user202729 Feb 4, 2025
9e5e2ae
Merge branch 'improve-category-empty-finite' into more-polynomial-rin…
user202729 Feb 4, 2025
e54624f
Revert behavior of an_element for convenience
user202729 Feb 4, 2025
5441060
Fix some tests
user202729 Feb 4, 2025
678f208
Revert "Modify some_elements() to make tests pass"
user202729 Feb 4, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/sage/categories/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -1657,7 +1657,7 @@ def parent_class(self):
True
sage: Algebras(QQ).parent_class is Algebras(ZZ).parent_class
False
sage: Algebras(ZZ['t']).parent_class is Algebras(ZZ['t','x']).parent_class
sage: Algebras(ZZ['t']).parent_class is Algebras(ZZ['x']).parent_class
True

See :class:`CategoryWithParameters` for an abstract base class for
Expand Down Expand Up @@ -1702,7 +1702,7 @@ def element_class(self):
True
sage: Algebras(QQ).element_class is Algebras(ZZ).element_class
False
sage: Algebras(ZZ['t']).element_class is Algebras(ZZ['t','x']).element_class
sage: Algebras(ZZ['t']).element_class is Algebras(ZZ['x']).element_class
True

These classes are constructed with ``__slots__ = ()``, so
Expand Down
3 changes: 2 additions & 1 deletion src/sage/categories/homset.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,8 @@ def Hom(X, Y, category=None, check=True):
sage: R = Set_PythonType(int)
sage: S = Set_PythonType(float)
sage: Hom(R, S)
Set of Morphisms from Set of Python objects of class 'int' to Set of Python objects of class 'float' in Category of sets
Set of Morphisms from Set of Python objects of class 'int'
to Set of Python objects of class 'float' in Category of infinite sets

Checks that the domain and codomain are in the specified
category. Case of a non parent::
Expand Down
2 changes: 1 addition & 1 deletion src/sage/categories/modules_with_basis.py
Original file line number Diff line number Diff line change
Expand Up @@ -2560,7 +2560,7 @@ def _an_element_(self):
B[()] + B[(1,2)] + 3*B[(1,2,3)] + 2*B[(1,3,2)]
sage: ABA = cartesian_product((A, B, A))
sage: ABA.an_element() # indirect doctest
2*B[(0, word: )] + 2*B[(0, word: a)] + 3*B[(0, word: b)]
2*B[(0, word: )] + 2*B[(1, ())] + 3*B[(1, (1,3,2))]
"""
from .cartesian_product import cartesian_product
return cartesian_product([module.an_element() for module in self.modules])
Expand Down
76 changes: 67 additions & 9 deletions src/sage/categories/sets_cat.py
Original file line number Diff line number Diff line change
Expand Up @@ -2373,8 +2373,32 @@
False
sage: cartesian_product([S1,S2,S1]).is_empty()
True
"""
return any(c.is_empty() for c in self.cartesian_factors())

Even when some parent did not implement ``is_empty``,
as long as one element is nonempty, the result can be determined::

sage: C = ConditionSet(QQ, lambda x: x > 0)
sage: C.is_empty()
Traceback (most recent call last):
...
AttributeError...
sage: cartesian_product([C,[]]).is_empty()
True
sage: cartesian_product([C,C]).is_empty()
Traceback (most recent call last):
...
NotImplementedError...
"""
last_exception = None
for c in self.cartesian_factors():
try:
if c.is_empty():
return True
except (AttributeError, NotImplementedError) as e:
last_exception = e
if last_exception is not None:
raise NotImplementedError from last_exception
return False

def is_finite(self):
r"""
Expand All @@ -2391,18 +2415,52 @@
False
sage: cartesian_product([ZZ, Set(), ZZ]).is_finite()
True

TESTS:

This should still work even if some parent does not implement
``is_finite``::

sage: known_infinite_set = ZZ
sage: unknown_infinite_set = Set([1]) + ConditionSet(QQ, lambda x: x > 0)
sage: unknown_infinite_set.is_empty()
False
sage: unknown_infinite_set.is_finite()
Traceback (most recent call last):
...
AttributeError...
sage: cartesian_product([unknown_infinite_set, known_infinite_set]).is_finite()
False
sage: unknown_empty_set = ConditionSet(QQ, lambda x: False)
sage: cartesian_product([known_infinite_set, unknown_empty_set]).is_finite()
Traceback (most recent call last):
...
NotImplementedError...
sage: cartesian_product([unknown_infinite_set, Set([])]).is_finite()
True
"""
f = self.cartesian_factors()
try:
# Note: some parent might not implement "is_empty". So we
# carefully isolate this test.
test = any(c.is_empty() for c in f)
if self.is_empty():
return True
except (AttributeError, NotImplementedError):
pass
else:
if test:
return test
return all(c.is_finite() for c in f)
# it is unknown whether some set may be empty
if all(c.is_finite() for c in self.cartesian_factors()):
return True

Check warning on line 2450 in src/sage/categories/sets_cat.py

View check run for this annotation

Codecov / codecov/patch

src/sage/categories/sets_cat.py#L2450

Added line #L2450 was not covered by tests
raise NotImplementedError

# in this case, all sets are definitely nonempty
last_exception = None
for c in self.cartesian_factors():
try:
if not c.is_finite():
return False
except (AttributeError, NotImplementedError) as e:
last_exception = e
if last_exception is not None:
raise NotImplementedError from last_exception
return True

Check warning on line 2463 in src/sage/categories/sets_cat.py

View check run for this annotation

Codecov / codecov/patch

src/sage/categories/sets_cat.py#L2461-L2463

Added lines #L2461 - L2463 were not covered by tests

def cardinality(self):
r"""
Expand Down
18 changes: 9 additions & 9 deletions src/sage/combinat/root_system/root_lattice_realizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -694,14 +694,14 @@ def positive_roots(self, index_set=None):
sage: [PR.unrank(i) for i in range(10)] # needs sage.graphs
[alpha[1],
alpha[2],
alpha[0] + alpha[1] + alpha[2] + alpha[3],
alpha[3],
2*alpha[0] + 2*alpha[1] + 2*alpha[2] + 2*alpha[3],
alpha[1] + alpha[2],
3*alpha[0] + 3*alpha[1] + 3*alpha[2] + 3*alpha[3],
alpha[2] + alpha[3],
alpha[1] + alpha[2] + alpha[3],
alpha[0] + 2*alpha[1] + alpha[2] + alpha[3],
alpha[0] + alpha[1] + 2*alpha[2] + alpha[3],
alpha[0] + alpha[1] + alpha[2] + 2*alpha[3],
alpha[0] + 2*alpha[1] + 2*alpha[2] + alpha[3]]
4*alpha[0] + 4*alpha[1] + 4*alpha[2] + 4*alpha[3],
alpha[1] + alpha[2] + alpha[3]]
"""
if self.cartan_type().is_affine():
from sage.sets.disjoint_union_enumerated_sets \
Expand Down Expand Up @@ -798,18 +798,18 @@ def positive_real_roots(self):
sage: [PR.unrank(i) for i in range(5)] # needs sage.graphs
[alpha[1],
alpha[2],
2*alpha[0] + 2*alpha[1] + alpha[2],
alpha[1] + alpha[2],
2*alpha[1] + alpha[2],
alpha[0] + alpha[1] + alpha[2]]
4*alpha[0] + 4*alpha[1] + 2*alpha[2]]

sage: Q = RootSystem(['D',3,2]).root_lattice()
sage: PR = Q.positive_roots() # needs sage.graphs
sage: [PR.unrank(i) for i in range(5)] # needs sage.graphs
[alpha[1],
alpha[2],
alpha[0] + alpha[1] + alpha[2],
alpha[1] + 2*alpha[2],
alpha[1] + alpha[2],
alpha[0] + alpha[1] + 2*alpha[2]]
2*alpha[0] + 2*alpha[1] + 2*alpha[2]]
"""
if self.cartan_type().is_finite():
return tuple(RecursivelyEnumeratedSet(self.simple_roots(),
Expand Down
30 changes: 30 additions & 0 deletions src/sage/combinat/words/words.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,37 @@ class FiniteWords(AbstractLanguage):
sage: W = FiniteWords('ab')
sage: W
Finite words over {'a', 'b'}

TESTS::

sage: FiniteWords('ab').is_finite()
False
sage: FiniteWords([]).is_finite()
True
"""

def __init__(self, alphabet=None, category=None):
if category is None:
category = Sets()
if alphabet:
category = category.Infinite()
else:
category = category.Finite()
super().__init__(alphabet, category)

def is_empty(self):
"""
Return False, because the empty word is in the set.

TESTS::

sage: FiniteWords('ab').is_empty()
False
sage: FiniteWords([]).is_empty()
False
"""
return False

def cardinality(self):
r"""
Return the cardinality of this set.
Expand Down
6 changes: 5 additions & 1 deletion src/sage/rings/polynomial/laurent_polynomial_ring_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,12 @@ def __init__(self, R):
self._R = R
names = R.variable_names()
self._one_element = self.element_class(self, R.one())
category = R.category()
if "Enumerated" in category.axioms():
# this ring should also be countable, but __iter__ is not yet implemented
category = category._without_axiom("Enumerated")
CommutativeRing.__init__(self, R.base_ring(), names=names,
category=R.category())
category=category)
ernames = []
for n in names:
ernames.append(n)
Expand Down
86 changes: 82 additions & 4 deletions src/sage/rings/polynomial/polynomial_ring.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@
from sage.rings.ring import Ring, CommutativeRing
from sage.structure.element import RingElement
import sage.rings.rational_field as rational_field
from sage.rings.infinity import Infinity
from sage.rings.rational_field import QQ
from sage.rings.integer_ring import ZZ
from sage.rings.integer import Integer
Expand Down Expand Up @@ -264,7 +265,7 @@
(Dedekind domains and euclidean domains
and noetherian rings and infinite enumerated sets
and metric spaces)
and Category of infinite sets
and Category of infinite enumerated sets

sage: category(GF(7)['x'])
Join of Category of euclidean domains
Expand All @@ -274,7 +275,7 @@
and Category of commutative algebras over
(finite enumerated fields and subquotients of monoids
and quotients of semigroups)
and Category of infinite sets
and Category of infinite enumerated sets

TESTS:

Expand All @@ -287,7 +288,7 @@
Check that category for zero ring::

sage: PolynomialRing(Zmod(1), 'x').category()
Category of finite commutative rings
Category of finite enumerated commutative rings

Check ``is_finite`` inherited from category (:issue:`24432`)::

Expand All @@ -306,7 +307,7 @@
# We trust that, if category is given, it is useful and does not need to be joined
# with the default category
if base_ring.is_zero():
category = categories.rings.Rings().Commutative().Finite()
category = categories.rings.Rings().Commutative().Finite().Enumerated()
else:
defaultcat = polynomial_default_category(base_ring.category(), 1)
category = check_default_category(defaultcat, category)
Expand Down Expand Up @@ -1033,6 +1034,83 @@
h = self._cached_hash = hash((self.base_ring(),self.variable_name()))
return h

def __iter__(self):
r"""
Return iterator over the elements of this polynomial ring.

EXAMPLES::

sage: from itertools import islice
sage: R.<x> = GF(3)[]
sage: list(islice(iter(R), 10))
[0, 1, 2, x, x + 1, x + 2, 2*x, 2*x + 1, 2*x + 2, x^2]

TESTS::

sage: R.<x> = Integers(1)[]
sage: [*R]
[0]
sage: R.<x> = QQ[]
sage: l = list(islice(iter(R), 50)); l
[0, 1, -1, x, 1/2, x + 1, x^2, -1/2, -x, x^2 + 1, x^3, 2, x - 1, ...]
sage: len(set(l))
50
"""
R = self.base_ring()
# adapted from sage.modules.free_module.FreeModule_generic.__iter__
iters = []
v = []
n = 0
yield self.zero()
if R.is_zero():
return

zero = R.zero()
if R.cardinality() == Infinity:
from sage.categories.sets_cat import cartesian_product
from sage.sets.disjoint_union_enumerated_sets import DisjointUnionEnumeratedSets
from sage.sets.family import Family
from sage.rings.semirings.non_negative_integer_semiring import NN
from sage.sets.set import Set
R_nonzero = Set(R) - Set([zero])

def polynomials_with_degree(d):
"""
Return the family of polynomials with degree exactly ``d``.
"""
nonlocal self, R, R_nonzero
return Family(cartesian_product([R] * d + [R_nonzero]),
lambda t: self([*t]), lazy=True)

yield from DisjointUnionEnumeratedSets(Family(NN, polynomials_with_degree))
assert False, "this should not be reached"

Check warning on line 1086 in src/sage/rings/polynomial/polynomial_ring.py

View check run for this annotation

Codecov / codecov/patch

src/sage/rings/polynomial/polynomial_ring.py#L1086

Added line #L1086 was not covered by tests

while True:
if n == len(iters):
iters.append(iter(R))
v.append(next(iters[n]))
assert v[n] == zero, ("first element of iteration must be zero otherwise result "
"of this and free module __iter__ will be incorrect")
try:
v[n] = next(iters[n])
yield self(v)
n = 0
except StopIteration:
iters[n] = iter(R)
v[n] = next(iters[n])
assert v[n] == zero
n += 1

def _an_element_(self):
"""
Return an arbitrary element of this polynomial ring.

Strictly speaking this is not necessary because it is already provided by the category
framework, but before :issue:`39399` this returns the generator, we keep the behavior
because it is more convenient.
"""
return self.gen()

def _repr_(self):
try:
return self._cached_repr
Expand Down
17 changes: 17 additions & 0 deletions src/sage/rings/polynomial/polynomial_ring_constructor.py
Original file line number Diff line number Diff line change
Expand Up @@ -892,6 +892,7 @@ def _multi_variate(base_ring, names, sparse=None, order='degrevlex', implementat
from sage import categories
from sage.categories.algebras import Algebras
# Some fixed categories, in order to avoid the function call overhead
_EnumeratedSets = categories.sets_cat.Sets().Enumerated()
_FiniteSets = categories.sets_cat.Sets().Finite()
_InfiniteSets = categories.sets_cat.Sets().Infinite()
_EuclideanDomains = categories.euclidean_domains.EuclideanDomains()
Expand Down Expand Up @@ -938,12 +939,28 @@ def polynomial_default_category(base_ring_category, n_variables):
True
sage: QQ['s']['t'].category() is UniqueFactorizationDomains() & CommutativeAlgebras(QQ['s'].category()).WithBasis().Infinite()
True

TESTS::

sage: category(GF(7)['x'])
Join of Category of euclidean domains
and Category of algebras with basis over
(finite enumerated fields and subquotients of monoids
and quotients of semigroups)
and Category of commutative algebras over
(finite enumerated fields and subquotients of monoids
and quotients of semigroups)
and Category of infinite enumerated sets
"""
category = Algebras(base_ring_category).WithBasis()

if n_variables:
# here we assume the base ring to be nonzero
category = category.Infinite()
if base_ring_category.is_subcategory(_EnumeratedSets) and n_variables == 1:
# n_variables == 1 is not necessary but iteration over multivariate polynomial ring
# is not yet implemented
category = category.Enumerated()
else:
if base_ring_category.is_subcategory(_Fields):
category = category & _Fields
Expand Down
Loading
Loading