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.

# Configuration (optional)
import symforce

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:

import symforce.symbolic as sf

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

Build a symbolic expression:

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

This expression object is a tree of operations and arguments:

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:

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

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

$\displaystyle \frac{\cos{\left(y \right)}}{x^{2}}$
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)$