Skip to content

Commit

Permalink
gh-35916: some pep8 cleanup in schemes/affine and schemes/curves
Browse files Browse the repository at this point in the history
    
<!-- Please provide a concise, informative and self-explanatory title.
-->
<!-- Don't put issue numbers in the title. Put it in the Description
below. -->
<!-- For example, instead of "Fixes #12345", use "Add a new method to
multiply two integers" -->

### 📚 Description

This is fixing many pycodestyle warnings in the `schemes` folder, mostly
in `affine` and `curves` subfolders

<!-- Describe your changes here in detail. -->
<!-- Why is this change required? What problem does it solve? -->
<!-- If this PR resolves an open issue, please link to it here. For
example "Fixes #12345". -->
<!-- If your change requires a documentation PR, please link it
appropriately. -->

### 📝 Checklist

<!-- Put an `x` in all the boxes that apply. It should be `[x]` not `[x
]`. -->

- [x] The title is concise, informative, and self-explanatory.
- [x] The description explains in detail what this PR is about.
- [ ] I have linked a relevant issue or discussion.
- [ ] I have created tests covering the changes.
- [ ] I have updated the documentation accordingly.

### ⌛ Dependencies

<!-- List all open PRs that this PR logically depends on
- #12345: short description why this is a dependency
- #34567: ...
-->

<!-- If you're unsure about any of these, don't hesitate to ask. We're
here to help! -->
    
URL: #35916
Reported by: Frédéric Chapoton
Reviewer(s): Matthias Köppe, Travis Scrimshaw
  • Loading branch information
Release Manager committed Jul 19, 2023
2 parents 174c410 + fdae513 commit 41fa630
Show file tree
Hide file tree
Showing 14 changed files with 287 additions and 269 deletions.
51 changes: 26 additions & 25 deletions src/sage/schemes/affine/affine_homset.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.schemes.generic.homset import SchemeHomset_points, SchemeHomset_generic


# *******************************************************************
# Affine varieties
# *******************************************************************
Expand Down Expand Up @@ -274,63 +275,63 @@ def points(self, **kwds):
numerical = False
# Then X must be a subscheme
dim_ideal = X.defining_ideal().dimension()
if dim_ideal < 0: # no points
if dim_ideal < 0: # no points
return []
if dim_ideal == 0: # if X zero-dimensional
if dim_ideal == 0: # if X zero-dimensional
rat_points = []
AS = X.ambient_space()
N = AS.dimension_relative()
BR = X.base_ring()
#need a lexicographic ordering for elimination
# need a lexicographic ordering for elimination
R = PolynomialRing(BR, N, AS.gens(), order='lex')
I = R.ideal(X.defining_polynomials())
I0 = R.ideal(0)
#Determine the points through elimination
#This is much faster than using the I.variety() function on each affine chart.
# Determine the points through elimination
# This is much faster than using the I.variety() function on each affine chart.
G = I.groebner_basis()
if G != [1]:
P = {}
points = [P]
#work backwards from solving each equation for the possible
#values of the next coordinate
# work backwards from solving each equation for the possible
# values of the next coordinate
for i in range(len(G) - 1, -1, -1):
new_points = []
good = 0
for P in points:
#substitute in our dictionary entry that has the values
#of coordinates known so far. This results in a single
#variable polynomial (by elimination)
# substitute in our dictionary entry that has the values
# of coordinates known so far. This results in a single
# variable polynomial (by elimination)
L = G[i].substitute(P)
if R(L).degree() > 0:
if numerical:
for pol in L.univariate_polynomial().roots(multiplicities=False):
r = L.variables()[0]
varindex = R.gens().index(r)
P.update({R.gen(varindex):pol})
P.update({R.gen(varindex): pol})
new_points.append(copy(P))
good = 1
else:
L = L.factor()
#the linear factors give the possible rational values of
#this coordinate
# the linear factors give the possible rational values of
# this coordinate
for pol, pow in L:
if pol.degree() == 1 and len(pol.variables()) == 1:
good = 1
r = pol.variables()[0]
varindex = R.gens().index(r)
#add this coordinates information to
#each dictionary entry
P.update({R.gen(varindex):-pol.constant_coefficient() /
pol.monomial_coefficient(r)})
# add this coordinates information to
# each dictionary entry
P.update({R.gen(varindex):
-pol.constant_coefficient() / pol.monomial_coefficient(r)})
new_points.append(copy(P))
else:
new_points.append(P)
good = 1
if good:
points = new_points
#the dictionary entries now have values for all coordinates
#they are the rational solutions to the equations
#make them into affine points
# the dictionary entries now have values for all coordinates
# they are the rational solutions to the equations
# make them into affine points
for i in range(len(points)):
if numerical:
if len(points[i]) == N:
Expand All @@ -350,19 +351,19 @@ def points(self, **kwds):
prec = kwds.pop('precision', 53)
if is_RationalField(R) or R == ZZ:
if not B > 0:
raise TypeError("a positive bound B (= %s) must be specified"%B)
raise TypeError("a positive bound B (= %s) must be specified" % B)
from sage.schemes.affine.affine_rational_point import enum_affine_rational_field
return enum_affine_rational_field(self,B)
return enum_affine_rational_field(self, B)
if R in NumberFields():
if not B > 0:
raise TypeError("a positive bound B (= %s) must be specified"%B)
raise TypeError("a positive bound B (= %s) must be specified" % B)
from sage.schemes.affine.affine_rational_point import enum_affine_number_field
return enum_affine_number_field(self, bound=B, tolerance=tol, precision=prec)
elif isinstance(R, FiniteField):
from sage.schemes.affine.affine_rational_point import enum_affine_finite_field
return enum_affine_finite_field(self)
else:
raise TypeError("unable to enumerate points over %s"%R)
raise TypeError("unable to enumerate points over %s" % R)

