Skip to content

Commit

Permalink
sagemathgh-38611: pep and ruff cleanup in semirings and tropicals
Browse files Browse the repository at this point in the history
    
some code cleanup (pep8 and ruff suggestions) in rings/semirings/

### 📝 Checklist

- [x] The title is concise and informative.
- [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 and checked the documentation
preview.
    
URL: sagemath#38611
Reported by: Frédéric Chapoton
Reviewer(s): Frédéric Chapoton, gmou3
  • Loading branch information
Release Manager committed Sep 4, 2024
2 parents 73def88 + 5d05987 commit 95fa3e3
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 42 deletions.
12 changes: 7 additions & 5 deletions src/sage/rings/semirings/non_negative_integer_semiring.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
r"""
Non Negative Integer Semiring
"""
#*****************************************************************************
# ****************************************************************************
# Copyright (C) 2010 Nicolas Borie <nicolas.borie at math.u-psud.fr>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#******************************************************************************
# https://www.gnu.org/licenses/
# *****************************************************************************

from sage.sets.non_negative_integers import NonNegativeIntegers
from sage.categories.semirings import Semirings
from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets
from sage.sets.family import Family


class NonNegativeIntegerSemiring(NonNegativeIntegers):
r"""
A class for the semiring of the nonnegative integers.
Expand Down Expand Up @@ -69,9 +70,10 @@ def __init__(self):
Category of facade infinite enumerated commutative semirings
sage: TestSuite(NN).run()
"""
NonNegativeIntegers.__init__(self, category=(Semirings().Commutative(), InfiniteEnumeratedSets()) )
NonNegativeIntegers.__init__(self, category=(Semirings().Commutative(),
InfiniteEnumeratedSets()))

def _repr_(self):
def _repr_(self) -> str:
r"""
EXAMPLES::
Expand Down
8 changes: 4 additions & 4 deletions src/sage/rings/semirings/tropical_mpolynomial.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from sage.structure.unique_representation import UniqueRepresentation
from sage.rings.polynomial.multi_polynomial_element import MPolynomial_polydict


class TropicalMPolynomial(MPolynomial_polydict):
r"""
A multivariate tropical polynomial.
Expand Down Expand Up @@ -305,7 +306,7 @@ def plot3d(self, color='random'):
corner = set()
for i in axes[0]:
for j in axes[1]:
corner.add((i,j))
corner.add((i, j))
marks = corner | vertices | edge

# Calculate the value of polynomial at each marked point
Expand All @@ -316,9 +317,8 @@ def plot3d(self, color='random'):
mark_terms = []
value = self(T(mark[0]), T(mark[1]))
value_terms = [term(T(mark[0]), T(mark[1])) for term in terms]
for i in range(len(terms)):
if value_terms[i] == value:
mark_terms.append(terms[i])
mark_terms.extend(terms[i] for i in range(len(terms))
if value_terms[i] == value)
point_terms[(R(mark[0]), R(mark[1]), value.lift())] = mark_terms

# Plot the points that attained its value at one term only
Expand Down
18 changes: 9 additions & 9 deletions src/sage/rings/semirings/tropical_polynomial.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from sage.structure.parent import Parent
from sage.rings.polynomial.polynomial_element_generic import Polynomial_generic_sparse


class TropicalPolynomial(Polynomial_generic_sparse):
r"""
A univariate tropical polynomial.
Expand Down Expand Up @@ -332,9 +333,8 @@ def factor(self):
roots_order[root] += 1
else:
roots_order[root] = 1
factors = []
for root in roots_order:
factors.append((R([root, 0]), roots_order[root]))
factors = [(R([root, 0]), roots_order[root])
for root in roots_order]
return Factorization(factors, unit=unit)

def piecewise_function(self):
Expand Down Expand Up @@ -386,10 +386,10 @@ def piecewise_function(self):
f = intercept + gradient*x
return f

unique_root = sorted(list(set(self.roots())))
unique_root = sorted(set(self.roots()))
pieces = []
domain = []
for i in range(len(unique_root)+1):
for i in range(len(unique_root) + 1):
if i == 0:
test_number = R(unique_root[i] - 1)
elif i == len(unique_root):
Expand Down Expand Up @@ -579,12 +579,12 @@ def _latex_(self):
if x.find("-") == 0:
x = "\\left(" + x + "\\right)"
if n > 1:
v = "|%s^{%s}" % (name, n)
v = f"|{name}^{{{n}}}"
elif n == 1:
v = "|%s" % name
v = f"|{name}"
else:
v = ""
s += "%s %s" % (x, v)
s += f"{x} {v}"
s = s.replace("|", "")
if s == " ":
return self.parent().base().zero()._latex_()
Expand Down Expand Up @@ -968,7 +968,7 @@ def interpolation(self, points):

result = self.one()
for root, order in roots.items():
result *= self([root,0])**order
result *= self([root, 0])**order
test_value = result(R(points[0][0]))
unit = R(points[0][1] - test_value.lift())
result *= unit
Expand Down
40 changes: 16 additions & 24 deletions src/sage/rings/semirings/tropical_variety.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from sage.rings.infinity import infinity
from sage.structure.unique_representation import UniqueRepresentation


class TropicalVariety(UniqueRepresentation, SageObject):
r"""
A tropical variety in `\RR^n`.
Expand Down Expand Up @@ -195,9 +196,8 @@ def __init__(self, poly):
self._poly = poly
self._hypersurface = []
tropical_roots = []
variables = []
for name in poly.parent().variable_names():
variables.append(SR.var(name))
variables = [SR.var(name)
for name in poly.parent().variable_names()]

# Convert each term to its linear function
linear_eq = {}
Expand All @@ -214,9 +214,7 @@ def __init__(self, poly):
sol = solve(linear_eq[keys[0]] == linear_eq[keys[1]], variables)

# Parametric solution of the chosen two terms
final_sol = []
for s in sol[0]:
final_sol.append(s.right())
final_sol = [s.right() for s in sol[0]]
xy_interval = []
xy_interval.append(tuple(final_sol))

Expand Down Expand Up @@ -257,9 +255,8 @@ def __init__(self, poly):
xy_interval.append(parameter_solution[0])
tropical_roots.append(xy_interval)
# Calculate the order
index_diff = []
for i in range(len(keys[0])):
index_diff.append(abs(keys[0][i] - keys[1][i]))
index_diff = [abs(ai - bi)
for ai, bi in zip(keys[0], keys[1])]
order = gcd(index_diff)
temp_order.append(order)
temp_keys.append(keys)
Expand All @@ -270,7 +267,7 @@ def __init__(self, poly):
dim_param = 0
if tropical_roots:
dim_param = len(tropical_roots[0][0]) - 1
vars = [SR.var('t{}'.format(i)) for i in range(1, dim_param+1)]
vars = [SR.var(f't{i}') for i in range(1, dim_param + 1)]
for arg in tropical_roots:
subs_dict = {}
index_vars = 0
Expand Down Expand Up @@ -450,7 +447,6 @@ def _components_intersection(self):
import operator
from sage.functions.min_max import max_symbolic, min_symbolic
from sage.symbolic.relation import solve
from sage.symbolic.expression import Expression
from sage.sets.set import Set

def update_result(result):
Expand Down Expand Up @@ -480,7 +476,7 @@ def update_result(result):
# Checking there are no conditions with the same variables
# that use the <= and >= operators simultaneously
unique_sol_param = set()
temp = [s for s in sol_param_sim]
temp = list(sol_param_sim)
op_temp = {i: set(temp[i].operands()) for i in range(len(temp))}
for s_value in op_temp.values():
match_keys = [k for k, v in op_temp.items() if v == s_value]
Expand Down Expand Up @@ -598,8 +594,7 @@ def _axes(self):
for eqn in self._hypersurface[0][0]:
for op in eqn.operands():
if op.is_numeric():
if op > bound:
bound = op
bound = max(op, bound)
return [[-bound, bound]] * 3

u_set = set()
Expand Down Expand Up @@ -668,10 +663,8 @@ def _axes(self):
zmin = z
zmax = z
else:
if z < zmin:
zmin = z
if z > zmax:
zmax = z
zmin = min(z, zmin)
zmax = max(z, zmax)
axes.append([zmin, zmax])
return axes

Expand Down Expand Up @@ -783,8 +776,8 @@ def find_edge_vertices(i):

# Find the interval of parameter for outer vertex
for index in range(len(comps)):
interval1 = RealSet(-infinity,infinity) # represent t1
interval2 = RealSet(-infinity,infinity) # represent t2
interval1 = RealSet(-infinity, infinity) # represent t1
interval2 = RealSet(-infinity, infinity) # represent t2
is_doublevar = False
for i, point in enumerate(comps[index][0]):
pv = point.variables()
Expand Down Expand Up @@ -952,8 +945,7 @@ def _axes(self):
temp_operands += eq.operands()
for op in temp_operands:
if op.is_numeric():
if abs(op) > bound:
bound = abs(op)
bound = max(abs(op), bound)
return [[-bound, bound]] * 2

verts = self.vertices()
Expand Down Expand Up @@ -1002,11 +994,11 @@ def vertices(self):
if lower != -infinity:
x = parametric_function[0].subs(**{str(var): lower})
y = parametric_function[1].subs(**{str(var): lower})
vertices.add((x,y))
vertices.add((x, y))
if upper != infinity:
x = parametric_function[0].subs(**{str(var): upper})
y = parametric_function[1].subs(**{str(var): upper})
vertices.add((x,y))
vertices.add((x, y))
return vertices

def _parameter_intervals(self):
Expand Down

0 comments on commit 95fa3e3

Please sign in to comment.