Speed perfomance using sympy.simplify in python

Viewed 40

As part of a project on differential equations, I have a function that replaces the variable 'y' by a mathematical expression (sympy class or int) and that simplifies the result as much as possible to use it later in my program.

Here is the code corresponding to my description :

def get_ode_with_proposed_equations(self, ode, undefined_equation, proposed_equation):
        """This function replaces an undefined equation in the differential
        equation with the corresponding proposed solution. However, the
        algorithm can be very slow at times which can make you think that
        the algorithm is frozen.

        Parameter:
            ode (sympy): ode is for Ordinary Differential Equation. It is
            the differential equation that we want to solve.

            undefined_equation (sympy symbol): An equation symbolized by "y"
            followed by the corresponding index. i.e "y3"

            proposed_equation (sympy expression): A sympy mathematical equation.
            i.e exp(x) + sin(x)

        Return:
            sympy expression: The Ordinary Differential Equation but with the
            proposed equation instead of the undefined equation.
        """
        try:
            return round(simplify(ode.subs(undefined_equation, proposed_equation).doit()))
        except TypeError:
            return simplify(ode.subs(undefined_equation, proposed_equation).doit())

The obstacle is without expectation a speed problem because sometimes it happens that my program is completely frozen. I used multiprocessing Pool to optimize this function. It helped for some expression but the algorithm can freeze time to time. I also tried to find an alternative of simplify because this method is very slow but it wasn't conclusive. So I would like to know if there is a way to improve the performance of this function knowing that I really have to simplify the result (e.g. I have to get 0 and not x -x +(1/2)*x**2 - (1/2)*x**2)

Thank you in advance

1 Answers

If you are just checking to see if a particular expression is a solution, consider function checkodesol. If you really just want a simplified version it would be good to see an example input and output using just subs that isn't as you would like it. Perhaps you only need to use expand_mul (or _mexpand) on the result instead of the more general simplify or expand.

Related