def numerical_points(self, F=None, **kwds):
"""
Expand Down Expand Up @@ -447,7 +448,7 @@ def numerical_points(self, F=None, **kwds):
if not is_AffineSpace(X) and X.base_ring() in Fields():
# Then X must be a subscheme
dim_ideal = X.defining_ideal().dimension()
if dim_ideal != 0: # no points
if dim_ideal != 0: # no points
return []
else:
return []
Expand Down
64 changes: 33 additions & 31 deletions src/sage/schemes/affine/affine_morphism.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,11 @@ def __init__(self, parent, polys, check=True):
"""
if check:
if not isinstance(polys, (list, tuple)):
raise TypeError("polys (=%s) must be a list or tuple"%polys)
raise TypeError("polys (=%s) must be a list or tuple" % polys)
source_ring = parent.domain().ambient_space().coordinate_ring()
target = parent.codomain().ambient_space()
if len(polys) != target.ngens():
raise ValueError("there must be %s polynomials"%target.ngens())
raise ValueError("there must be %s polynomials" % target.ngens())
try:
polys = [source_ring(poly) for poly in polys]
except TypeError: # maybe given quotient ring elements
Expand All @@ -207,14 +207,15 @@ def __init__(self, parent, polys, check=True):
except (TypeError, AttributeError):
# must be a rational function since we cannot have
# rational functions for quotient rings
source_field = source_ring.base_ring().fraction_field()
try:
if not all(p.base_ring().fraction_field()==source_ring.base_ring().fraction_field() for p in polys):
raise TypeError("polys (=%s) must be rational functions in %s"%(polys, source_ring))
if not all(p.base_ring().fraction_field() == source_field for p in polys):
raise TypeError("polys (=%s) must be rational functions in %s" % (polys, source_ring))
K = FractionField(source_ring)
polys = [K(p) for p in polys]
# polys = [source_ring(poly.numerator())/source_ring(poly.denominator()) for poly in polys]
except TypeError: # can't seem to coerce
raise TypeError("polys (=%s) must be rational functions in %s"%(polys, source_ring))
except TypeError: # can't seem to coerce
raise TypeError("polys (=%s) must be rational functions in %s" % (polys, source_ring))
check = False

