Search code examples
pythonsympysymbolic-math

Is there a way to handle constant function parameters in SymPy?


I am generating symbolic functions and using SymPy to simplify them. Now I would like a way to "simplify" symbols that represent constant parameters in a function that is yet to be fitted. For example, if I am generating a polynomial, I might generate a string like this

C*x*x + C*x + C*x + C,

which SymPy would turn into

C*x^2 + 2*C*x + C.

Now I would like to find a way to get this:

C*x^2 + C*x + C.

In other words, is there a way to tell SymPy that a certain symbol is constant and undefined, so that

C+C -> C, C*C -> C, etc. Or more generally: f(C) = C, for any f(C)?

My first idea was that perhaps there is an assumption (such as Q.positive) that describes this property and I might be able to use refine. However, this does not seem to be the case. If nothing else, I'm sure there is a way to use preorder_traversal to do what I want, but I can't come up with a strategy to do it. Any help or ideas are appreciated.


Solution

  • Perhaps something like this (applied to an expression that has been fully expanded):

    def consim(eq, *v):
        con = numbered_symbols('c', cls=Dummy)
        reps = {}
        for i in preorder_traversal(eq):
            if i.is_Mul or i.is_Add:
                c, d = i.as_independent(*v)
                if c != i.identity and c.free_symbols:
                    c = reps.setdefault(c, next(con))
        return eq.subs(reps)
    
    
    >>> from sympy.abc import a, b, c, d, x
    >>> eq = 2*a*x**2 + b*c*x + d + e
    >>> consim(eq, x)
             2
    c₀ + c₁⋅x  + c₂⋅x
    

    You probably want numbered symbols, not all symbols the same.