Cadabra
a field theory motivated approach to computer algebra

Using Cadabra and Sympy together

This notebook illustrates the interaction of Cadabra with Sympy. In particular, it shows how Cadabra expressions can be manipulated by Sympy if they are index-free (i.e. non-tensors). Cadabra allows you to enter mathematical expressions without a lot of declarations, and even without wrapping them in strings. Simply do the following:
ex:=(\sin(x)**2 + \cos(x)**2)/x;
\(\displaystyle{}\frac{\sin\left(x\right)^{2}+\cos\left(x\right)^{2}}{x}\)
Note the use of LaTeX notation for things like trigonometric functions. You can then directly call Sympy algorithms on these Cadabra expressions:
sympy.integrate(ex);
\(\displaystyle{}\log{\left (x \right )}\)
sympy.simplify(ex);
\(\displaystyle{}\frac{1}{x}\)
Note that for the time being this does not change the original Cadabra expression:
ex;
\(\displaystyle{}\frac{\sin\left(x\right)^{2}+\cos\left(x\right)^{2}}{x}\)
You can do more complicated things as well, like integrals and sums. Here is an example which is first entered in Cadabra form (which is inert), and then converted to Sympy, after which the integrals are evaluated by calling doit() on the Sympy expression. Again note the use of standard LaTeX-like constructions to write down integrals.
ex2:= \int{\sin(x) \cos(x)}{x} + \int{ x**2 }{x};
\(\displaystyle{}\int{}\sin\left(x\right) \cos\left(x\right)\, {\rm d}x+\int{}x^{2}\, {\rm d}x\)
You can print this in a Sympy-parseable form by using the _sympy_() method:
ex2._sympy_(); print(ex2._sympy_()) print(type(ex2._sympy_()))
\(\displaystyle{}\int x^{2}\, dx + \int \sin{\left (x \right )} \cos{\left (x \right )}\, dx\)
Integral(x**2, x) + Integral(sin(x)*cos(x), x)
<class 'sympy.core.add.Add'>
ex2._sympy_().doit();
\(\displaystyle{}\frac{x^{3}}{3} + \frac{1}{2} \sin^{2}{\left (x \right )}\)
Here's another example, of similar nature:
ex4:= x**2 - 3;
\(\displaystyle{}x^{2}-3\)
sympy.solve(ex4._sympy_());
\(\displaystyle{}- \sqrt{3}, \sqrt{3}\)
Of course, if you do not like or need Cadabra's input format, then you can happily use Sympy in the way you have always used it, but taking advantage of the display logic of the Cadabra notebook:
from sympy import * x,y=var('x,y') i = Integral(sin(x),(x,0,2));
\(\displaystyle{}\int_{0}^{2} \sin{\left (x \right )}\, dx\)
i.doit();
\(\displaystyle{}- \cos{\left (2 \right )} + 1\)
Hope this has triggered your interest; as usual, any feedback to mailto:info@cadabra.science is greatly appreciated.
Copyright © 2001-2017 Kasper Peeters
Questions? info@cadabra.science