SchemeMorphism_polynomial.__init__(self, parent, polys, check)
Expand Down Expand Up @@ -263,7 +264,7 @@ def __call__(self, x, check=True):
try:
x = self.domain()(x)
except (TypeError, NotImplementedError):
raise TypeError("%s fails to convert into the map's domain %s, but a `pushforward` method is not properly implemented"%(x, self.domain()))
raise TypeError("%s fails to convert into the map's domain %s, but a `pushforward` method is not properly implemented" % (x, self.domain()))

R = x.domain().coordinate_ring()
if R is self.base_ring():
Expand Down Expand Up @@ -307,7 +308,7 @@ def __eq__(self, right):
return False
if self.parent() != right.parent():
return False
return all(val == right._polys[i] for i,val in enumerate(self._polys))
return all(val == right._polys[i] for i, val in enumerate(self._polys))

def __ne__(self, right):
"""
Expand Down Expand Up @@ -336,7 +337,7 @@ def __ne__(self, right):
return True
if self.parent() != right.parent():
return True
return any(val != right._polys[i] for i,val in enumerate(self._polys))
return any(val != right._polys[i] for i, val in enumerate(self._polys))

@lazy_attribute
def _fastpolys(self):
Expand Down Expand Up @@ -422,11 +423,11 @@ def _fast_eval(self, x):
P = []
for i in range(len(self._fastpolys[0])):
# Check if denominator is the identity;
#if not, then must append the fraction evaluated at the point
# if not, then must append the fraction evaluated at the point
if self._fastpolys[1][i] is R.one():
P.append(self._fastpolys[0][i](*x))
else:
P.append(self._fastpolys[0][i](*x)/self._fastpolys[1][i](*x))
P.append(self._fastpolys[0][i](*x) / self._fastpolys[1][i](*x))
return P

def homogenize(self, n):
Expand Down Expand Up @@ -597,32 +598,32 @@ def homogenize(self, n):
# create dictionary for mapping of coordinate rings
R = self.domain().ambient_space().coordinate_ring()
S = A.ambient_space().coordinate_ring()
D = dict(zip(R.gens(), [S.gen(i) for i in range(N+1) if i != ind[0]]))
D = dict(zip(R.gens(), [S.gen(i) for i in range(N + 1) if i != ind[0]]))

if self.codomain().is_projective():
L = [self[i].denominator() for i in range(M+1)]
l = [prod(L[:j] + L[j+1:M+1]) for j in range(M+1)]
F = [S(R(self[i].numerator()*l[i]).subs(D)) for i in range(M+1)]
L = [self[i].denominator() for i in range(M + 1)]
l = [prod(L[:j] + L[j + 1:M + 1]) for j in range(M + 1)]
F = [S(R(self[i].numerator() * l[i]).subs(D)) for i in range(M + 1)]
else:
# clear the denominators if a rational function
L = [self[i].denominator() for i in range(M)]
l = [prod(L[:j] + L[j+1:M]) for j in range(M)]
F = [S(R(self[i].numerator()*l[i]).subs(D)) for i in range(M)]
l = [prod(L[:j] + L[j + 1:M]) for j in range(M)]
F = [S(R(self[i].numerator() * l[i]).subs(D)) for i in range(M)]
F.insert(ind[1], S(R(prod(L)).subs(D))) # coerce in case l is a constant

try:
# remove possible gcd of the polynomials
g = gcd(F)
F = [S(f/g) for f in F]
F = [S(f / g) for f in F]
# remove possible gcd of coefficients
gc = gcd([f.content() for f in F])
F = [S(f/gc) for f in F]
except (AttributeError, ValueError, NotImplementedError, TypeError, ArithmeticError): # no gcd
F = [S(f / gc) for f in F]
except (AttributeError, ValueError, NotImplementedError, TypeError, ArithmeticError): # no gcd
pass

# homogenize
d = max([F[i].degree() for i in range(M+1)])
F = [F[i].homogenize(str(newvar))*newvar**(d-F[i].degree()) for i in range(M+1)]
d = max([F[i].degree() for i in range(M + 1)])
F = [F[i].homogenize(str(newvar)) * newvar**(d - F[i].degree()) for i in range(M + 1)]

return H(F)

Expand Down Expand Up @@ -678,7 +679,7 @@ def as_dynamical_system(self):
if R not in _Fields:
return DynamicalSystem_affine(list(self), self.domain())
if isinstance(R, FiniteField):
return DynamicalSystem_affine_finite_field(list(self), self.domain())
return DynamicalSystem_affine_finite_field(list(self), self.domain())
return DynamicalSystem_affine_field(list(self), self.domain())

def global_height(self, prec=None):
Expand Down Expand Up @@ -885,7 +886,7 @@ def jacobian(self):
return self.__jacobian
except AttributeError:
pass
self.__jacobian = jacobian(list(self),self.domain().ambient_space().gens())
self.__jacobian = jacobian(list(self), self.domain().ambient_space().gens())
return self.__jacobian

def _matrix_times_polymap_(self, mat, h):
Expand Down Expand Up @@ -1025,6 +1026,7 @@ def degree(self):
max_degree = poly.degree()
return max_degree


class SchemeMorphism_polynomial_affine_space_field(SchemeMorphism_polynomial_affine_space):

@cached_method
Expand Down Expand Up @@ -1210,7 +1212,7 @@ def reduce_base_field(self):
R = new_domain.coordinate_ring()
H = Hom(new_domain, new_codomain)
if isinstance(g[0], FractionFieldElement):
return H([R(G.numerator())/R(G.denominator()) for G in g])
return H([R(G.numerator()) / R(G.denominator()) for G in g])
return H([R(G) for G in g])

def indeterminacy_locus(self):
Expand Down Expand Up @@ -1241,7 +1243,7 @@ def indeterminacy_locus(self):
"""
A = self.domain()
X = A.subscheme(0) # affine space as a subscheme
return (self*X.hom(A.gens(), A)).indeterminacy_locus()
return (self * X.hom(A.gens(), A)).indeterminacy_locus()

