This module provides functionality to generate directly compilable code from SymPy expressions. The codegen function is the user interface to the code generation functionality in SymPy. Some details of the implementation is given below for advanced users that may want to use the framework directly.
Note
The codegen callable is not in the sympy namespace automatically, to use it you must first execute
>>> from sympy.utilities.codegen import codegen
Here we present the most important pieces of the internal structure, as advanced users may want to use it directly, for instance by subclassing a code generator for a specialized application. It is very likely that you would prefer to use the codegen() function documented above.
Basic assumptions:
The Routine class is a very important piece of the codegen module. Viewing the codegen utility as a translator of mathematical expressions into a set of statements in a programming language, the Routine instances are responsible for extracting and storing information about how the math can be encapsulated in a function call. Thus, it is the Routine constructor that decides what arguments the routine will need and if there should be a return value.
module for generating C, C++, Fortran77, Fortran90, Julia and Octave/Matlab routines that evaluate sympy expressions. This module is work in progress. Only the milestones with a ‘+’ character in the list below have been completed.
— How is sympy.utilities.codegen different from sympy.printing.ccode? —
We considered the idea to extend the printing routines for sympy functions in such a way that it prints complete compilable code, but this leads to a few unsurmountable issues that can only be tackled with dedicated code generator:
— Basic assumptions —
— Milestones —
Generic description of evaluation routine for set of expressions.
A CodeGen class can translate instances of this class into code in a particular language. The routine specification covers all the features present in these languages. The CodeGen part must raise an exception when certain features are not present in the target language. For example, multiple return values are possible in Python, but not in C or Fortran. Another example: Fortran and Python support complex numbers, while C does not.
Holds strings for a certain datatype in different languages.
Derives an appropriate datatype based on the expression.
An abstract Argument data structure: a name and a data type.
This structure is refined in the descendants below.
An expression for a return value.
The name result is used to avoid conflicts with the reserved word “return” in the python language. It is also shorter than ReturnValue.
These may or may not need a name in the destination (e.g., “return(x*y)” might return a value without ever naming it).
Abstract class for the code generators.
Write the code by calling language specific methods.
The generated file contains all the definitions of the routines in low-level code and refers to the header file if appropriate.
Parameters : | routines : list
f : file-like
prefix : string
header : bool, optional
empty : bool, optional
|
---|
Creates an Routine object that is appropriate for this language.
This implementation is appropriate for at least C/Fortran. Subclasses can override this if necessary.
Here, we assume at most one return value (the l-value) which must be scalar. Additional outputs are OutputArguments (e.g., pointers on right-hand-side or pass-by-reference). Matrices are always returned via OutputArguments. If argument_sequence is None, arguments will be ordered alphabetically, but with all InputArguments first, and then OutputArgument and InOutArguments.
Writes all the source code files for the given routines.
The generated source is returned as a list of (filename, contents) tuples, or is written to files (see below). Each filename consists of the given prefix, appended with an appropriate extension.
Parameters : | routines : list
prefix : string
to_files : bool, optional
header : bool, optional
empty : bool, optional
|
---|
Generator for C code.
The .write() method inherited from CodeGen will output a code file and an interface file, <prefix>.c and <prefix>.h respectively.
Write the code by calling language specific methods.
The generated file contains all the definitions of the routines in low-level code and refers to the header file if appropriate.
Parameters : | routines : list
f : file-like
prefix : string
header : bool, optional
empty : bool, optional
|
---|
Writes the C header file.
This file contains all the function declarations.
Parameters : | routines : list
f : file-like
prefix : string
header : bool, optional
empty : bool, optional
|
---|
Generator for Fortran 95 code
The .write() method inherited from CodeGen will output a code file and an interface file, <prefix>.f90 and <prefix>.h respectively.
Write the code by calling language specific methods.
The generated file contains all the definitions of the routines in low-level code and refers to the header file if appropriate.
Parameters : | routines : list
f : file-like
prefix : string
header : bool, optional
empty : bool, optional
|
---|
Writes the interface to a header file.
This file contains all the function declarations.
Parameters : | routines : list
f : file-like
prefix : string
header : bool, optional
empty : bool, optional
|
---|
Generator for Julia code.
The .write() method inherited from CodeGen will output a code file <prefix>.jl.
Write the code by calling language specific methods.
The generated file contains all the definitions of the routines in low-level code and refers to the header file if appropriate.
Parameters : | routines : list
f : file-like
prefix : string
header : bool, optional
empty : bool, optional
|
---|
Generator for Octave code.
The .write() method inherited from CodeGen will output a code file <prefix>.m.
Octave .m files usually contain one function. That function name should match the filename (prefix). If you pass multiple name_expr pairs, the latter ones are presumed to be private functions accessed by the primary function.
You should only pass inputs to argument_sequence: outputs are ordered according to their order in name_expr.
Write the code by calling language specific methods.
The generated file contains all the definitions of the routines in low-level code and refers to the header file if appropriate.
Parameters : | routines : list
f : file-like
prefix : string
header : bool, optional
empty : bool, optional
|
---|
Generate source code for expressions in a given language.
Parameters : | name_expr : tuple, or list of tuples
language : string
prefix : string, optional
project : string, optional
to_files : bool, optional
header : bool, optional
empty : bool, optional
argument_sequence : iterable, optional
global_vars : iterable, optional
|
---|
Examples
>>> from sympy.utilities.codegen import codegen
>>> from sympy.abc import x, y, z
>>> [(c_name, c_code), (h_name, c_header)] = codegen(
... ("f", x+y*z), "C", "test", header=False, empty=False)
>>> print(c_name)
test.c
>>> print(c_code)
#include "test.h"
#include <math.h>
double f(double x, double y, double z) {
double f_result;
f_result = x + y*z;
return f_result;
}
>>> print(h_name)
test.h
>>> print(c_header)
#ifndef PROJECT__TEST__H
#define PROJECT__TEST__H
double f(double x, double y, double z);
#endif
Another example using Equality objects to give named outputs. Here the filename (prefix) is taken from the first (name, expr) pair.
>>> from sympy.abc import f, g
>>> from sympy import Eq
>>> [(c_name, c_code), (h_name, c_header)] = codegen(
... [("myfcn", x + y), ("fcn2", [Eq(f, 2*x), Eq(g, y)])],
... "C", header=False, empty=False)
>>> print(c_name)
myfcn.c
>>> print(c_code)
#include "myfcn.h"
#include <math.h>
double myfcn(double x, double y) {
double myfcn_result;
myfcn_result = x + y;
return myfcn_result;
}
void fcn2(double x, double y, double *f, double *g) {
(*f) = 2*x;
(*g) = y;
}
If the generated function(s) will be part of a larger project where various global variables have been defined, the ‘global_vars’ option can be used to remove the specified variables from the function signature
>>> from sympy.utilities.codegen import codegen
>>> from sympy.abc import x, y, z
>>> [(f_name, f_code), header] = codegen(
... ("f", x+y*z), "F95", header=False, empty=False,
... argument_sequence=(x, y), global_vars=(z,))
>>> print(f_code)
REAL*8 function f(x, y)
implicit none
REAL*8, intent(in) :: x
REAL*8, intent(in) :: y
f = x + y*z
end function
A factory that makes an appropriate Routine from an expression.
Parameters : | name : string
expr : expression or list/tuple of expressions
argument_sequence : list or tuple, optional
global_vars : iterable, optional
language : string, optional
A decision about whether to use output arguments or return values is made depending on both the language and the particular mathematical expressions. For an expression of type Equality, the left hand side is typically made into an OutputArgument (or perhaps an InOutArgument if appropriate). Otherwise, typically, the calculated expression is made a return values of the routine. |
---|
Examples
>>> from sympy.utilities.codegen import make_routine
>>> from sympy.abc import x, y, f, g
>>> from sympy import Eq
>>> r = make_routine('test', [Eq(f, 2*x), Eq(g, x + y)])
>>> [arg.result_var for arg in r.results]
[]
>>> [arg.name for arg in r.arguments]
[x, y, f, g]
>>> [arg.name for arg in r.result_variables]
[f, g]
>>> r.local_vars
set()
Another more complicated example with a mixture of specified and automatically-assigned names. Also has Matrix output.
>>> from sympy import Matrix
>>> r = make_routine('fcn', [x*y, Eq(f, 1), Eq(g, x + g), Matrix([[x, 2]])])
>>> [arg.result_var for arg in r.results]
[result_5397460570204848505]
>>> [arg.expr for arg in r.results]
[x*y]
>>> [arg.name for arg in r.arguments]
[x, y, f, g, out_8598435338387848786]
We can examine the various arguments more closely:
>>> from sympy.utilities.codegen import (InputArgument, OutputArgument,
... InOutArgument)
>>> [a.name for a in r.arguments if isinstance(a, InputArgument)]
[x, y]
>>> [a.name for a in r.arguments if isinstance(a, OutputArgument)]
[f, out_8598435338387848786]
>>> [a.expr for a in r.arguments if isinstance(a, OutputArgument)]
[1, Matrix([[x, 2]])]
>>> [a.name for a in r.arguments if isinstance(a, InOutArgument)]
[g]
>>> [a.expr for a in r.arguments if isinstance(a, InOutArgument)]
[g + x]