How To Add Knowledge To SymPy
Your Daily Dose of Computer Algebra
About this series: Learning to use computer algebra systems with ease requires a lot of practice. To help you on your journey to mastery, follow this series and solve common and not-so-common problems using systems like SymPy, Sage, or Mathematica.
In yesterday’s article, I showed you how to find out which rules for rewriting mathematical terms are available in SymPy. While in many cases, the existing rules are fine, all too often, the one rule you need, is not yet there. But, no problem: just add your own rewriting rules! It’s quite easy, but not well documented. So this article will show you how you can do it.
As a simple example, suppose we want to rewrite the expression

We know that there are addition theorems for trigonometric functions. So we might expect SymPy to have rewriting rules for applying those theorems. Surprisingly this is not the case! So, as a simple use case, let’s add our own rule for rewriting sines and cosines in terms of their half-angle equivalents. Mathematically, we have

and

How do we add this knowledge as a rewriting rule in SymPy?
As discussed in yesterday’s post, already implemented rewriting rules have implemented private methods with names starting with _eval_rewrite_as_. But each function in SymPy also has a private method _eval_rewrite(without …as…). Normally, this function is doing nothing, but if you overwrite it, it will do whatever you want.
The signature of _eval_rewrite is:
_eval_rewrite(self, rule, args, **hints)self refers to the object to which we want to attach the rule (in our case sin and cos). rule is an identifier for the rule and can be anything, args are the arguments of the object (in our case 2*x) and hints are optional keyword arguments that we won't need.
To implement rules, just write normal Python functions with matching signatures:

Then, attach the rules to the objects by overwriting _eval_rewrite.

From now on, sin and cos know about the half-angle theorem! Let’s try to apply the new rule to our expression:

which is what we expected. To only apply it to, say, the sine, use the pattern list syntax, as described in yesterday’s post.

If you want to attach more rules, just add more if-statements to your custom functions.
Of course, this was only a very simple example, but I think you see that this is very powerful. You can easily add knowledge about functions and object to SymPy and from that on use that knowledge in term rewriting.
If you found this article useful, you may want to consider becoming a Medium member to get unlimited access to all Medium articles. By registering using this link you can even support me as a writer.