def indeterminacy_points(self, F=None):
r"""
Expand Down Expand Up @@ -1316,7 +1318,7 @@ def image(self):
"""
X = self.domain().subscheme(0)
e = X.embedding_morphism()
return (self*e).image()
return (self * e).image()


class SchemeMorphism_polynomial_affine_space_finite_field(SchemeMorphism_polynomial_affine_space_field):
Expand All @@ -1342,7 +1344,7 @@ def _fast_eval(self, x):
[1, 1, 2]
"""
R = self.domain().ambient_space().coordinate_ring()
P=[]
P = []
for i in range(len(self._fastpolys[0])):
r = self._fastpolys[0][i](*x)
if self._fastpolys[1][i] is R.one():
Expand All @@ -1356,7 +1358,7 @@ def _fast_eval(self, x):
p = self.base_ring().characteristic()
r = Integer(r) % p
s = Integer(s) % p
P.append(r/s)
P.append(r / s)
return P


Expand Down Expand Up @@ -1441,7 +1443,7 @@ def representatives(self):
reprs = []
for r in h.representatives():
i = X.projective_embedding(0, h.domain().ambient_space())
reprs.append(r*i)
reprs.append(r * i)
else:
reprs = []
for r in h.representatives():
Expand Down Expand Up @@ -1563,5 +1565,5 @@ def image(self):
return self.homogenize(0).image()

e = Y.projective_embedding(0)
h = (e*self).homogenize(0)
h = (e * self).homogenize(0)
return h.image().affine_patch(0, Y.ambient_space())
Loading

0 comments on commit 41fa630

Please sign in to comment.