Contribute Media
A thank you to everyone who has made this possible: Read More

Automatic Code Generation with SymPy


Tutorial materials found here:

This tutorial will introduce code generation concepts using the SymPy library. SymPy is a pure Python library for symbolic mathematics. Code generation refers to the act of converting a SymPy symbolic expression into equivalent code in some language. This allows one to use SymPy to symbolically model a problem, and generate fast numerical code for specific platforms that executes that model. This is a powerful tool that is useful to scientists in many domains. Code generation allows users to speed up existing code, to deal only with the high level mathematics of a problem, avoids mathematical errors and typos, makes it possible to deal with expressions that would otherwise be too large to write by hand, and opens possibilities to perform automatic mathematical optimizations of expressions.

SymPy supports generating code for C, C++, Fortran, Matlab/Octave, Python, Cython, Julia, Javascript, LLVM, Rust, Haskell, Mathematica, Tensorflow, and Theano, and can easily be extended to other languages. SymPy’s code generation is used by libraries such as PyDy, pyodesys, sympybotics, pycalphad, and many other programs.

Learning objectives

Attendees will be able to:

  • write SymPy expressions describing mathematical functions and identify the function arguments and outputs.
  • use the SymPy code printers to transform SymPy expressions representing common domain specific functions into multiple output languages.
  • use the SymPy code generation routines to output compilable C code and use Cython to access these functions in Python.
  • generate custom vectorized functions with the three SymPy functions: lambdify, ufuncify, and autowrap.
  • create both custom code printers that make use of specialized C libraries and common subexpression elimination (CSE).
  • subclass the core SymPy printers and create a printer for a custom language.


Improve this page