SymPy Tutorial

SymForce is built on the SymPy API for symbolic algebra. If you’re not familiar with SymPy or symbolic computation, go through their tutorial. Some basic usage is shown here.

[1]:
# Configuration (optional)
import symforce

symforce.set_symbolic_api("sympy")
symforce.set_log_level("warning")
from symforce.notebook_util import display, print_expression_tree

Always import the SymPy API through SymForce, because symforce can switch out the symbolic implementation of the API and adds a few minor but important augmentations. Let’s define some algebraic symbols:

[2]:
import symforce.symbolic as sf

x = sf.Symbol("x")
y = sf.Symbol("y")

Build a symbolic expression:

[3]:
expr = x ** 2 + sf.sin(y) / x ** 2
display(expr)
$\displaystyle x^{2} + \frac{\sin{\left(y \right)}}{x^{2}}$

This expression object is a tree of operations and arguments:

[4]:
print_expression_tree(expr)
Add: x**2 + sin(y)/x**2
+-Pow: x**2
| +-Symbol: x
| +-Integer: 2
+-Mul: sin(y)/x**2
  +-Pow: x**(-2)
  | +-Symbol: x
  | +-Integer: -2
  +-sin: sin(y)
    +-Symbol: y

We can evaluate this numerically by plugging in values:

[5]:
display(expr.subs({x: 1.2, y: 0.4}))
$\displaystyle 1.71042940438101$

We can perform symbolic manipulation like differentiation, integration, simplifiation, etc..

[6]:
display(expr.diff(y))
$\displaystyle \frac{\cos{\left(y \right)}}{x^{2}}$
[7]:
display(sf.series(expr, y))
$\displaystyle \frac{y}{x^{2}} - \frac{y^{3}}{6 x^{2}} + \frac{y^{5}}{120 x^{2}} + x^{2} + O\left(y^{6}\right)$