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.

First, some optional configuration - see Symbolic APIs below for more information:

import symforce


Some imports that are useful for notebooks - you’ll see these across many of our tutorials:

from symforce.notebook_util import display
from symforce.notebook_util import 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. symforce.symbolic includes both the supported parts of the underlying symbolic API, as well as all of the types from symforce.geo and 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: sin(y)/x**2 + 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 x^{2} + \frac{y^{5}}{120 x^{2}} - \frac{y^{3}}{6 x^{2}} + \frac{y}{x^{2}}$

Symbolic APIs#

SymForce supports two underling symbolic APIs. The SymPy API is pure Python, and the SymEngine API is a C++ implementation of much of SymPy. SymEngine is the default, and if you installed SymForce with pip or built it from source you’ll have it already. SymEngine is much faster than SymPy by a factor of 100 or more. However, SymEngine doesn’t implement everything SymPy does. SymForce abstracts over some of these differences, and adds support for some operations by converting between SymEngine and SymPy calls.

For how to set the symbolic api, see the docs for symforce.set_symbolic_api.