Skip to content

Commit

Permalink
gh-35450: Replace remaining uses of is_SymbolicEquation, `is_Symbol…
Browse files Browse the repository at this point in the history
…icVariable`

    
<!-- 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

<!-- 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. -->


- Follow up from #32665
- Part of #32414

### 📝 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: #35450
Reported by: Matthias Köppe
Reviewer(s):
  • Loading branch information
Release Manager committed Apr 12, 2023
2 parents 358d64d + ae7db7e commit 98bf731
Show file tree
Hide file tree
Showing 13 changed files with 68 additions and 60 deletions.
10 changes: 5 additions & 5 deletions src/sage/calculus/calculus.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,9 +424,9 @@

from sage.misc.latex import latex
from sage.misc.parser import Parser, LookupNameMaker

from sage.symbolic.ring import var, SR, is_SymbolicVariable
from sage.symbolic.expression import Expression, symbol_table
from sage.structure.element import Expression
from sage.symbolic.ring import var, SR
from sage.symbolic.expression import symbol_table
from sage.symbolic.function import Function
from sage.symbolic.function_factory import function_factory
from sage.symbolic.integration.integral import (indefinite_integral,
Expand Down Expand Up @@ -613,7 +613,7 @@ def symbolic_sum(expression, v, a, b, algorithm='maxima', hold=False):
the summation the result might not be convertible into a Sage
expression.
"""
if not is_SymbolicVariable(v):
if not (isinstance(v, Expression) and v.is_symbol()):
if isinstance(v, str):
v = var(v)
else:
Expand Down Expand Up @@ -879,7 +879,7 @@ def symbolic_product(expression, v, a, b, algorithm='maxima', hold=False):
(-1)^n*factorial(n)^2
"""
if not is_SymbolicVariable(v):
if not (isinstance(v, Expression) and v.is_symbol()):
if isinstance(v, str):
v = var(v)
else:
Expand Down
34 changes: 18 additions & 16 deletions src/sage/calculus/desolvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,11 @@

from sage.interfaces.maxima import Maxima
from sage.misc.lazy_import import lazy_import
lazy_import("sage.plot.all", "line")
from sage.symbolic.expression import is_SymbolicEquation
from sage.symbolic.ring import SR, is_SymbolicVariable
from sage.calculus.functional import diff
from sage.misc.functional import N
from sage.rings.real_mpfr import RealField
from sage.structure.element import Expression

from .functional import diff


maxima = Maxima()
Expand Down Expand Up @@ -550,9 +549,9 @@ def desolve(de, dvar, ics=None, ivar=None, show_method=False, contrib_ode=False,
- Robert Bradshaw (10-2008)
- Robert Marik (10-2009)
"""
if is_SymbolicEquation(de):
if isinstance(de, Expression) and de.is_relational():
de = de.lhs() - de.rhs()
if is_SymbolicVariable(dvar):
if isinstance(dvar, Expression) and dvar.is_symbol():
raise ValueError("You have to declare dependent variable as a function evaluated at the independent variable, eg. y=function('y')(x)")
# for backwards compatibility
if isinstance(dvar, list):
Expand Down Expand Up @@ -600,8 +599,8 @@ def sanitize_var(exprs):
if show_method:
maxima_method=P("method")

if (ics is not None):
if not is_SymbolicEquation(soln.sage()):
if ics is not None:
if not (isinstance(soln.sage(), Expression) and soln.sage().is_relational()):
if not show_method:
maxima_method=P("method")
raise NotImplementedError("Unable to use initial condition for this equation (%s)."%(str(maxima_method).strip()))
Expand Down Expand Up @@ -649,8 +648,8 @@ def sanitize_var(exprs):
if str(soln).strip() == 'false':
raise NotImplementedError("Maxima was unable to solve this BVP. Remove the initial condition to get the general solution.")

soln=soln.sage()
if is_SymbolicEquation(soln) and soln.lhs() == dvar:
soln = soln.sage()
if isinstance(soln, Expression) and soln.is_relational() and soln.lhs() == dvar:
# Remark: Here we do not check that the right hand side does not depend on dvar.
# This probably will not happen for solutions obtained via ode2, anyway.
soln = soln.rhs()
Expand Down Expand Up @@ -796,9 +795,9 @@ def desolve_laplace(de, dvar, ics=None, ivar=None):
#return maxima(cmd).rhs()._maxima_init_()

## verbatim copy from desolve - begin
if is_SymbolicEquation(de):
if isinstance(de, Expression) and de.is_relational():
de = de.lhs() - de.rhs()
if is_SymbolicVariable(dvar):
if isinstance(dvar, Expression) and dvar.is_symbol():
raise ValueError("You have to declare dependent variable as a function evaluated at the independent variable, eg. y=function('y')(x)")
# for backwards compatibility
if isinstance(dvar, list):
Expand Down Expand Up @@ -959,7 +958,7 @@ def desolve_system(des, vars, ics=None, ivar=None, algorithm="maxima"):
return desolve_laplace(des[0], vars[0], ics=ics, ivar=ivar)
ivars = set([])
for i, de in enumerate(des):
if not is_SymbolicEquation(de):
if not (isinstance(de, Expression) and de.is_relational()):
des[i] = de == 0
ivars = ivars.union(set(de.variables()))
if ivar is None:
Expand Down Expand Up @@ -1206,6 +1205,8 @@ def eulers_method_2x2_plot(f,g, t0, x0, y0, h, t1):
sage: f = lambda z : z[2]; g = lambda z : -sin(z[1])
sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0)
"""
from sage.plot.line import line

n = int((1.0)*(t1-t0)/h)
t00 = t0
x00 = x0
Expand Down Expand Up @@ -1409,11 +1410,11 @@ def desolve_rk4_inner(de, dvar):
YMIN = t
return plot_slope_field(de, (ivar,XMIN,XMAX), (dvar,YMIN,YMAX))+R

if not is_SymbolicVariable(dvar):
if not (isinstance(dvar, Expression) and dvar.is_symbol()):
from sage.symbolic.ring import SR
from sage.calculus.all import diff
from sage.symbolic.relation import solve
if is_SymbolicEquation(de):
if isinstance(de, Expression) and de.is_relational():
de = de.lhs() - de.rhs()
# consider to add warning if the solution is not unique
de=solve(de,diff(dvar,ivar),solution_dict=True)
Expand Down Expand Up @@ -1706,7 +1707,7 @@ def Dfun(y, t):
mxhnil=mxhnil, mxordn=mxordn, mxords=mxords, printmessg=printmessg)
return sol

if is_SymbolicVariable(dvars):
if isinstance(dvars, Expression) and dvars.is_symbol():
dvars = [dvars]

if not isinstance(des, (list, tuple)):
Expand All @@ -1719,6 +1720,7 @@ def Dfun(y, t):
if len(ivars)==1:
return desolve_odeint_inner(next(iter(ivars)))
elif not ivars:
from sage.symbolic.ring import SR
with SR.temp_var() as ivar:
return desolve_odeint_inner(ivar)
else:
Expand Down
8 changes: 6 additions & 2 deletions src/sage/calculus/functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@
-a^3 + 3*a^2*x - 3*a*x^2 + x^3
"""

from .calculus import SR
from sage.symbolic.expression import Expression
from sage.structure.element import Expression


def simplify(f):
r"""
Expand Down Expand Up @@ -147,6 +147,7 @@ def derivative(f, *args, **kwds):
except AttributeError:
pass
if not isinstance(f, Expression):
from sage.symbolic.ring import SR
f = SR(f)
return f.derivative(*args, **kwds)

Expand Down Expand Up @@ -296,6 +297,7 @@ def integral(f, *args, **kwds):
pass

if not isinstance(f, Expression):
from sage.symbolic.ring import SR
f = SR(f)
return f.integral(*args, **kwds)

Expand Down Expand Up @@ -349,6 +351,7 @@ def limit(f, dir=None, taylor=False, **argv):
-limit((erf(x) - 1)*e^(x^2), x, +Infinity)
"""
if not isinstance(f, Expression):
from sage.symbolic.ring import SR
f = SR(f)
return f.limit(dir=dir, taylor=taylor, **argv)

Expand Down Expand Up @@ -392,6 +395,7 @@ def taylor(f, *args):
(x - 1)*(y + 1)^3 - 3*(x - 1)*(y + 1)^2 + (y + 1)^3 + 3*(x - 1)*(y + 1) - 3*(y + 1)^2 - x + 3*y + 3
"""
if not isinstance(f, Expression):
from sage.symbolic.ring import SR
f = SR(f)
return f.taylor(*args)

Expand Down
7 changes: 3 additions & 4 deletions src/sage/calculus/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
Calculus functions
"""
from sage.matrix.constructor import matrix
from sage.structure.element import is_Matrix
from sage.structure.element import is_Vector
from sage.symbolic.ring import is_SymbolicVariable
from sage.structure.element import is_Matrix, is_Vector, Expression

from .functional import diff


Expand Down Expand Up @@ -82,7 +81,7 @@ def wronskian(*args):
# a 1x1 Wronskian is just its argument
return args[0]
else:
if is_SymbolicVariable(args[-1]):
if isinstance(args[-1], Expression) and args[-1].is_symbol():
# if last argument is a variable, peel it off and
# differentiate the other args
v = args[-1]
Expand Down
6 changes: 4 additions & 2 deletions src/sage/calculus/var.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -384,10 +384,12 @@ def clear_vars():
sage: k
15
"""
from sage.structure.element import Expression

G = globals()
from sage.symbolic.ring import is_SymbolicVariable
for i in list(range(65, 65 + 26)) + list(range(97, 97 + 26)):
if chr(i) in G and is_SymbolicVariable(G[chr(i)]):
chr_i = chr(i)
if chr_i in G and isinstance(G[chr_i], Expression) and G[chr_i].is_symbol():
# We check to see if there is a corresponding pyobject
# associated with the expression. This will work for
# constants which we want to keep, but will fail for
Expand Down
4 changes: 2 additions & 2 deletions src/sage/interfaces/maxima_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@
# https://www.gnu.org/licenses/
# ****************************************************************************

from sage.structure.element import Expression
from sage.symbolic.ring import SR

from sage.libs.ecl import EclObject, ecl_eval
Expand Down Expand Up @@ -1615,9 +1616,8 @@ def sr_to_max(expr):
# For that, we should change the API of the functions there
# (we need to have access to op, not only to expr.operands()
if isinstance(op, FDerivativeOperator):
from sage.symbolic.ring import is_SymbolicVariable
args = expr.operands()
if (not all(is_SymbolicVariable(v) for v in args) or
if (not all(isinstance(v, Expression) and v.is_symbol() for v in args) or
len(args) != len(set(args))):
# An evaluated derivative of the form f'(1) is not a
# symbolic variable, yet we would like to treat it
Expand Down
5 changes: 3 additions & 2 deletions src/sage/symbolic/assumptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
from sage.rings.rational_field import QQ
from sage.rings.real_mpfr import RR
from sage.rings.cc import CC
from sage.symbolic.ring import is_SymbolicVariable
from sage.structure.element import Expression
from sage.structure.unique_representation import UniqueRepresentation

# #30074: We use the keys of a dict to store the assumptions.
Expand Down Expand Up @@ -427,7 +427,8 @@ def preprocess_assumptions(args):
if isinstance(x, str):
del args[i]
last = x
elif ((not hasattr(x, 'assume') or is_SymbolicVariable(x))
elif ((not hasattr(x, 'assume')
or (isinstance(x, Expression) and x.is_symbol()))
and last is not None):
args[i] = GenericDeclaration(x, last)
else:
Expand Down
4 changes: 2 additions & 2 deletions src/sage/symbolic/callable.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,11 +490,11 @@ def create_key(self, args, check=True):
(x, y)
"""
if check:
from sage.symbolic.ring import is_SymbolicVariable
from sage.structure.element import Expression
if len(args) == 1 and isinstance(args[0], (list, tuple)):
args, = args
for arg in args:
if not is_SymbolicVariable(arg):
if not (isinstance(arg, Expression) and arg.is_symbol()):
raise TypeError("must construct a function with a tuple (or list) of variables")
args = tuple(args)
return args
Expand Down
12 changes: 5 additions & 7 deletions src/sage/symbolic/expression.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,7 @@ def _subs_make_dict(s):
"""
if isinstance(s, dict):
return s
elif is_SymbolicEquation(s):
elif isinstance(s, Expression) and s.is_relational():
if s.operator() is not operator.eq:
msg = "can only substitute equality, not inequalities; got {}"
raise TypeError(msg.format(s))
Expand Down Expand Up @@ -692,7 +692,7 @@ def _subs_fun_make_dict(s):
"""
if isinstance(s, dict):
return dict((k, v) if not isinstance(k, Expression) else (k.operator(), v.function(*k.operands())) for k, v in s.items())
elif is_SymbolicEquation(s):
elif isinstance(s, Expression) and s.is_relational():
if s.operator() is not operator.eq:
msg = "can only substitute equality, not inequalities; got {}"
raise TypeError(msg.format(s))
Expand Down Expand Up @@ -6810,12 +6810,11 @@ cdef class Expression(Expression_abc):
# we override type checking in CallableSymbolicExpressionRing,
# since it checks for old SymbolicVariable's
# and do the check here instead
from sage.symbolic.callable import CallableSymbolicExpressionRing
from sage.symbolic.ring import is_SymbolicVariable
for i in args:
if not is_SymbolicVariable(i):
if not (isinstance(i, Expression) and i.is_symbol()):
break
else:
from sage.symbolic.callable import CallableSymbolicExpressionRing
R = CallableSymbolicExpressionRing(args, check=False)
return R(self)
raise TypeError(f"must construct a function with symbolic variables as arguments, got {args}.")
Expand Down Expand Up @@ -12881,7 +12880,6 @@ cdef class Expression(Expression_abc):
sage: plot(f,0,1)
Graphics object consisting of 1 graphics primitive
"""
from sage.symbolic.ring import is_SymbolicVariable
from sage.plot.plot import plot

# see if the user passed a variable in.
Expand All @@ -12890,7 +12888,7 @@ cdef class Expression(Expression_abc):
else:
param = None
for i, arg in enumerate(args):
if is_SymbolicVariable(arg):
if isinstance(arg, Expression) and arg.is_symbol():
param = arg
args = args[:i] + args[i+1:]
break
Expand Down
6 changes: 2 additions & 4 deletions src/sage/symbolic/expression_conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -579,11 +579,10 @@ def derivative(self, ex, operator):
"""
# This code should probably be moved into the interface
# object in a nice way.
from sage.symbolic.ring import is_SymbolicVariable
if self.name_init != "_maxima_init_":
raise NotImplementedError
args = ex.operands()
if (not all(is_SymbolicVariable(v) for v in args) or
if (not all(isinstance(v, Expression) and v.is_symbol() for v in args) or
len(args) != len(set(args))):
# An evaluated derivative of the form f'(1) is not a
# symbolic variable, yet we would like to treat it like
Expand Down Expand Up @@ -1103,12 +1102,11 @@ def derivative(self, ex, operator):
,1,1,2
"""
from sage.symbolic.ring import is_SymbolicVariable
args = ex.operands() # the arguments the derivative is evaluated at
params = operator.parameter_set()
params_set = set(params)
mult = ",".join(str(params.count(i)) for i in params_set)
if (not all(is_SymbolicVariable(v) for v in args) or
if (not all(isinstance(v, Expression) and v.is_symbol() for v in args) or
len(args) != len(set(args))):
# An evaluated derivative of the form f'(1) is not a
# symbolic variable, yet we would like to treat it like
Expand Down
11 changes: 6 additions & 5 deletions src/sage/symbolic/integration/integral.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
# (at your option) any later version.
# https://www.gnu.org/licenses/
# ****************************************************************************`
from sage.symbolic.ring import SR, is_SymbolicVariable
from sage.structure.element import Expression
from sage.symbolic.ring import SR
from sage.symbolic.function import BuiltinFunction

##################################################################
Expand Down Expand Up @@ -113,7 +114,7 @@ def _eval_(self, f, x):
-1/2*x^2*sgn(x) + 3/2*x^2
"""
# Check for x
if not is_SymbolicVariable(x):
if not (isinstance(x, Expression) and x.is_symbol()):
if len(x.variables()) == 1:
nx = x.variables()[0]
f = f * x.diff(nx)
Expand Down Expand Up @@ -173,7 +174,7 @@ def _print_latex_(self, f, x):
\int \frac{\tan\left(x\right)}{x}\,{d x}
"""
from sage.misc.latex import latex
if not is_SymbolicVariable(x):
if not (isinstance(x, Expression) and x.is_symbol()):
dx_str = "{d \\left(%s\\right)}" % latex(x)
else:
dx_str = "{d %s}" % latex(x)
Expand Down Expand Up @@ -236,7 +237,7 @@ def _eval_(self, f, x, a, b):
-1
"""
# Check for x
if not is_SymbolicVariable(x):
if not (isinstance(x, Expression) and x.is_symbol()):
if len(x.variables()) == 1:
nx = x.variables()[0]
f = f * x.diff(nx)
Expand Down Expand Up @@ -346,7 +347,7 @@ def _print_latex_(self, f, x, a, b):
\int_{0}^{1} \frac{\tan\left(x\right)}{x}\,{d x}
"""
from sage.misc.latex import latex
if not is_SymbolicVariable(x):
if not (isinstance(x, Expression) and x.is_symbol()):
dx_str = "{d \\left(%s\\right)}" % latex(x)
else:
dx_str = "{d %s}" % latex(x)
Expand Down
Loading

0 comments on commit 98bf731

Please sign in to comment.