Autowrap module

Module for compiling codegen output, and wrap the binary for use in python.


To use the autowrap module it must first be imported

>>> from sympy.utilities.autowrap import autowrap

This module provides a common interface for different external backends, such as f2py, fwrap, Cython, SWIG(?) etc. (Currently only f2py and Cython are implemented) The goal is to provide access to compiled binaries of acceptable performance with a one-button user interface, i.e.

>>> from import x,y
>>> expr = ((x - y)**(25)).expand()
>>> binary_callable = autowrap(expr)           
>>> binary_callable(1, 2)                      

The callable returned from autowrap() is a binary python function, not a Sympy object. If it is desired to use the compiled function in symbolic expressions, it is better to use binary_function() which returns a Sympy Function object. The binary callable is attached as the _imp_ attribute and invoked when a numerical evaluation is requested with evalf(), or with lambdify().

>>> from sympy.utilities.autowrap import binary_function
>>> f = binary_function('f', expr)             
>>> 2*f(x, y) + y                              
y + 2*f(x, y)
>>> (2*f(x, y) + y).evalf(2, subs={x: 1, y:2}) 

The idea is that a SymPy user will primarily be interested in working with mathematical expressions, and should not have to learn details about wrapping tools in order to evaluate expressions numerically, even if they are computationally expensive.

When is this useful?

  1. For computations on large arrays, Python iterations may be too slow, and depending on the mathematical expression, it may be difficult to exploit the advanced index operations provided by NumPy.
  2. For really long expressions that will be called repeatedly, the compiled binary should be significantly faster than SymPy’s .evalf()
  3. If you are generating code with the codegen utility in order to use it in another project, the automatic python wrappers let you test the binaries immediately from within SymPy.
  4. To create customized ufuncs for use with numpy arrays. See ufuncify

When is this module NOT the best approach?

  1. If you are really concerned about speed or memory optimizations, you will probably get better results by working directly with the wrapper tools and the low level code. However, the files generated by this utility may provide a useful starting point and reference code. Temporary files will be left intact if you supply the keyword tempdir=”path/to/files/”.
  2. If the array computation can be handled easily by numpy, and you don’t need the binaries for another project.


The autowrap module works very well in tandem with the Indexed classes of the Tensor Module. Here is a simple example that shows how to setup a binary routine that calculates a matrix-vector product.

>>> from sympy.utilities.autowrap import autowrap
>>> from sympy import symbols, IndexedBase, Idx, Eq
>>> A, x, y = map(IndexedBase, ['A', 'x', 'y'])
>>> m, n = symbols('m n', integer=True)
>>> i = Idx('i', m)
>>> j = Idx('j', n)
>>> instruction = Eq(y[i], A[i, j]*x[j]); instruction
y[i] == A[i, j]*x[j]

Because the code printers treat Indexed objects with repeated indices as a summation, the above equality instance will be translated to low-level code for a matrix vector product. This is how you tell Sympy to generate the code, compile it and wrap it as a python function:

>>> matvec = autowrap(instruction)                 

That’s it. Now let’s test it with some numpy arrays. The default wrapper backend is f2py. The wrapper function it provides is set up to accept python lists, which it will silently convert to numpy arrays. So we can test the matrix vector product like this:

>>> M = [[0, 1],
...      [1, 0]]
>>> matvec(M, [2, 3])                              
[ 3.  2.]

More examples of usage are supplied with the Sympy installation. There is one example demonstrating basic usage of ufuncify, and another more elaborate example, showing how the autowrap module can be used to set up specialized binary integration routines.

User interface


sympy.utilities.autowrap.autowrap(expr, language='F95', backend='f2py', tempdir=None, args=None, flags=[], verbose=False, helpers=[])[source]

Generates python callable binaries based on the math expression.

The SymPy expression that should be wrapped as a binary routine
Optional arguments:
The programming language to use, currently ‘C’ or ‘F95’
The wrapper backend to use, currently f2py or Cython
Path to directory for temporary files. If this argument is supplied, the generated code and the wrapper input files are left intact in the specified path.
Sequence of the formal parameters of the generated code, if ommited the function signature is determined by the code generator.
Additional option flags that will be passed to the backend
If True, autowrap will not mute the command line backends. This can be helpful for debugging.
Used to define auxillary expressions needed for the main expr. If the main expression need to do call a specialized function it should be put in the `helpers’ list. Autowrap will then make sure that the compiled main expression can link to the helper routine. Items should be tuples with (<funtion_name>, <sympy_expression>, <arguments>). It is mandatory to supply an argument sequence to helper routines.
>>> from import x, y, z
>>> from sympy.utilities.autowrap import autowrap
>>> expr = ((x - y + z)**(13)).expand()
>>> binary_func = autowrap(expr)               
>>> binary_func(1, 4, 2)                       


sympy.utilities.autowrap.ufuncify(args, expr, **kwargs)[source]

Generates a binary ufunc-like lambda function for numpy arrays

Either a Symbol or a tuple of symbols. Specifies the argument sequence for the ufunc-like function.
A Sympy expression that defines the element wise operation
Optional keyword arguments are forwarded to autowrap().

The returned function can only act on one array at a time, as only the first argument accept arrays as input.


a proper numpy ufunc is required to support broadcasting, type casting and more. The function returned here, may not qualify for numpy’s definition of a ufunc. That why we use the term ufunc-like.


Examples :
>>> from sympy.utilities.autowrap import ufuncify
>>> from import x, y, z
>>> f = ufuncify([x, y], y + x**2)             
>>> f([1, 2, 3], 2)                            
[2.  5.  10.]


sympy.utilities.autowrap.binary_function(symfunc, expr, **kwargs)[source]

Returns a sympy function with expr as binary implementation

This is a convenience function that automates the steps needed to autowrap the Sympy expression and attaching it to a Function object with implemented_function().

>>> from import x, y, z
>>> from sympy.utilities.autowrap import binary_function
>>> expr = ((x - y)**(25)).expand()
>>> f = binary_function('f', expr)             
>>> type(f)                                    
<class 'sympy.core.function.FunctionClass'>
>>> 2*f(x, y)                                  
2*f(x, y)
>>> f(x, y).evalf(2, subs={x: 1, y: 2})        

Implementation details

The autowrap module is implemented with a backend consisting of CodeWrapper objects. The base class CodeWrapper takes care of details about module name, filenames and options. It also contains the driver routine, which runs through all steps in the correct order, and also takes care of setting up and removing the temporary working directory.

The actual compilation and wrapping is done by external resources, such as the system installed f2py command. The Cython backend runs a distutils setup script in a subprocess. Subclasses of CodeWrapper takes care of these backend-dependent details.

class sympy.utilities.autowrap.CodeWrapper(generator, filepath=None, flags=[], verbose=False)[source]

Base Class for code wrappers

class sympy.utilities.autowrap.F2PyCodeWrapper(generator, filepath=None, flags=[], verbose=False)[source]

Wrapper that uses f2py

class sympy.utilities.autowrap.CythonCodeWrapper(generator, filepath=None, flags=[], verbose=False)[source]

Wrapper that uses Cython

dump_pyx(routines, f, prefix, header=True, empty=True)[source]

Write a Cython file with python wrappers

This file contains all the definitions of the routines in c code and refers to the header file.

Arguments :
List of Routine instances
File-like object to write the file to
The filename prefix, used to refer to the proper header file. Only the basename of the prefix is used.
Optional. When True, empty lines are included to structure the source files. [DEFAULT=True]

Table Of Contents

Previous topic


Next topic


This Page