[RFC] Subs as container for parametric expressions

18 views
Skip to first unread message

Chris Smith

unread,
Sep 22, 2023, 7:07:59 PM9/22/23
to sympy
When SymPy returns an expression and needs to include a parameter, this presents some api challenges because in order for the use to use it in a `subs` call the user must know what the variable is. So sometimes we give the user the option to select the parameter or use a default symbol in the expression which they may or may not need to access to.

In issue #25720 I suggest the following possibility: use Subs to contain the expression and create a method that allows the values to be specified in an unambiguous way:

>>> n = Dummy('n'); s = Subs(pi/2 + n*pi, n, n); s
Subs(_n*pi + pi/2, _n, _n)

Define a Subs method:

def period(self, **k):
    e, x, V = list(self.args)
    reps = {xi: k[xi.name] for xi in x if xi.name in k}
    ek = e.xreplace(reps) 
    for xi in reps:
        i = x.index(xi)
        x.pop(i)
        V.pop(i)
    if not V: 
        return ek 
    return self.func(ek, x, V) 

>>> period(s, n=1)
3*pi/2

The `period` (or whatever name makes sense) is not using `subs` so it would never do more than affect the immediate subs since the Dummy is being selected from `x` and used in the `xreplace`. So if there were another Subs inside, it would not have a matching Dummy (as long as a new Dummy were used when needed).

Perhaps a Param class deriving from Subs could be used so the printing could omit the showing of the subtitution values. The `doit` method should also probably be removed or else the ability to easily access the parameters would be lost.

Wondering if others see benefit, issues or other solutions.

/c
Reply all
Reply to author
Forward
0 new messages