Mathematical Modeling in SymPy

Presented by Jacob Maples (GS Comm)


Navigate the reveal.js slideshow with the arrow keys.

Go right to advance the slide, go down for details


WARNING: This presentation contains Python!

To Do:

  • wrap sympy.subsm sympy.solve
  • look at Kaggle notebook for creating a cell, use to generate a %%latex cell
  • create interface table
  • create entity figure (use script at work)
  • figure out multiline Latex print with sympy printer (no %%latex cell)
  • ipython nbconvert myslides.ipynb --to slides --post serve

SymPy Introduction


In [1]:
import sympy

In [2]:
print(sympy.__doc__)


SymPy is a Python library for symbolic mathematics. It aims to become a
full-featured computer algebra system (CAS) while keeping the code as simple
as possible in order to be comprehensible and easily extensible.  SymPy is
written entirely in Python. It depends on mpmath, and other external libraries
may be optionally for things like plotting support.

See the webpage for more information and documentation:

    http://sympy.org



In [3]:
help(sympy)


Help on package sympy:

NAME
    sympy

DESCRIPTION
    SymPy is a Python library for symbolic mathematics. It aims to become a
    full-featured computer algebra system (CAS) while keeping the code as simple
    as possible in order to be comprehensible and easily extensible.  SymPy is
    written entirely in Python. It depends on mpmath, and other external libraries
    may be optionally for things like plotting support.
    
    See the webpage for more information and documentation:
    
        http://sympy.org

PACKAGE CONTENTS
    abc
    assumptions (package)
    benchmarks (package)
    calculus (package)
    categories (package)
    combinatorics (package)
    concrete (package)
    conftest
    core (package)
    crypto (package)
    deprecated (package)
    diffgeom (package)
    external (package)
    functions (package)
    galgebra
    geometry (package)
    integrals (package)
    interactive (package)
    liealgebras (package)
    logic (package)
    matrices (package)
    ntheory (package)
    parsing (package)
    physics (package)
    plotting (package)
    polys (package)
    printing (package)
    release
    sandbox (package)
    series (package)
    sets (package)
    simplify (package)
    solvers (package)
    stats (package)
    strategies (package)
    tensor (package)
    unify (package)
    utilities (package)
    vector (package)

SUBMODULES
    add
    ask_generated
    assume
    basic
    bivariate
    boolalg
    cache
    class_registry
    combinatorial
    compatibility
    conditionset
    containers
    contains
    continued_fraction
    coreerrors
    cse_main
    cse_opts
    curve
    decorator
    decorators
    dense
    deutils
    elementary
    ellipse
    entity
    enumerative
    epathtools
    euler
    evalf
    exceptions
    expr
    expr_with_intlimits
    expr_with_limits
    expressions
    exprtools
    factor_
    facts
    fancysets
    finite_diff
    function
    generate
    gosper
    immutable
    index_methods
    indexed
    inequalities
    inference
    iterables
    line
    line3d
    magic
    manualintegrate
    meijerint
    memoization
    misc
    mod
    mul
    multidimensional
    multinomial
    numbers
    ode
    operations
    partitions_
    pde
    plane
    point
    polygon
    polysys
    power
    primetest
    products
    recurr
    relational
    residue_ntheory
    rules
    runtests
    singleton
    sparse
    special
    summations
    symbol
    timeutils
    transforms
    traversaltools
    trigonometry
    util

DATA
    C = <sympy.deprecated.class_registry.ClassRegistry object>
    CC = CC
    Catalan = Catalan
    E = E
    EX = EX
    EulerGamma = EulerGamma
    FU = {'L': <function L>, 'TR0': <function TR0>, 'TR1': <function TR1>,...
    GoldenRatio = GoldenRatio
    I = I
    Id = Lambda(_x, _x)
    Q = <sympy.assumptions.ask.AssumptionKeys object>
    QQ = QQ
    RR = RR
    S = S
    SYMPY_DEBUG = False
    ZZ = ZZ
    false = False
    grevlex = ReversedGradedLexOrder()
    grlex = GradedLexOrder()
    igrevlex = InverseOrder()
    igrlex = InverseOrder()
    ilex = InverseOrder()
    lex = LexOrder()
    nan = nan
    oo = oo
    pi = pi
    plot_backends = {'default': <class 'sympy.plotting.plot.DefaultBackend...
    sieve = <Sieve with 6 primes sieved: 2, 3, 5, ... 11, 13>
    true = True
    zoo = zoo

VERSION
    1.0

FILE
    c:\users\jimaples\appdata\local\continuum\anaconda3\lib\site-packages\sympy\__init__.py


Here are some examples of basic symbol operations:


In [4]:
x = sympy.Symbol('x')
y = x
x, x*2+1, y, type(y), x == y


Out[4]:
(x, 2*x + 1, x, sympy.core.symbol.Symbol, True)

In [5]:
try:
    x*y+z
except NameError as e:
    print(e)


name 'z' is not defined

In [6]:
sympy.symbols('x5:10'), sympy.symbols('x:z')


Out[6]:
((x5, x6, x7, x8, x9), (x, y, z))

In [7]:
X = sympy.numbered_symbols('variable')
[ next(X) for i in range(5) ]


Out[7]:
[variable0, variable1, variable2, variable3, variable4]

SymPy also handles expressions:


In [8]:
e = sympy.sympify('x*(x-1)+(x-1)')
e, sympy.factor(e), sympy.expand(e)


Out[8]:
(x*(x - 1) + x - 1, (x - 1)*(x + 1), x**2 - 1)

But most work of interest is more than single expressions, so here is a helper function to handle systems of equations.


In [9]:
from process import parseExpr
help(parseExpr)


Help on function parseExpr in module process:

parseExpr(expr='')
    Helper function to iterate through a list of equations


In [10]:
import inspect
print(inspect.getsource(parseExpr))


def parseExpr(expr=''):
    '''Helper function to iterate through a list of equations'''
    err = 'Malformed expression! Does not match "y = f(x)"\n  {0:s}'
    for s in expr.strip().split('\n'):
        # Parse anything that looks like an equation and isn't commented out
        if ('=' in s) and (s[0] != '#'):
            # convert expression to sympy
            y, f = list(map(str.strip, s.split('=',1)))
            y = sympy.Symbol(y)
            f = sympy.sympify(f)
            assert type(y) == sympy.symbol.Symbol, err.format(s)
            yield (y, f)

Example Use Case

Let's use a simple example to explore the additional functionality. Performing a 2-D rotation involves multiple dependant variables, independant variables, and functions.

$x' = x \cos \theta - y \sin \theta$

$y' = x \sin \theta + y \cos \theta$


In [11]:
inputs='x y theta'
outputs="x' y'"
expr='''
x' = x*cos(theta) - y*sin(theta)
y' = x*sin(theta) + y*cos(theta)
'''

ins = sympy.symbols(inputs)
outs = sympy.symbols(outputs)
eqn = dict(parseExpr(expr))

# No quote marks, the dictionary keys are SymPy symbols
ins, outs, eqn


Out[11]:
((x, y, theta),
 (x', y'),
 {x': x*cos(theta) - y*sin(theta), y': x*sin(theta) + y*cos(theta)})

Expression Trees

SymPy maintains a tree for all expressions. Everything in SymPy has .args and .func arguments that allow the expression (at that point in the tree) to be reconstructed. The .func argument is essentially the same as calling type and specifies whether the node is a add, multiply, cosine, some other function or a symbol. As you might expect, the .args attribute for leaves is empty.


In [12]:
expr_inputs = set()
expr_functs = set()
for arg in sympy.preorder_traversal(eqn[outs[0]]):
    print(arg.func, '\t', arg, '\t', arg.args)
    if arg.is_Symbol:
        expr_inputs.add(arg)
    elif arg.is_Function:
        expr_functs.add(arg.func)    
expr_inputs, expr_functs


<class 'sympy.core.add.Add'> 	 x*cos(theta) - y*sin(theta) 	 (x*cos(theta), -y*sin(theta))
<class 'sympy.core.mul.Mul'> 	 x*cos(theta) 	 (x, cos(theta))
<class 'sympy.core.symbol.Symbol'> 	 x 	 ()
cos 	 cos(theta) 	 (theta,)
<class 'sympy.core.symbol.Symbol'> 	 theta 	 ()
<class 'sympy.core.mul.Mul'> 	 -y*sin(theta) 	 (-1, y, sin(theta))
<class 'sympy.core.numbers.NegativeOne'> 	 -1 	 ()
<class 'sympy.core.symbol.Symbol'> 	 y 	 ()
sin 	 sin(theta) 	 (theta,)
<class 'sympy.core.symbol.Symbol'> 	 theta 	 ()
Out[12]:
({x, theta, y}, {cos, sin})

Adding Functionality

Before we go on, let's create a class around parseExpr so we can add object-oriented functionality.


In [13]:
from process import Block
print(inspect.getdoc(Block))
b = Block(expr, '2-D Rotate', inputs, outputs)


Block(expr, inputs='', outputs='', functions={})
Generic processing block that performs specified calculations on given inputs
in such a way to ease documentation
    
Creating Block(expr="\nx' = x*cos(theta) - y*sin(theta)\ny' = x*sin(theta) + y*cos(theta)\n", name='2-D Rotate', inputs='x y theta', outputs="x' y'", functions={})
outs=(x', y')

In [14]:
# spoiler alert!
print(inspect.getsource(Block.__init__))


    def __init__(self, expr, name='', inputs='', outputs='', functions={}):
        '''Create a Block instance'''
        
        if Block.verbose:
            s = 'Creating Block(expr={:s}, name={:s}, inputs={:s}, outputs={:s}, functions='
            s = s.format(*list(map(repr,[expr, name, inputs, outputs])))+'{'
            if functions:
                s_functions = []
                for k, v in functions.items():
                    s2 = k+':'+v.__name__
                    args, varargs, keywords, defaults = getargspec(v)
                    if varargs != None:
                        args += ['*args']
                    if keywords != None:
                        args += ['*kwargs']
                    s2 += '('+','.join(args)+')'
                    s_functions.append(s2)
                s += ','.join(s_functions)
            print(s+'})')
        
        self.name = name
        self.user = functions
        
        # save in list form for ordered outputs
        eqn = tuple(parseExpr(expr))
        self.eqn = tuple([ sympy.Eq(k, v) for k, v in eqn ])
        # placeholder for compiled expressions
        self.lambdas = {}
        
        # Extract inputs and functions used
        expr_inputs = set()
        expr_functs = set()
        for k, v in eqn:
            for arg in sympy.preorder_traversal(v):
                if arg.is_Symbol:
                    expr_inputs.add(arg)
                elif arg.is_Function:
                    expr_functs.add(arg.func)
        
        # save SymPy style .args and .func attributes
        self.args = tuple(expr_inputs)
        self.func = tuple(expr_functs)     
        
        if inputs:
            self.ins = sympy.symbols(inputs)
        else: # extract inputs from expr
            self.ins = tuple(self.args)
            
        outs = tuple([ i[0] for i in eqn ])
        if outputs:
            self.outs = sympy.symbols(outputs)
            print('outs='+repr(outs))
            self.hidden = tuple([ i for i in outs if i not in self.outs ])
        else: # extract inputs from expr
            self.outs = outs
            self.hidden = tuple()
            if Block.verbose:
                print('  Extracting outputs:', self.outs)
                
        # create _eval() wrapper function with useful docstring        
        self.eval = self._wrap_eval()

Convert SymPy equations to text


In [15]:
print('\n'.join( str(k)+' = '+sympy.pretty(v) for k,v in eqn.items() ))
print()
print('\n'.join( str(k)+' = '+str(v) for k,v in eqn.items() ))


x' = x⋅cos(θ) - y⋅sin(θ)
y' = x⋅sin(θ) + y⋅cos(θ)

x' = x*cos(theta) - y*sin(theta)
y' = x*sin(theta) + y*cos(theta)

So our Block instance can do the same thing, it needs to have pretty and __str__ functions defined. A __repr__ function could also be used to return a separate representation of the object.


In [16]:
b.pretty()
print(b)


Block: 2-D Rotate
x' = x⋅cos(θ) - y⋅sin(θ)
y' = x⋅sin(θ) + y⋅cos(θ)
Block: 2-D Rotate
Eq(x', x*cos(theta) - y*sin(theta))
Eq(y', x*sin(theta) + y*cos(theta))

In [17]:
print(inspect.getsource(b.pretty))
print(inspect.getsource(b.__str__))


    def pretty(self):
        '''Show a SymPy pretty print version of Block equations'''
        print('\nBlock:', self.name)
        print('\n'.join( sympy.pretty(e) for e in self.eqn ))

    def __str__(self):
        '''Support str calls on Block instances'''
        s  = 'Block: '+str(self.name)+'\n'
        s += '\n'.join( str(e).replace('==','=') for e in self.eqn )
        return s

Convert SymPy equations to LaTeX

Strings are well and good, but don't quite cut it for publications and presentations


In [18]:
# Generate a LaTeX string for the Jupyter notebook to render
print(' \\\\\n'.join([ str(k)+' = '+sympy.latex(v) for k, v in eqn.items() ]))


x' = x \cos{\left (\theta \right )} - y \sin{\left (\theta \right )} \\
y' = x \sin{\left (\theta \right )} + y \cos{\left (\theta \right )}

In [19]:
%%latex
$
x' = x \cos{\left (\theta \right )} - y \sin{\left (\theta \right )} \\
y' = x \sin{\left (\theta \right )} + y \cos{\left (\theta \right )}
$


$ x' = x \cos{\left (\theta \right )} - y \sin{\left (\theta \right )} \\ y' = x \sin{\left (\theta \right )} + y \cos{\left (\theta \right )} $

For our Block instance, the latex function doesn't need any arguments, so it can be handled as an attribute


In [20]:
print(b.latex)


\underline{\verb;Block: 2-D Rotate;} \\ 
x' = x \cos{\left (\theta \right )} - y \sin{\left (\theta \right )} \\ 
y' = x \sin{\left (\theta \right )} + y \cos{\left (\theta \right )}

In [21]:
%%latex
$
\underline{\verb;Block: 2-D Rotate;} \\ 
x' = x \cos{\left (\theta \right )} - y \sin{\left (\theta \right )} \\ 
y' = x \sin{\left (\theta \right )} + y \cos{\left (\theta \right )}
$


$ \underline{\verb;Block: 2-D Rotate;} \\ x' = x \cos{\left (\theta \right )} - y \sin{\left (\theta \right )} \\ y' = x \sin{\left (\theta \right )} + y \cos{\left (\theta \right )} $

In [22]:
f = inspect.getsource(Block).split('def ')
for i,s in enumerate(f):
    if s.startswith('latex'):
        # grab the last 2 lines from the previous code block, suppress the final newline
        print('\n'.join(f[i-1].rsplit('\n',2)[-2:]), end="")
        print('def '+s.strip())


    @property
    def latex(self):
        '''generate a latex version of Block equations'''
        # \verb;*; leaves contents unformatted
        s  = r'\underline{\verb;Block: '+str(self.name)+';} \\\\ \n'
        s += ' \\\\ \n'.join( sympy.latex(e) for e in self.eqn )
        return s

As a property, the latex function above is implicitly called instead of returning the function itself. Attempting to use inspect.getsource results in a TypeError since the LaTeX output isn't source code.


In [23]:
try:
    inspect.getsource(getattr(Block,'latex'))
except TypeError as e:
    print(type(e),' : ', e)


<class 'TypeError'>  :  <property object at 0x000000000724D9F8> is not a module, class, method, function, traceback, frame, or code object

We've seen a couple SymPy output formats. The init_printing function provides a lot of additional control over how symbols and expressions are shown, including LaTeX.


In [24]:
b.eqn


Out[24]:
(Eq(x', x*cos(theta) - y*sin(theta)), Eq(y', x*sin(theta) + y*cos(theta)))

In [25]:
sympy.init_printing(use_latex=True)
#sympy.init_printing(use_latex=False)

In [26]:
b.eqn


Out[26]:
$$\left ( x' = x \cos{\left (\theta \right )} - y \sin{\left (\theta \right )}, \quad y' = x \sin{\left (\theta \right )} + y \cos{\left (\theta \right )}\right )$$

In [27]:
sympy.Matrix(b.eqn)


Out[27]:
$$\left[\begin{matrix}x' = x \cos{\left (\theta \right )} - y \sin{\left (\theta \right )}\\y' = x \sin{\left (\theta \right )} + y \cos{\left (\theta \right )}\end{matrix}\right]$$

In [28]:
help(sympy.init_printing)


Help on function init_printing in module sympy.interactive.printing:

init_printing(pretty_print=True, order=None, use_unicode=None, use_latex=None, wrap_line=None, num_columns=None, no_global=False, ip=None, euler=False, forecolor='Black', backcolor='Transparent', fontsize='10pt', latex_mode='equation*', print_builtin=True, str_printer=None, pretty_printer=None, latex_printer=None)
    Initializes pretty-printer depending on the environment.
    
    Parameters
    ==========
    
    pretty_print: boolean
        If True, use pretty_print to stringify or the provided pretty
        printer; if False, use sstrrepr to stringify or the provided string
        printer.
    order: string or None
        There are a few different settings for this parameter:
        lex (default), which is lexographic order;
        grlex, which is graded lexographic order;
        grevlex, which is reversed graded lexographic order;
        old, which is used for compatibility reasons and for long expressions;
        None, which sets it to lex.
    use_unicode: boolean or None
        If True, use unicode characters;
        if False, do not use unicode characters.
    use_latex: string, boolean, or None
        If True, use default latex rendering in GUI interfaces (png and
        mathjax);
        if False, do not use latex rendering;
        if 'png', enable latex rendering with an external latex compiler,
        falling back to matplotlib if external compilation fails;
        if 'matplotlib', enable latex rendering with matplotlib;
        if 'mathjax', enable latex text generation, for example MathJax
        rendering in IPython notebook or text rendering in LaTeX documents
    wrap_line: boolean
        If True, lines will wrap at the end; if False, they will not wrap
        but continue as one line. This is only relevant if `pretty_print` is
        True.
    num_columns: int or None
        If int, number of columns before wrapping is set to num_columns; if
        None, number of columns before wrapping is set to terminal width.
        This is only relevant if `pretty_print` is True.
    no_global: boolean
        If True, the settings become system wide;
        if False, use just for this console/session.
    ip: An interactive console
        This can either be an instance of IPython,
        or a class that derives from code.InteractiveConsole.
    euler: boolean, optional, default=False
        Loads the euler package in the LaTeX preamble for handwritten style
        fonts (http://www.ctan.org/pkg/euler).
    forecolor: string, optional, default='Black'
        DVI setting for foreground color.
    backcolor: string, optional, default='Transparent'
        DVI setting for background color.
    fontsize: string, optional, default='10pt'
        A font size to pass to the LaTeX documentclass function in the
        preamble.
    latex_mode: string, optional, default='equation*'
        The mode used in the LaTeX printer. Can be one of:
        {'inline'|'plain'|'equation'|'equation*'}.
    print_builtin: boolean, optional, default=True
        If true then floats and integers will be printed. If false the
        printer will only print SymPy types.
    str_printer: function, optional, default=None
        A custom string printer function. This should mimic
        sympy.printing.sstrrepr().
    pretty_printer: function, optional, default=None
        A custom pretty printer. This should mimic sympy.printing.pretty().
    latex_printer: function, optional, default=None
        A custom LaTeX printer. This should mimic sympy.printing.latex()
        This should mimic sympy.printing.latex().
    
    Examples
    ========
    
    >>> from sympy.interactive import init_printing
    >>> from sympy import Symbol, sqrt
    >>> from sympy.abc import x, y
    >>> sqrt(5)
    sqrt(5)
    >>> init_printing(pretty_print=True) # doctest: +SKIP
    >>> sqrt(5) # doctest: +SKIP
      ___
    \/ 5
    >>> theta = Symbol('theta') # doctest: +SKIP
    >>> init_printing(use_unicode=True) # doctest: +SKIP
    >>> theta # doctest: +SKIP
    θ
    >>> init_printing(use_unicode=False) # doctest: +SKIP
    >>> theta # doctest: +SKIP
    theta
    >>> init_printing(order='lex') # doctest: +SKIP
    >>> str(y + x + y**2 + x**2) # doctest: +SKIP
    x**2 + x + y**2 + y
    >>> init_printing(order='grlex') # doctest: +SKIP
    >>> str(y + x + y**2 + x**2) # doctest: +SKIP
    x**2 + x + y**2 + y
    >>> init_printing(order='grevlex') # doctest: +SKIP
    >>> str(y * x**2 + x * y**2) # doctest: +SKIP
    x**2*y + x*y**2
    >>> init_printing(order='old') # doctest: +SKIP
    >>> str(x**2 + y**2 + x + y) # doctest: +SKIP
    x**2 + x + y**2 + y
    >>> init_printing(num_columns=10) # doctest: +SKIP
    >>> x**2 + x + y**2 + y # doctest: +SKIP
    x + y +
    x**2 + y**2

Rearranging Equations

SymPy can also handle sets of equations (sympy.Eq instances) to handle intermediate values or solve equations in terms of desired variables. Block can catch up later.


In [29]:
inputs='x y theta'
outputs="x' y'"
expr='''
x' = x*c - y*s
y' = x*s + y*c
c = cos(theta)
s = sin(theta)
'''

ins2 = sympy.symbols(inputs)
outs2 = sympy.symbols(outputs)
hidden2 = sympy.symbols('c s')
eqn2 = tuple(sympy.Eq(k,v) for k, v in parseExpr(expr))
ins2, outs2, eqn2


Out[29]:
$$\left ( \left ( x, \quad y, \quad \theta\right ), \quad \left ( x', \quad y'\right ), \quad \left ( x' = c x - s y, \quad y' = c y + s x, \quad c = \cos{\left (\theta \right )}, \quad s = \sin{\left (\theta \right )}\right )\right )$$

In [30]:
sympy.solve(eqn2, outs2+hidden2)


Out[30]:
$$\left \{ c : \cos{\left (\theta \right )}, \quad s : \sin{\left (\theta \right )}, \quad x' : x \cos{\left (\theta \right )} - y \sin{\left (\theta \right )}, \quad y' : x \sin{\left (\theta \right )} + y \cos{\left (\theta \right )}\right \}$$

In [31]:
help(sympy.solve)


Help on function solve in module sympy.solvers.solvers:

solve(f, *symbols, **flags)
    Algebraically solves equations and systems of equations.
    
    Currently supported are:
        - polynomial,
        - transcendental
        - piecewise combinations of the above
        - systems of linear and polynomial equations
        - sytems containing relational expressions.
    
    Input is formed as:
    
    * f
        - a single Expr or Poly that must be zero,
        - an Equality
        - a Relational expression or boolean
        - iterable of one or more of the above
    
    * symbols (object(s) to solve for) specified as
        - none given (other non-numeric objects will be used)
        - single symbol
        - denested list of symbols
          e.g. solve(f, x, y)
        - ordered iterable of symbols
          e.g. solve(f, [x, y])
    
    * flags
        'dict'=True (default is False)
            return list (perhaps empty) of solution mappings
        'set'=True (default is False)
            return list of symbols and set of tuple(s) of solution(s)
        'exclude=[] (default)'
            don't try to solve for any of the free symbols in exclude;
            if expressions are given, the free symbols in them will
            be extracted automatically.
        'check=True (default)'
            If False, don't do any testing of solutions. This can be
            useful if one wants to include solutions that make any
            denominator zero.
        'numerical=True (default)'
            do a fast numerical check if ``f`` has only one symbol.
        'minimal=True (default is False)'
            a very fast, minimal testing.
        'warn=True (default is False)'
            show a warning if checksol() could not conclude.
        'simplify=True (default)'
            simplify all but polynomials of order 3 or greater before
            returning them and (if check is not False) use the
            general simplify function on the solutions and the
            expression obtained when they are substituted into the
            function which should be zero
        'force=True (default is False)'
            make positive all symbols without assumptions regarding sign.
        'rational=True (default)'
            recast Floats as Rational; if this option is not used, the
            system containing floats may fail to solve because of issues
            with polys. If rational=None, Floats will be recast as
            rationals but the answer will be recast as Floats. If the
            flag is False then nothing will be done to the Floats.
        'manual=True (default is False)'
            do not use the polys/matrix method to solve a system of
            equations, solve them one at a time as you might "manually"
        'implicit=True (default is False)'
            allows solve to return a solution for a pattern in terms of
            other functions that contain that pattern; this is only
            needed if the pattern is inside of some invertible function
            like cos, exp, ....
        'particular=True (default is False)'
            instructs solve to try to find a particular solution to a linear
            system with as many zeros as possible; this is very expensive
        'quick=True (default is False)'
            when using particular=True, use a fast heuristic instead to find a
            solution with many zeros (instead of using the very slow method
            guaranteed to find the largest number of zeros possible)
        'cubics=True (default)'
            return explicit solutions when cubic expressions are encountered
        'quartics=True (default)'
            return explicit solutions when quartic expressions are encountered
        'quintics=True (default)'
            return explicit solutions (if possible) when quintic expressions
            are encountered
    
    Examples
    ========
    
    The output varies according to the input and can be seen by example::
    
        >>> from sympy import solve, Poly, Eq, Function, exp
        >>> from sympy.abc import x, y, z, a, b
        >>> f = Function('f')
    
    * boolean or univariate Relational
    
        >>> solve(x < 3)
        And(-oo < x, x < 3)
    
    * to always get a list of solution mappings, use flag dict=True
    
        >>> solve(x - 3, dict=True)
        [{x: 3}]
        >>> solve([x - 3, y - 1], dict=True)
        [{x: 3, y: 1}]
    
    * to get a list of symbols and set of solution(s) use flag set=True
    
        >>> solve([x**2 - 3, y - 1], set=True)
        ([x, y], set([(-sqrt(3), 1), (sqrt(3), 1)]))
    
    * single expression and single symbol that is in the expression
    
        >>> solve(x - y, x)
        [y]
        >>> solve(x - 3, x)
        [3]
        >>> solve(Eq(x, 3), x)
        [3]
        >>> solve(Poly(x - 3), x)
        [3]
        >>> solve(x**2 - y**2, x, set=True)
        ([x], set([(-y,), (y,)]))
        >>> solve(x**4 - 1, x, set=True)
        ([x], set([(-1,), (1,), (-I,), (I,)]))
    
    * single expression with no symbol that is in the expression
    
        >>> solve(3, x)
        []
        >>> solve(x - 3, y)
        []
    
    * single expression with no symbol given
    
          In this case, all free symbols will be selected as potential
          symbols to solve for. If the equation is univariate then a list
          of solutions is returned; otherwise -- as is the case when symbols are
          given as an iterable of length > 1 -- a list of mappings will be returned.
    
            >>> solve(x - 3)
            [3]
            >>> solve(x**2 - y**2)
            [{x: -y}, {x: y}]
            >>> solve(z**2*x**2 - z**2*y**2)
            [{x: -y}, {x: y}, {z: 0}]
            >>> solve(z**2*x - z**2*y**2)
            [{x: y**2}, {z: 0}]
    
    * when an object other than a Symbol is given as a symbol, it is
      isolated algebraically and an implicit solution may be obtained.
      This is mostly provided as a convenience to save one from replacing
      the object with a Symbol and solving for that Symbol. It will only
      work if the specified object can be replaced with a Symbol using the
      subs method.
    
          >>> solve(f(x) - x, f(x))
          [x]
          >>> solve(f(x).diff(x) - f(x) - x, f(x).diff(x))
          [x + f(x)]
          >>> solve(f(x).diff(x) - f(x) - x, f(x))
          [-x + Derivative(f(x), x)]
          >>> solve(x + exp(x)**2, exp(x), set=True)
          ([exp(x)], set([(-sqrt(-x),), (sqrt(-x),)]))
    
          >>> from sympy import Indexed, IndexedBase, Tuple, sqrt
          >>> A = IndexedBase('A')
          >>> eqs = Tuple(A[1] + A[2] - 3, A[1] - A[2] + 1)
          >>> solve(eqs, eqs.atoms(Indexed))
          {A[1]: 1, A[2]: 2}
    
        * To solve for a *symbol* implicitly, use 'implicit=True':
    
            >>> solve(x + exp(x), x)
            [-LambertW(1)]
            >>> solve(x + exp(x), x, implicit=True)
            [-exp(x)]
    
        * It is possible to solve for anything that can be targeted with
          subs:
    
            >>> solve(x + 2 + sqrt(3), x + 2)
            [-sqrt(3)]
            >>> solve((x + 2 + sqrt(3), x + 4 + y), y, x + 2)
            {y: -2 + sqrt(3), x + 2: -sqrt(3)}
    
        * Nothing heroic is done in this implicit solving so you may end up
          with a symbol still in the solution:
    
            >>> eqs = (x*y + 3*y + sqrt(3), x + 4 + y)
            >>> solve(eqs, y, x + 2)
            {y: -sqrt(3)/(x + 3), x + 2: (-2*x - 6 + sqrt(3))/(x + 3)}
            >>> solve(eqs, y*x, x)
            {x: -y - 4, x*y: -3*y - sqrt(3)}
    
        * if you attempt to solve for a number remember that the number
          you have obtained does not necessarily mean that the value is
          equivalent to the expression obtained:
    
            >>> solve(sqrt(2) - 1, 1)
            [sqrt(2)]
            >>> solve(x - y + 1, 1)  # /!\ -1 is targeted, too
            [x/(y - 1)]
            >>> [_.subs(z, -1) for _ in solve((x - y + 1).subs(-1, z), 1)]
            [-x + y]
    
        * To solve for a function within a derivative, use dsolve.
    
    * single expression and more than 1 symbol
    
        * when there is a linear solution
    
            >>> solve(x - y**2, x, y)
            [{x: y**2}]
            >>> solve(x**2 - y, x, y)
            [{y: x**2}]
    
        * when undetermined coefficients are identified
    
            * that are linear
    
                >>> solve((a + b)*x - b + 2, a, b)
                {a: -2, b: 2}
    
            * that are nonlinear
    
                >>> solve((a + b)*x - b**2 + 2, a, b, set=True)
                ([a, b], set([(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))]))
    
        * if there is no linear solution then the first successful
          attempt for a nonlinear solution will be returned
    
            >>> solve(x**2 - y**2, x, y)
            [{x: -y}, {x: y}]
            >>> solve(x**2 - y**2/exp(x), x, y)
            [{x: 2*LambertW(y/2)}]
            >>> solve(x**2 - y**2/exp(x), y, x)
            [{y: -x*sqrt(exp(x))}, {y: x*sqrt(exp(x))}]
    
    * iterable of one or more of the above
    
        * involving relationals or bools
    
            >>> solve([x < 3, x - 2])
            Eq(x, 2)
            >>> solve([x > 3, x - 2])
            False
    
        * when the system is linear
    
            * with a solution
    
                >>> solve([x - 3], x)
                {x: 3}
                >>> solve((x + 5*y - 2, -3*x + 6*y - 15), x, y)
                {x: -3, y: 1}
                >>> solve((x + 5*y - 2, -3*x + 6*y - 15), x, y, z)
                {x: -3, y: 1}
                >>> solve((x + 5*y - 2, -3*x + 6*y - z), z, x, y)
                {x: -5*y + 2, z: 21*y - 6}
    
            * without a solution
    
                >>> solve([x + 3, x - 3])
                []
    
        * when the system is not linear
    
            >>> solve([x**2 + y -2, y**2 - 4], x, y, set=True)
            ([x, y], set([(-2, -2), (0, 2), (2, -2)]))
    
        * if no symbols are given, all free symbols will be selected and a list
          of mappings returned
    
            >>> solve([x - 2, x**2 + y])
            [{x: 2, y: -4}]
            >>> solve([x - 2, x**2 + f(x)], set([f(x), x]))
            [{x: 2, f(x): -4}]
    
        * if any equation doesn't depend on the symbol(s) given it will be
          eliminated from the equation set and an answer may be given
          implicitly in terms of variables that were not of interest
    
            >>> solve([x - y, y - 3], x)
            {x: y}
    
    Notes
    =====
    
    solve() with check=True (default) will run through the symbol tags to
    elimate unwanted solutions.  If no assumptions are included all possible
    solutions will be returned.
    
        >>> from sympy import Symbol, solve
        >>> x = Symbol("x")
        >>> solve(x**2 - 1)
        [-1, 1]
    
    By using the positive tag only one solution will be returned:
    
        >>> pos = Symbol("pos", positive=True)
        >>> solve(pos**2 - 1)
        [1]
    
    
    Assumptions aren't checked when `solve()` input involves
    relationals or bools.
    
    When the solutions are checked, those that make any denominator zero
    are automatically excluded. If you do not want to exclude such solutions
    then use the check=False option:
    
        >>> from sympy import sin, limit
        >>> solve(sin(x)/x)  # 0 is excluded
        [pi]
    
    If check=False then a solution to the numerator being zero is found: x = 0.
    In this case, this is a spurious solution since sin(x)/x has the well known
    limit (without dicontinuity) of 1 at x = 0:
    
        >>> solve(sin(x)/x, check=False)
        [0, pi]
    
    In the following case, however, the limit exists and is equal to the the
    value of x = 0 that is excluded when check=True:
    
        >>> eq = x**2*(1/x - z**2/x)
        >>> solve(eq, x)
        []
        >>> solve(eq, x, check=False)
        [0]
        >>> limit(eq, x, 0, '-')
        0
        >>> limit(eq, x, 0, '+')
        0
    
    Disabling high-order, explicit solutions
    ----------------------------------------
    
    When solving polynomial expressions, one might not want explicit solutions
    (which can be quite long). If the expression is univariate, CRootOf
    instances will be returned instead:
    
        >>> solve(x**3 - x + 1)
        [-1/((-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)) - (-1/2 -
        sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3, -(-1/2 +
        sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3 - 1/((-1/2 +
        sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)), -(3*sqrt(69)/2 +
        27/2)**(1/3)/3 - 1/(3*sqrt(69)/2 + 27/2)**(1/3)]
        >>> solve(x**3 - x + 1, cubics=False)
        [CRootOf(x**3 - x + 1, 0),
         CRootOf(x**3 - x + 1, 1),
         CRootOf(x**3 - x + 1, 2)]
    
        If the expression is multivariate, no solution might be returned:
    
        >>> solve(x**3 - x + a, x, cubics=False)
        []
    
    Sometimes solutions will be obtained even when a flag is False because the
    expression could be factored. In the following example, the equation can
    be factored as the product of a linear and a quadratic factor so explicit
    solutions (which did not require solving a cubic expression) are obtained:
    
        >>> eq = x**3 + 3*x**2 + x - 1
        >>> solve(eq, cubics=False)
        [-1, -1 + sqrt(2), -sqrt(2) - 1]
    
    Solving equations involving radicals
    ------------------------------------
    
    Because of SymPy's use of the principle root (issue #8789), some solutions
    to radical equations will be missed unless check=False:
    
        >>> from sympy import root
        >>> eq = root(x**3 - 3*x**2, 3) + 1 - x
        >>> solve(eq)
        []
        >>> solve(eq, check=False)
        [1/3]
    
    In the above example there is only a single solution to the equation. Other
    expressions will yield spurious roots which must be checked manually;
    roots which give a negative argument to odd-powered radicals will also need
    special checking:
    
        >>> from sympy import real_root, S
        >>> eq = root(x, 3) - root(x, 5) + S(1)/7
        >>> solve(eq)  # this gives 2 solutions but misses a 3rd
        [CRootOf(7*_p**5 - 7*_p**3 + 1, 1)**15,
        CRootOf(7*_p**5 - 7*_p**3 + 1, 2)**15]
        >>> sol = solve(eq, check=False)
        >>> [abs(eq.subs(x,i).n(2)) for i in sol]
        [0.48, 0.e-110, 0.e-110, 0.052, 0.052]
    
        The first solution is negative so real_root must be used to see that
        it satisfies the expression:
    
        >>> abs(real_root(eq.subs(x, sol[0])).n(2))
        0.e-110
    
    If the roots of the equation are not real then more care will be necessary
    to find the roots, especially for higher order equations. Consider the
    following expression:
    
        >>> expr = root(x, 3) - root(x, 5)
    
    We will construct a known value for this expression at x = 3 by selecting
    the 1-th root for each radical:
    
        >>> expr1 = root(x, 3, 1) - root(x, 5, 1)
        >>> v = expr1.subs(x, -3)
    
    The solve function is unable to find any exact roots to this equation:
    
        >>> eq = Eq(expr, v); eq1 = Eq(expr1, v)
        >>> solve(eq, check=False), solve(eq1, check=False)
        ([], [])
    
    The function unrad, however, can be used to get a form of the equation for
    which numerical roots can be found:
    
        >>> from sympy.solvers.solvers import unrad
        >>> from sympy import nroots
        >>> e, (p, cov) = unrad(eq)
        >>> pvals = nroots(e)
        >>> inversion = solve(cov, x)[0]
        >>> xvals = [inversion.subs(p, i) for i in pvals]
    
    Although eq or eq1 could have been used to find xvals, the solution can
    only be verified with expr1:
    
        >>> z = expr - v
        >>> [xi.n(chop=1e-9) for xi in xvals if abs(z.subs(x, xi).n()) < 1e-9]
        []
        >>> z1 = expr1 - v
        >>> [xi.n(chop=1e-9) for xi in xvals if abs(z1.subs(x, xi).n()) < 1e-9]
        [-3.0]
    
    See Also
    ========
    
        - rsolve() for solving recurrence relationships
        - dsolve() for solving differential equations

Evaluating Expressions

SymPy can evaluate equations symbolically (.subs function) or numerically (.evalf function), at specified level of precision.


In [32]:
x = sympy.Symbol("x'")
eqn[x].subs(zip(ins, (1, 1, 45)))


Out[32]:
$$- \sin{\left (45 \right )} + \cos{\left (45 \right )}$$

In [33]:
eqn[x].evalf(4, subs=dict(zip(ins, (1, 1, 45))))


Out[33]:
$$-0.3256$$

In [34]:
# sanity check with NumPy
import numpy as np
-1*np.sin(45) + np.cos(45)


Out[34]:
$$-0.325581535716$$

In [35]:
e = sympy.sympify('sqrt(x)')
print(e.evalf(subs={'x':2}))
print(e.evalf(60, subs={'x':2}))


1.41421356237310
1.41421356237309504880168872420969807856967187537694807317668

In [36]:
print(sympy.pi.evalf())
print(sympy.pi.evalf(100))


3.14159265358979
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068

In [37]:
help(eqn[x].subs)


Help on method subs in module sympy.core.basic:

subs(*args, **kwargs) method of sympy.core.add.Add instance
    Substitutes old for new in an expression after sympifying args.
    
    `args` is either:
      - two arguments, e.g. foo.subs(old, new)
      - one iterable argument, e.g. foo.subs(iterable). The iterable may be
         o an iterable container with (old, new) pairs. In this case the
           replacements are processed in the order given with successive
           patterns possibly affecting replacements already made.
         o a dict or set whose key/value items correspond to old/new pairs.
           In this case the old/new pairs will be sorted by op count and in
           case of a tie, by number of args and the default_sort_key. The
           resulting sorted list is then processed as an iterable container
           (see previous).
    
    If the keyword ``simultaneous`` is True, the subexpressions will not be
    evaluated until all the substitutions have been made.
    
    Examples
    ========
    
    >>> from sympy import pi, exp, limit, oo
    >>> from sympy.abc import x, y
    >>> (1 + x*y).subs(x, pi)
    pi*y + 1
    >>> (1 + x*y).subs({x:pi, y:2})
    1 + 2*pi
    >>> (1 + x*y).subs([(x, pi), (y, 2)])
    1 + 2*pi
    >>> reps = [(y, x**2), (x, 2)]
    >>> (x + y).subs(reps)
    6
    >>> (x + y).subs(reversed(reps))
    x**2 + 2
    
    >>> (x**2 + x**4).subs(x**2, y)
    y**2 + y
    
    To replace only the x**2 but not the x**4, use xreplace:
    
    >>> (x**2 + x**4).xreplace({x**2: y})
    x**4 + y
    
    To delay evaluation until all substitutions have been made,
    set the keyword ``simultaneous`` to True:
    
    >>> (x/y).subs([(x, 0), (y, 0)])
    0
    >>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True)
    nan
    
    This has the added feature of not allowing subsequent substitutions
    to affect those already made:
    
    >>> ((x + y)/y).subs({x + y: y, y: x + y})
    1
    >>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True)
    y/(x + y)
    
    In order to obtain a canonical result, unordered iterables are
    sorted by count_op length, number of arguments and by the
    default_sort_key to break any ties. All other iterables are left
    unsorted.
    
    >>> from sympy import sqrt, sin, cos
    >>> from sympy.abc import a, b, c, d, e
    
    >>> A = (sqrt(sin(2*x)), a)
    >>> B = (sin(2*x), b)
    >>> C = (cos(2*x), c)
    >>> D = (x, d)
    >>> E = (exp(x), e)
    
    >>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)
    
    >>> expr.subs(dict([A, B, C, D, E]))
    a*c*sin(d*e) + b
    
    The resulting expression represents a literal replacement of the
    old arguments with the new arguments. This may not reflect the
    limiting behavior of the expression:
    
    >>> (x**3 - 3*x).subs({x: oo})
    nan
    
    >>> limit(x**3 - 3*x, x, oo)
    oo
    
    If the substitution will be followed by numerical
    evaluation, it is better to pass the substitution to
    evalf as
    
    >>> (1/x).evalf(subs={x: 3.0}, n=21)
    0.333333333333333333333
    
    rather than
    
    >>> (1/x).subs({x: 3.0}).evalf(21)
    0.333333333333333314830
    
    as the former will ensure that the desired level of precision is
    obtained.
    
    See Also
    ========
    replace: replacement capable of doing wildcard-like matching,
             parsing of match, and conditional replacements
    xreplace: exact node replacement in expr tree; also capable of
              using matching rules
    evalf: calculates the given formula to a desired level of precision


In [38]:
help(eqn[x].evalf)


Help on method evalf in module sympy.core.evalf:

evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False) method of sympy.core.add.Add instance
    Evaluate the given formula to an accuracy of n digits.
    Optional keyword arguments:
    
        subs=<dict>
            Substitute numerical values for symbols, e.g.
            subs={x:3, y:1+pi}. The substitutions must be given as a
            dictionary.
    
        maxn=<integer>
            Allow a maximum temporary working precision of maxn digits
            (default=100)
    
        chop=<bool>
            Replace tiny real or imaginary parts in subresults
            by exact zeros (default=False)
    
        strict=<bool>
            Raise PrecisionExhausted if any subresult fails to evaluate
            to full accuracy, given the available maxprec
            (default=False)
    
        quad=<str>
            Choose algorithm for numerical quadrature. By default,
            tanh-sinh quadrature is used. For oscillatory
            integrals on an infinite interval, try quad='osc'.
    
        verbose=<bool>
            Print debug information (default=False)

Compiling Expressions

For efficiency, sympy.lambdify is preferred for numerical analysis. It supports mathematical functions from math, sympy.Function, or mpmath. Since these library functions are compiled Python, C, or even Fortran, they are significantly faster than sympy.evalf.


In [39]:
rad=np.linspace(0, np.pi, 8+1)
f = sympy.lambdify(ins, eqn[x], 'numpy')
%timeit f(1,0,rad)


The slowest run took 4.76 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.01 µs per loop

In [40]:
%%timeit 
for i in rad: # evalf doesn't support arrays!
    eqn[x].evalf(subs={'x':1.0,'y':0.0,'theta':i})


10 loops, best of 3: 69.1 ms per loop

SymPy also supports uFuncify for generating binary functions (using f2py and Cython) and Theano for GPU support. These options are discussed in the SymPy documentation.


In [41]:
help(sympy.lambdify)


Help on function lambdify in module sympy.utilities.lambdify:

lambdify(args, expr, modules=None, printer=None, use_imps=True, dummify=True)
    Returns a lambda function for fast calculation of numerical values.
    
    If not specified differently by the user, SymPy functions are replaced as
    far as possible by either python-math, numpy (if available) or mpmath
    functions - exactly in this order. To change this behavior, the "modules"
    argument can be used. It accepts:
    
     - the strings "math", "mpmath", "numpy", "numexpr", "sympy"
     - any modules (e.g. math)
     - dictionaries that map names of sympy functions to arbitrary functions
     - lists that contain a mix of the arguments above, with higher priority
       given to entries appearing first.
    
    The default behavior is to substitute all arguments in the provided
    expression with dummy symbols. This allows for applied functions (e.g.
    f(t)) to be supplied as arguments. Call the function with dummify=False if
    dummy substitution is unwanted (and `args` is not a string). If you want
    to view the lambdified function or provide "sympy" as the module, you
    should probably set dummify=False.
    
    For functions involving large array calculations, numexpr can provide a
    significant speedup over numpy.  Please note that the available functions
    for numexpr are more limited than numpy but can be expanded with
    implemented_function and user defined subclasses of Function.  If specified,
    numexpr may be the only option in modules. The official list of numexpr
    functions can be found at:
    https://github.com/pydata/numexpr#supported-functions
    
    In previous releases ``lambdify`` replaced ``Matrix`` with ``numpy.matrix``
    by default. As of release 1.0 ``numpy.array`` is the default.
    To get the old default behavior you must pass in ``[{'ImmutableMatrix':
    numpy.matrix}, 'numpy']`` to the ``modules`` kwarg.
    
    >>> from sympy import lambdify, Matrix
    >>> from sympy.abc import x, y
    >>> import numpy
    >>> array2mat = [{'ImmutableMatrix': numpy.matrix}, 'numpy']
    >>> f = lambdify((x, y), Matrix([x, y]), modules=array2mat)
    >>> f(1, 2)
    matrix([[1],
            [2]])
    
    Usage
    =====
    
    (1) Use one of the provided modules:
    
        >>> from sympy import sin, tan, gamma
        >>> from sympy.utilities.lambdify import lambdastr
        >>> from sympy.abc import x, y
        >>> f = lambdify(x, sin(x), "math")
    
        Attention: Functions that are not in the math module will throw a name
                   error when the lambda function is evaluated! So this would
                   be better:
    
        >>> f = lambdify(x, sin(x)*gamma(x), ("math", "mpmath", "sympy"))
    
    (2) Use some other module:
    
        >>> import numpy
        >>> f = lambdify((x,y), tan(x*y), numpy)
    
        Attention: There are naming differences between numpy and sympy. So if
                   you simply take the numpy module, e.g. sympy.atan will not be
                   translated to numpy.arctan. Use the modified module instead
                   by passing the string "numpy":
    
        >>> f = lambdify((x,y), tan(x*y), "numpy")
        >>> f(1, 2)
        -2.18503986326
        >>> from numpy import array
        >>> f(array([1, 2, 3]), array([2, 3, 5]))
        [-2.18503986 -0.29100619 -0.8559934 ]
    
    (3) Use a dictionary defining custom functions:
    
        >>> def my_cool_function(x): return 'sin(%s) is cool' % x
        >>> myfuncs = {"sin" : my_cool_function}
        >>> f = lambdify(x, sin(x), myfuncs); f(1)
        'sin(1) is cool'
    
    Examples
    ========
    
    >>> from sympy.utilities.lambdify import implemented_function
    >>> from sympy import sqrt, sin, Matrix
    >>> from sympy import Function
    >>> from sympy.abc import w, x, y, z
    
    >>> f = lambdify(x, x**2)
    >>> f(2)
    4
    >>> f = lambdify((x, y, z), [z, y, x])
    >>> f(1,2,3)
    [3, 2, 1]
    >>> f = lambdify(x, sqrt(x))
    >>> f(4)
    2.0
    >>> f = lambdify((x, y), sin(x*y)**2)
    >>> f(0, 5)
    0.0
    >>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy')
    >>> row(1, 2)
    Matrix([[1, 3]])
    
    Tuple arguments are handled and the lambdified function should
    be called with the same type of arguments as were used to create
    the function.:
    
    >>> f = lambdify((x, (y, z)), x + y)
    >>> f(1, (2, 4))
    3
    
    A more robust way of handling this is to always work with flattened
    arguments:
    
    >>> from sympy.utilities.iterables import flatten
    >>> args = w, (x, (y, z))
    >>> vals = 1, (2, (3, 4))
    >>> f = lambdify(flatten(args), w + x + y + z)
    >>> f(*flatten(vals))
    10
    
    Functions present in `expr` can also carry their own numerical
    implementations, in a callable attached to the ``_imp_``
    attribute.  Usually you attach this using the
    ``implemented_function`` factory:
    
    >>> f = implemented_function(Function('f'), lambda x: x+1)
    >>> func = lambdify(x, f(x))
    >>> func(4)
    5
    
    ``lambdify`` always prefers ``_imp_`` implementations to implementations
    in other namespaces, unless the ``use_imps`` input parameter is False.

Note that sympy.lambdify also supports custom functions (e.g. conditional operations or reshaping arrays). These custom functions can also be optimized for computing as easily as including a @jit decorator from the numba library.


In [42]:
def my_sample(x):
    r = len(x) >> 1
    return np.reshape(x[:2*r], (r,2))

x = np.linspace(0, np.pi, 9+1)
print(x*180/np.pi) # degrees


[   0.   20.   40.   60.   80.  100.  120.  140.  160.  180.]

In [43]:
e = sympy.sympify('1+sample(x)')
print(e)

f = sympy.lambdify(sympy.Symbol('x'), e, {'sample':my_sample})
f(x)


sample(x) + 1
Out[43]:
array([[ 1.        ,  1.34906585],
       [ 1.6981317 ,  2.04719755],
       [ 2.3962634 ,  2.74532925],
       [ 3.0943951 ,  3.44346095],
       [ 3.7925268 ,  4.14159265]])

In [44]:
f = sympy.lambdify(sympy.Symbol('x'),               # inputs
                   sympy.sympify('sample(cos(x))'), # expressions
                   ('numpy', {'sample':my_sample})) # functions
# Note: Can also use empty function dictionary for consistency
f(x)


Out[44]:
array([[ 1.        ,  0.93969262],
       [ 0.76604444,  0.5       ],
       [ 0.17364818, -0.17364818],
       [-0.5       , -0.76604444],
       [-0.93969262, -1.        ]])

However, the documentation could be better. (Earlier versions didn't even include the expresion.)


In [45]:
help(f)


Help on function <lambda> in module numpy:

<lambda> lambda _Dummy_26
    Created with lambdify. Signature:
    
    func(x)
    
    Expression:
    
    sample(cos(x))

For more control over the output function, including the __doc__, __name__, and __signature__ attributes used by the help function, let's revisit the Block class to wrap the functionality seen so far.

All together now

As we've seen, all the information is available for a more informative way to manipulate and evaluate systems of equations.


In [46]:
b2 = Block('''c = cos(theta)
s = sin(theta)
x' = x*c - y*s
y' = x*s + y*c
''', '2-D Rotate', 'x y theta', "x' y'")
print('\n',vars(b2))


Creating Block(expr="c = cos(theta)\ns = sin(theta)\nx' = x*c - y*s\ny' = x*s + y*c\n", name='2-D Rotate', inputs='x y theta', outputs="x' y'", functions={})
outs=(c, s, x', y')

 {'ins': (x, y, theta), 'user': {}, 'outs': (x', y'), 'func': (sin, cos), 'args': (theta, s, c, x, y), 'hidden': (c, s), 'eval': <function <lambda> at 0x0000000007E09488>, 'name': '2-D Rotate', 'lambdas': {}, 'eqn': (Eq(c, cos(theta)), Eq(s, sin(theta)), Eq(x', c*x - s*y), Eq(y', c*y + s*x))}

When it comes to function arguments, Python 3.5 has had a lot of development beyond Python 2.7. Since the Block code was originally developed in Python 2.7, let's replace those _Dummy arguments from sympy.lambdify.


In [47]:
f = b2.lambdify()


Compiling Block '2-D Rotate' expressions:
Solving equations for unknowns: (x', y', c, s)
(Eq(c, cos(theta)), Eq(s, sin(theta)), Eq(x', c*x - s*y), Eq(y', c*y + s*x))
 = [{x': x*cos(theta) - y*sin(theta), s: sin(theta), c: cos(theta), y': x*sin(theta) + y*cos(theta)}] 

  x' = sympy.lambdify((x, y, theta), x*cos(theta) - y*sin(theta), '('numpy', [])')
  y' = sympy.lambdify((x, y, theta), x*sin(theta) + y*cos(theta), '('numpy', [])')

In [48]:
help(f["x'"])


Help on function Block(2-D Rotate).lambdas[x'] in Block(2-D Rotate):

Block(2-D Rotate).lambdas[x'](_Dummy_31, _Dummy_32, _Dummy_33)
    x' = x*cos(theta) - y*sin(theta)


In [49]:
# All lambdify calls are made with the full set of inputs
p = []
# Update the signatures for each compiled expression
for k in f.keys():
    sig=inspect.signature(f[k])
    if len(p) == 0:
        for i,s in zip(sig.parameters.values(), map(str, b2.ins)):
            p.append(i.replace(name=s))
    f[k].__signature__ = sig.replace(parameters=p)
    help(f[k])


Help on function Block(2-D Rotate).lambdas[y'] in Block(2-D Rotate):

Block(2-D Rotate).lambdas[y'](x, y, theta)
    y' = x*sin(theta) + y*cos(theta)

Help on function Block(2-D Rotate).lambdas[x'] in Block(2-D Rotate):

Block(2-D Rotate).lambdas[x'](x, y, theta)
    x' = x*cos(theta) - y*sin(theta)


In [50]:
import types

# backup functions before overwriting them
Block.__lambdify = Block.lambdify
b2.__lambdify = b2.lambdify

In [51]:
# Rename the old function
b2._lambdify = b2.lambdify
Block._lambdify = Block.lambdify

#test._lambdify = types.MethodType(test.lambdify, test)
#Block._lambdify = types.MethodType(Block.lambdify, Block)

In [52]:
def lambdify(self, *args, **kwargs):
    # Call the base function with any arguments
    self._lambdify(*args, **kwargs)
    # Update the signatures for each compiled expression
    for k in self.lambdas.keys():
        sig=inspect.signature(self.lambdas[k])
        p = []
        for i,s in zip(sig.parameters.values(), map(str, self.ins)):
            p.append(i.replace(name=s))
        self.lambdas[k].__signature__ = sig.replace(parameters=p)
    return self.lambdas

# update the old __doc__ string
lambdify.__doc__ = Block._lambdify.__doc__ + ' and set the arguments to the variable names'

# use the new function in the class and existing instance
b2.lambdify = types.MethodType(lambdify, b2)
Block.lambdify = types.MethodType(lambdify, Block)

In [53]:
f = b2.lambdify()


Compiling Block '2-D Rotate' expressions:
Solving equations for unknowns: (x', y', c, s)
(Eq(c, cos(theta)), Eq(s, sin(theta)), Eq(x', c*x - s*y), Eq(y', c*y + s*x))
 = [{x': x*cos(theta) - y*sin(theta), s: sin(theta), c: cos(theta), y': x*sin(theta) + y*cos(theta)}] 

  x' = sympy.lambdify((x, y, theta), x*cos(theta) - y*sin(theta), '('numpy', [])')
  y' = sympy.lambdify((x, y, theta), x*sin(theta) + y*cos(theta), '('numpy', [])')

In [54]:
help(f["x'"])


Help on function Block(2-D Rotate).lambdas[x'] in Block(2-D Rotate):

Block(2-D Rotate).lambdas[x'](x, y, theta)
    x' = x*cos(theta) - y*sin(theta)


In [55]:
help(inspect.Signature)


Help on class Signature in module inspect:

class Signature(builtins.object)
 |  A Signature object represents the overall signature of a function.
 |  It stores a Parameter object for each parameter accepted by the
 |  function, as well as information specific to the function itself.
 |  
 |  A Signature object has the following public attributes and methods:
 |  
 |  * parameters : OrderedDict
 |      An ordered mapping of parameters' names to the corresponding
 |      Parameter objects (keyword-only arguments are in the same order
 |      as listed in `code.co_varnames`).
 |  * return_annotation : object
 |      The annotation for the return type of the function if specified.
 |      If the function has no annotation for its return type, this
 |      attribute is set to `Signature.empty`.
 |  * bind(*args, **kwargs) -> BoundArguments
 |      Creates a mapping from positional and keyword arguments to
 |      parameters.
 |  * bind_partial(*args, **kwargs) -> BoundArguments
 |      Creates a partial mapping from positional and keyword arguments
 |      to parameters (simulating 'functools.partial' behavior.)
 |  
 |  Methods defined here:
 |  
 |  __eq__(self, other)
 |      Return self==value.
 |  
 |  __hash__(self)
 |      Return hash(self).
 |  
 |  __init__(self, parameters=None, *, return_annotation, __validate_parameters__=True)
 |      Constructs Signature from the given list of Parameter
 |      objects and 'return_annotation'.  All arguments are optional.
 |  
 |  __reduce__(self)
 |      helper for pickle
 |  
 |  __repr__(self)
 |      Return repr(self).
 |  
 |  __setstate__(self, state)
 |  
 |  __str__(self)
 |      Return str(self).
 |  
 |  bind(*args, **kwargs)
 |      Get a BoundArguments object, that maps the passed `args`
 |      and `kwargs` to the function's signature.  Raises `TypeError`
 |      if the passed arguments can not be bound.
 |  
 |  bind_partial(*args, **kwargs)
 |      Get a BoundArguments object, that partially maps the
 |      passed `args` and `kwargs` to the function's signature.
 |      Raises `TypeError` if the passed arguments can not be bound.
 |  
 |  replace(self, *, parameters=<class 'inspect._void'>, return_annotation=<class 'inspect._void'>)
 |      Creates a customized copy of the Signature.
 |      Pass 'parameters' and/or 'return_annotation' arguments
 |      to override them in the new copy.
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  from_builtin(func) from builtins.type
 |      Constructs Signature for the given builtin function.
 |  
 |  from_callable(obj, *, follow_wrapped=True) from builtins.type
 |      Constructs Signature for the given callable object.
 |  
 |  from_function(func) from builtins.type
 |      Constructs Signature for the given python function.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  parameters
 |  
 |  return_annotation
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  empty = <class 'inspect._empty'>
 |      Marker object for Signature.empty and Parameter.empty.

And since it's coming up, let's go ahead and improve the Block.eval function used to call the various lambdify functions. Extra credit to anyone who figures out why I couldn't do the same sort of __signature__ update without getting a NameError exception.


In [56]:
help(b2._eval)
help(b2.eval)


Help on method _eval in module process:

_eval(*args, **kwargs) method of process.Block instance
    evaluate outputs for given inputs

Help on function Block.eval in Block:

Block.eval(_Dummy_27, _Dummy_28, _Dummy_29)
    Calculate outputs (x', y') as follows:
      Eq(c, cos(theta))
      Eq(s, sin(theta))
      Eq(x', c*x - s*y)
      Eq(y', c*y + s*x)
    
    Block.outputMode = 'dict'


In [57]:
# Backup the old functions
b2._eval_save = b2.eval
Block._wrap_eval_save = Block._wrap_eval

In [58]:
# instead of wrapping _eval, just update its help info
def wrap_eval(self):
    '''create _eval() wrapper function with useful docstring'''

    def tuple_repr(i):
        if type(i) == tuple:
            o = i
            s = repr(i)
        else:
            ins = (i,)
            s = '('+repr(i)+')'
        return o, s

    ins, s_ins = tuple_repr(self.ins)
    outs, s_outs = tuple_repr(self.outs)
    f = self._eval
            
    f.__func__.__name__ = str(self.__class__.__name__)+'('+self.name+').eval'
    s = 'Given inputs '+s_ins+', calculate outputs '+s_outs+' as follows:'
    for e in self.eqn:
        s += '\n  '+str(e.lhs)+' = '+str(e.rhs)
    s += '\n\nBlock.outputMode = '+repr(Block.outputMode)+'\n'
    f.__func__.__doc__ = s
    
    return f

b2.eval = wrap_eval(b2)

# use the new function in the class
Block._wrap_eval = types.MethodType(wrap_eval, Block)

In [59]:
help(b2.eval)

b2.eval(1.0,2.0,3.0)


Help on method Block(2-D Rotate).eval in Block(2-D Rotate):

Block(2-D Rotate).eval(*args, **kwargs) method of process.Block instance
    Given inputs (x, y, theta), calculate outputs (x', y') as follows:
      c = cos(theta)
      s = sin(theta)
      x' = c*x - s*y
      y' = c*y + s*x
    
    Block.outputMode = 'dict'


Block.eval(x=1.0, y=2.0, theta=3.0, output='dict')

Out[59]:
{"2-D Rotate.x'": -1.2722325127201799, "2-D Rotate.y'": -1.8388649851410237}

The outputs were specified when the Block instance was created, so lambdify all of those.


In [60]:
f = b2.lambdify()
f, b2.lambdas


Compiling Block '2-D Rotate' expressions:
Solving equations for unknowns: (x', y', c, s)
(Eq(c, cos(theta)), Eq(s, sin(theta)), Eq(x', c*x - s*y), Eq(y', c*y + s*x))
 = [{x': x*cos(theta) - y*sin(theta), s: sin(theta), c: cos(theta), y': x*sin(theta) + y*cos(theta)}] 

  x' = sympy.lambdify((x, y, theta), x*cos(theta) - y*sin(theta), '('numpy', [])')
  y' = sympy.lambdify((x, y, theta), x*sin(theta) + y*cos(theta), '('numpy', [])')
Out[60]:
({"x'": <function numpy.<lambda>>, "y'": <function numpy.<lambda>>},
 {"x'": <function numpy.<lambda>>, "y'": <function numpy.<lambda>>})

In [61]:
help(f["x'"])


Help on function Block(2-D Rotate).lambdas[x'] in Block(2-D Rotate):

Block(2-D Rotate).lambdas[x'](x, y, theta)
    x' = x*cos(theta) - y*sin(theta)

The functions were made using sympy.lambdify, so they get all the benefits like support for NumPy arrays. The Block class also has an eval function to use that calls all the lambdify results.


In [62]:
out = f["x'"](1,0,np.linspace(0, np.pi, 8+1))
print(out, type(out))


[  1.00000000e+00   9.23879533e-01   7.07106781e-01   3.82683432e-01
   6.12323400e-17  -3.82683432e-01  -7.07106781e-01  -9.23879533e-01
  -1.00000000e+00] <class 'numpy.ndarray'>

In [63]:
help(b2.eval)


Help on method Block(2-D Rotate).eval in Block(2-D Rotate):

Block(2-D Rotate).eval(*args, **kwargs) method of process.Block instance
    Given inputs (x, y, theta), calculate outputs (x', y') as follows:
      c = cos(theta)
      s = sin(theta)
      x' = c*x - s*y
      y' = c*y + s*x
    
    Block.outputMode = 'dict'


In [64]:
b2.eval(1,0,np.linspace(0, np.pi, 8+1))


Block.eval(x=1, y=0, theta=[ 0.          0.39269908  0.78539816  1.17809725  1.57079633  1.96349541
  2.35619449  2.74889357  3.14159265], output='dict')

Out[64]:
{"2-D Rotate.x'": array([  1.00000000e+00,   9.23879533e-01,   7.07106781e-01,
          3.82683432e-01,   6.12323400e-17,  -3.82683432e-01,
         -7.07106781e-01,  -9.23879533e-01,  -1.00000000e+00]),
 "2-D Rotate.y'": array([  0.00000000e+00,   3.82683432e-01,   7.07106781e-01,
          9.23879533e-01,   1.00000000e+00,   9.23879533e-01,
          7.07106781e-01,   3.82683432e-01,   1.22464680e-16])}

Potential Updates:

  • Set of 2 or more blocks with interconnects
  • Solve for selected outputs
  • Solve for selected inputs
  • Draw interconnect diagram
  • Create interface tables

Unnecessary Pictures

Because figures are fun. Using the 2-D rotation, we can rotate a constellation of points to best match expectations.


In [65]:
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib import colors

# for IPython plotting
%pylab inline


Populating the interactive namespace from numpy and matplotlib
WARNING: pylab import has clobbered these variables: ['colors', 'e', 'f']
`%matplotlib` prevents importing * from pylab and numpy

In [66]:
# random (x,y) points
xy1 = np.random.normal(0,0.5,(8,2))
x,y = np.hsplit(xy1,2)
# rotate points on a log-scale
a = [0]+np.logspace(-2,1,20,base=5)
b2.verbose = False
xy2 = b2.eval(x,y,a)
xy2["2-D Rotate.x'"].shape


Out[66]:
$$\left ( 8, \quad 20\right )$$

In [78]:
def example(xy1, xy2):
    '''Move plot code into a function for cleaner presentation'''
    # split original points into separate x/y arrays
    x,y = np.hsplit(xy1,2)
    
    # Fetch a matplotlib color map to use for line colors
    c = cm.get_cmap('gist_heat')
    cNorm  = matplotlib.colors.Normalize(vmin=0, vmax=20)
    scalarMap = cm.ScalarMappable(norm=cNorm, cmap=c)
    
    # calculate "unit" circles for each point
    a = np.reshape(np.linspace(0,2*np.pi,60), (60,1))
    unit = np.cos(a) + 1j*np.sin(a)
    circ = np.abs(x + 1j*y) * unit.T    

    # set up the figure
    plt.figure(figsize=(12,9))
    x = xy2["2-D Rotate.x'"].T
    y = xy2["2-D Rotate.y'"].T
    # "unit" circles for background
    for i in range(circ.shape[0]):
        s = '|iq{:d}|={:0.3f}'.format(i, np.abs(circ[i][0]))
        plt.plot(circ[i].real, circ[i].imag, ls=':', color='k', label=s)
        #plt.text(circ[i][0].real, circ[i][0].imag, str(i)+' ')
    # plot each rotation point
    for i in range(x.shape[0]):
        plt.plot(x[i], y[i], color=scalarMap.to_rgba(i), marker='o', ls='none')    
    # label the first rotation points
    for i in range(x.shape[1]):
        plt.text(x[0][i]+0.04, y[0][i]+0.04, str(i), color='blue')    
    plt.axis('equal')
    plt.grid()
    plt.legend()

In [79]:
example(xy1, xy2)



In [67]:
# Fetch a matplotlib color map to use for line colors
c = cm.get_cmap('gist_heat')
cNorm  = matplotlib.colors.Normalize(vmin=0, vmax=20)
scalarMap = cm.ScalarMappable(norm=cNorm, cmap=c)
# calculate "unit" circles for each point
a = np.reshape(np.linspace(0,2*np.pi,60), (60,1))
unit = np.cos(a) + 1j*np.sin(a)
circ = np.abs(x + 1j*y) * unit.T
# set up x/y
x = xy2["2-D Rotate.x'"].T
y = xy2["2-D Rotate.y'"].T
circ.shape


Out[67]:
$$\left ( 8, \quad 60\right )$$

In [86]:
plt.figure(figsize=(12,6))
for i in range(circ.shape[0]): # "unit" circles for background
    s = '|iq{:d}|={:0.3f}'.format(i, np.abs(circ[i][0]))
    plt.plot(circ[i].real, circ[i].imag, ls=':', color='k', label=s)
for i in range(x.shape[0]):    # plot each rotation point
    plt.plot(x[i], y[i], color=scalarMap.to_rgba(i), marker='o', ls='none')    
for i in range(x.shape[1]):    # label the first rotation points
    plt.text(x[0][i]+0.04, y[0][i]+0.04, str(i), color='blue')    
plt.axis('equal')
plt.grid()
i = plt.legend()


More Information

SymPy Help

  • sympy.*.subs(*args, **kwargs)
  • sympy.lambdify(args, expr, modules=None)

In [70]:
print(type(b.eqn[0]),'\n')
help(b.eqn[0].subs)


<class 'sympy.core.relational.Equality'> 

Help on method subs in module sympy.core.basic:

subs(*args, **kwargs) method of sympy.core.relational.Equality instance
    Substitutes old for new in an expression after sympifying args.
    
    `args` is either:
      - two arguments, e.g. foo.subs(old, new)
      - one iterable argument, e.g. foo.subs(iterable). The iterable may be
         o an iterable container with (old, new) pairs. In this case the
           replacements are processed in the order given with successive
           patterns possibly affecting replacements already made.
         o a dict or set whose key/value items correspond to old/new pairs.
           In this case the old/new pairs will be sorted by op count and in
           case of a tie, by number of args and the default_sort_key. The
           resulting sorted list is then processed as an iterable container
           (see previous).
    
    If the keyword ``simultaneous`` is True, the subexpressions will not be
    evaluated until all the substitutions have been made.
    
    Examples
    ========
    
    >>> from sympy import pi, exp, limit, oo
    >>> from sympy.abc import x, y
    >>> (1 + x*y).subs(x, pi)
    pi*y + 1
    >>> (1 + x*y).subs({x:pi, y:2})
    1 + 2*pi
    >>> (1 + x*y).subs([(x, pi), (y, 2)])
    1 + 2*pi
    >>> reps = [(y, x**2), (x, 2)]
    >>> (x + y).subs(reps)
    6
    >>> (x + y).subs(reversed(reps))
    x**2 + 2
    
    >>> (x**2 + x**4).subs(x**2, y)
    y**2 + y
    
    To replace only the x**2 but not the x**4, use xreplace:
    
    >>> (x**2 + x**4).xreplace({x**2: y})
    x**4 + y
    
    To delay evaluation until all substitutions have been made,
    set the keyword ``simultaneous`` to True:
    
    >>> (x/y).subs([(x, 0), (y, 0)])
    0
    >>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True)
    nan
    
    This has the added feature of not allowing subsequent substitutions
    to affect those already made:
    
    >>> ((x + y)/y).subs({x + y: y, y: x + y})
    1
    >>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True)
    y/(x + y)
    
    In order to obtain a canonical result, unordered iterables are
    sorted by count_op length, number of arguments and by the
    default_sort_key to break any ties. All other iterables are left
    unsorted.
    
    >>> from sympy import sqrt, sin, cos
    >>> from sympy.abc import a, b, c, d, e
    
    >>> A = (sqrt(sin(2*x)), a)
    >>> B = (sin(2*x), b)
    >>> C = (cos(2*x), c)
    >>> D = (x, d)
    >>> E = (exp(x), e)
    
    >>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)
    
    >>> expr.subs(dict([A, B, C, D, E]))
    a*c*sin(d*e) + b
    
    The resulting expression represents a literal replacement of the
    old arguments with the new arguments. This may not reflect the
    limiting behavior of the expression:
    
    >>> (x**3 - 3*x).subs({x: oo})
    nan
    
    >>> limit(x**3 - 3*x, x, oo)
    oo
    
    If the substitution will be followed by numerical
    evaluation, it is better to pass the substitution to
    evalf as
    
    >>> (1/x).evalf(subs={x: 3.0}, n=21)
    0.333333333333333333333
    
    rather than
    
    >>> (1/x).subs({x: 3.0}).evalf(21)
    0.333333333333333314830
    
    as the former will ensure that the desired level of precision is
    obtained.
    
    See Also
    ========
    replace: replacement capable of doing wildcard-like matching,
             parsing of match, and conditional replacements
    xreplace: exact node replacement in expr tree; also capable of
              using matching rules
    evalf: calculates the given formula to a desired level of precision


In [71]:
help(sympy.lambdify)


Help on function lambdify in module sympy.utilities.lambdify:

lambdify(args, expr, modules=None, printer=None, use_imps=True, dummify=True)
    Returns a lambda function for fast calculation of numerical values.
    
    If not specified differently by the user, SymPy functions are replaced as
    far as possible by either python-math, numpy (if available) or mpmath
    functions - exactly in this order. To change this behavior, the "modules"
    argument can be used. It accepts:
    
     - the strings "math", "mpmath", "numpy", "numexpr", "sympy"
     - any modules (e.g. math)
     - dictionaries that map names of sympy functions to arbitrary functions
     - lists that contain a mix of the arguments above, with higher priority
       given to entries appearing first.
    
    The default behavior is to substitute all arguments in the provided
    expression with dummy symbols. This allows for applied functions (e.g.
    f(t)) to be supplied as arguments. Call the function with dummify=False if
    dummy substitution is unwanted (and `args` is not a string). If you want
    to view the lambdified function or provide "sympy" as the module, you
    should probably set dummify=False.
    
    For functions involving large array calculations, numexpr can provide a
    significant speedup over numpy.  Please note that the available functions
    for numexpr are more limited than numpy but can be expanded with
    implemented_function and user defined subclasses of Function.  If specified,
    numexpr may be the only option in modules. The official list of numexpr
    functions can be found at:
    https://github.com/pydata/numexpr#supported-functions
    
    In previous releases ``lambdify`` replaced ``Matrix`` with ``numpy.matrix``
    by default. As of release 1.0 ``numpy.array`` is the default.
    To get the old default behavior you must pass in ``[{'ImmutableMatrix':
    numpy.matrix}, 'numpy']`` to the ``modules`` kwarg.
    
    >>> from sympy import lambdify, Matrix
    >>> from sympy.abc import x, y
    >>> import numpy
    >>> array2mat = [{'ImmutableMatrix': numpy.matrix}, 'numpy']
    >>> f = lambdify((x, y), Matrix([x, y]), modules=array2mat)
    >>> f(1, 2)
    matrix([[1],
            [2]])
    
    Usage
    =====
    
    (1) Use one of the provided modules:
    
        >>> from sympy import sin, tan, gamma
        >>> from sympy.utilities.lambdify import lambdastr
        >>> from sympy.abc import x, y
        >>> f = lambdify(x, sin(x), "math")
    
        Attention: Functions that are not in the math module will throw a name
                   error when the lambda function is evaluated! So this would
                   be better:
    
        >>> f = lambdify(x, sin(x)*gamma(x), ("math", "mpmath", "sympy"))
    
    (2) Use some other module:
    
        >>> import numpy
        >>> f = lambdify((x,y), tan(x*y), numpy)
    
        Attention: There are naming differences between numpy and sympy. So if
                   you simply take the numpy module, e.g. sympy.atan will not be
                   translated to numpy.arctan. Use the modified module instead
                   by passing the string "numpy":
    
        >>> f = lambdify((x,y), tan(x*y), "numpy")
        >>> f(1, 2)
        -2.18503986326
        >>> from numpy import array
        >>> f(array([1, 2, 3]), array([2, 3, 5]))
        [-2.18503986 -0.29100619 -0.8559934 ]
    
    (3) Use a dictionary defining custom functions:
    
        >>> def my_cool_function(x): return 'sin(%s) is cool' % x
        >>> myfuncs = {"sin" : my_cool_function}
        >>> f = lambdify(x, sin(x), myfuncs); f(1)
        'sin(1) is cool'
    
    Examples
    ========
    
    >>> from sympy.utilities.lambdify import implemented_function
    >>> from sympy import sqrt, sin, Matrix
    >>> from sympy import Function
    >>> from sympy.abc import w, x, y, z
    
    >>> f = lambdify(x, x**2)
    >>> f(2)
    4
    >>> f = lambdify((x, y, z), [z, y, x])
    >>> f(1,2,3)
    [3, 2, 1]
    >>> f = lambdify(x, sqrt(x))
    >>> f(4)
    2.0
    >>> f = lambdify((x, y), sin(x*y)**2)
    >>> f(0, 5)
    0.0
    >>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy')
    >>> row(1, 2)
    Matrix([[1, 3]])
    
    Tuple arguments are handled and the lambdified function should
    be called with the same type of arguments as were used to create
    the function.:
    
    >>> f = lambdify((x, (y, z)), x + y)
    >>> f(1, (2, 4))
    3
    
    A more robust way of handling this is to always work with flattened
    arguments:
    
    >>> from sympy.utilities.iterables import flatten
    >>> args = w, (x, (y, z))
    >>> vals = 1, (2, (3, 4))
    >>> f = lambdify(flatten(args), w + x + y + z)
    >>> f(*flatten(vals))
    10
    
    Functions present in `expr` can also carry their own numerical
    implementations, in a callable attached to the ``_imp_``
    attribute.  Usually you attach this using the
    ``implemented_function`` factory:
    
    >>> f = implemented_function(Function('f'), lambda x: x+1)
    >>> func = lambdify(x, f(x))
    >>> func(4)
    5
    
    ``lambdify`` always prefers ``_imp_`` implementations to implementations
    in other namespaces, unless the ``use_imps`` input parameter is False.

Upgrading Code to Python 3

I originally made this notebook using Python 2.7. Fortunately, there's a Python library for that too lib2to3, although the canned 2to3 application worked just fine for me. Although this doesn't usually change functionality, there may be some slight changes as seen when running help on the sympy.lambdify output functions.


In [72]:
%%file process.py
import sympy
import numpy as np

def parseExpr(expr=''):
    '''Helper function to iterate through a list of equations'''
    err = 'Malformed expression! Does not match "y = f(x)"\n  {0:s}'
    for s in expr.strip().split('\n'):
        # Parse anything that looks like an equation and isn't commented out
        if ('=' in s) and (s[0] != '#'):
            # convert expression to sympy
            y, f = map(str.strip, s.split('=',1))
            y = sympy.Symbol(y)
            f = sympy.sympify(f)
            assert type(y) == sympy.symbol.Symbol, err.format(s)
            yield (y, f)
                
class Block(object):
    '''Block(expr, inputs='', outputs='', functions={})
Generic processing block that performs specified calculations on given inputs
in such a way to ease documentation
    '''
    
    verbose    = True   # Enable verbose output
    outputMode = 'dict' # eval() return type ('dict' or 'tuple')
    
    def __init__(self, expr, name='', inputs='', outputs='', functions={}):
        '''Create a Block instance'''
        
        if Block.verbose:
            s = 'Creating Block(expr={:s}, name={:s}, inputs={:s}, outputs={:s}, functions='
            s = s.format(*map(repr,[expr, name, inputs, outputs]))+'{'
            if functions:
                s_functions = []
                for k, v in functions.iteritems():
                    s2 = k+':'+v.__name__
                    args, varargs, keywords, defaults = getargspec(v)
                    if varargs != None:
                        args += ['*args']
                    if keywords != None:
                        args += ['*kwargs']
                    s2 += '('+','.join(args)+')'
                    s_functions.append(s2)
                s += ','.join(s_functions)
            print s+'})'
        
        self.name = name
        self.user = functions
        
        # save in list form for ordered outputs
        eqn = tuple(parseExpr(expr))
        self.eqn = tuple([ sympy.Eq(k, v) for k, v in eqn ])
        # placeholder for compiled expressions
        self.lambdas = {}
        
        # Extract inputs and functions used
        expr_inputs = set()
        expr_functs = set()
        for k, v in eqn:
            for arg in sympy.preorder_traversal(v):
                if arg.is_Symbol:
                    expr_inputs.add(arg)
                elif arg.is_Function:
                    expr_functs.add(arg.func)
        
        # save SymPy style .args and .func attributes
        self.args = tuple(expr_inputs)
        self.func = tuple(expr_functs)     
        
        if inputs:
            self.ins = sympy.symbols(inputs)
        else: # extract inputs from expr
            self.ins = tuple(self.args)
            
        outs = tuple([ i[0] for i in eqn ])
        if outputs:
            self.outs = sympy.symbols(outputs)
            print 'outs='+repr(outs)
            self.hidden = tuple([ i for i in outs if i not in self.outs ])
        else: # extract inputs from expr
            self.outs = outs
            self.hidden = tuple()
            if Block.verbose:
                print '  Extracting outputs:', self.outs
                
        # create _eval() wrapper function with useful docstring        
        self.eval = self._wrap_eval()
                        
    def _wrap_eval(self):
        '''create _eval() wrapper function with useful docstring'''
        
        if type(self.ins) == tuple:
            ins = self.ins
            s = repr(self.ins)
        else:
            ins = (self.ins,)
            s = '('+repr(self.ins)+')'

        # not sure how to do a decorator with non-generic dynamic args
        func = sympy.lambdify(self.ins, '_eval'+s, {'_eval':self._eval})
        func.__name__ = 'Block.eval'
        s = repr(self.outs)
        if type(self.outs) != tuple:
            s = '('+s+')'
        func.__doc__ = 'Calculate outputs '+s+' as follows:\n  '
        func.__doc__ += '\n  '.join(map(str,self.eqn))
        func.__doc__ += '\n\nBlock.outputMode = '+repr(Block.outputMode)+'\n'
        
        return func
        
    def __str__(self):
        '''Support str calls on Block instances'''
        s  = 'Block: '+str(self.name)+'\n'
        s += '\n'.join( str(e).replace('==','=') for e in self.eqn )
        return s
    
    def __repr__(self):
        '''return representation that sympy will automatically show as LaTeX'''
        s = 'Block'
        if self.name:
            s += '('+self.name +')'
        return repr({s:[ sympy.Eq(sympy.Symbol(k), v) for k,v in self.eqn.items() ]})
    
    # method doesn't work currently
    __repr__ = __str__
    
    def pretty(self):
        '''Show a SymPy pretty print version of Block equations'''
        print '\nBlock:', self.name
        print '\n'.join( sympy.pretty(e) for e in self.eqn )
        
    @property
    def latex(self):
        '''generate a latex version of Block equations'''
        # \verb;*; leaves contents unformatted
        s  = r'\underline{\verb;Block: '+str(self.name)+';} \\\\ \n'
        s += ' \\\\ \n'.join( sympy.latex(e) for e in self.eqn )
        return s 
        
    def lambdify(self, unknowns=None):
        '''generate an executable function using NumPy'''
        lookup='numpy'
        
        # by default, unknowns are everything but outputs
        if unknowns == None:
            unknowns = self.outs+self.hidden
        
        if self.verbose:
            print 'Compiling Block '+repr(self.name)+' expressions:'
            
        # check for missing functions
        defined = set(dir(np) + self.user.keys())
        missing = [ f for f in self.func if str(f) not in defined ]
        if missing:
            s = 'Unable to find functions '+str(missing)+' in '+str(lookup)
            s += ' or user-defined functions ' + self.user.keys()
            raise LookupError, s
        
        # solve equations in terms of unknowns
        eqn = sympy.solve(self.eqn, unknowns, dict=True)
        if self.verbose:
            print 'Solving equations for unknowns:', unknowns 
            print self.eqn
            print ' =', eqn, '\n'
        
        s = "  {0:s} = sympy.lambdify({1:s}, {2:s}, '{3:s}')" # verbose string
        for k, v in eqn[0].iteritems():   
            if k in self.hidden: # skip intermediate values
                continue
            
            k = str(k) # convert output variable from sympy.Symbol
            
            if self.verbose:
                print s.format(*map(str, (k, self.ins, v, (lookup, self.user.keys()) )))
            f = sympy.lambdify(self.ins, v, (lookup, self.user))
            # Update the function name and doc string from "<lambda> lambda x, y, theta"
            f.__name__ = "Block"
            if self.name:
                f.__name__ += '('+self.name+')'
            f.__name__ += '.lambdas['+k+']'
            f.__doc__ = k+' = '+str(v)
            self.lambdas[k] = f
            
        return self.lambdas    
        
    def _eval(self, *args, **kwargs):
        '''evaluate outputs for given inputs'''
        
        # make sure in/ouputs are iterable
        if hasattr(self.ins, '__iter__'):
            ins = self.ins
        else:
            ins = [self.ins]
            
        # make sure all inputs are given
        assert len(args) == len(ins)

        # default kwargs values
        if not kwargs.has_key('output'):
            output=Block.outputMode
                   
        # compile expressions if needed
        if not self.lambdas:
            self.lambdify()
            
        if self.verbose:
            s = '\nBlock.eval('
            s += ', '.join( map(lambda k, v: str(k)+'='+str(v), ins, args) )
            s += ', output='+repr(output)
            print s+')\n'
        
        if output == 'dict':            
            if self.name:
                prefix=self.name+'.'
            else:
                prefix=''
            return { prefix+k:v(*args) for k, v in self.lambdas.iteritems() }
        else: # output tuple in order of .outs
            return tuple( self.lambdas[k](*args) for k in self.outs )


Overwriting process.py

Let's test the conversion of the rewritten Python 2.7 code


In [73]:
!2to3 -w process.py


--- process.py	(original)
+++ process.py	(refactored)
@@ -8,7 +8,7 @@
         # Parse anything that looks like an equation and isn't commented out
         if ('=' in s) and (s[0] != '#'):
             # convert expression to sympy
-            y, f = map(str.strip, s.split('=',1))
+            y, f = list(map(str.strip, s.split('=',1)))
             y = sympy.Symbol(y)
             f = sympy.sympify(f)
             assert type(y) == sympy.symbol.Symbol, err.format(s)
@@ -28,10 +28,10 @@
         
         if Block.verbose:
             s = 'Creating Block(expr={:s}, name={:s}, inputs={:s}, outputs={:s}, functions='
-            s = s.format(*map(repr,[expr, name, inputs, outputs]))+'{'
+            s = s.format(*list(map(repr,[expr, name, inputs, outputs])))+'{'
             if functions:
                 s_functions = []
-                for k, v in functions.iteritems():
+                for k, v in functions.items():
                     s2 = k+':'+v.__name__
                     args, varargs, keywords, defaults = getargspec(v)
                     if varargs != None:
@@ -41,7 +41,7 @@
                     s2 += '('+','.join(args)+')'
                     s_functions.append(s2)
                 s += ','.join(s_functions)
-            print s+'})'
+            print(s+'})')
         
         self.name = name
         self.user = functions
@@ -74,13 +74,13 @@
         outs = tuple([ i[0] for i in eqn ])
         if outputs:
             self.outs = sympy.symbols(outputs)
-            print 'outs='+repr(outs)
+            print('outs='+repr(outs))
             self.hidden = tuple([ i for i in outs if i not in self.outs ])
         else: # extract inputs from expr
             self.outs = outs
             self.hidden = tuple()
             if Block.verbose:
-                print '  Extracting outputs:', self.outs
+                print('  Extracting outputs:', self.outs)
                 
         # create _eval() wrapper function with useful docstring        
         self.eval = self._wrap_eval()
@@ -118,15 +118,15 @@
         s = 'Block'
         if self.name:
             s += '('+self.name +')'
-        return repr({s:[ sympy.Eq(sympy.Symbol(k), v) for k,v in self.eqn.items() ]})
+        return repr({s:[ sympy.Eq(sympy.Symbol(k), v) for k,v in list(self.eqn.items()) ]})
     
     # method doesn't work currently
     __repr__ = __str__
     
     def pretty(self):
         '''Show a SymPy pretty print version of Block equations'''
-        print '\nBlock:', self.name
-        print '\n'.join( sympy.pretty(e) for e in self.eqn )
+        print('\nBlock:', self.name)
+        print('\n'.join( sympy.pretty(e) for e in self.eqn ))
         
     @property
     def latex(self):
@@ -145,32 +145,32 @@
             unknowns = self.outs+self.hidden
         
         if self.verbose:
-            print 'Compiling Block '+repr(self.name)+' expressions:'
+            print('Compiling Block '+repr(self.name)+' expressions:')
             
         # check for missing functions
-        defined = set(dir(np) + self.user.keys())
+        defined = set(dir(np) + list(self.user.keys()))
         missing = [ f for f in self.func if str(f) not in defined ]
         if missing:
             s = 'Unable to find functions '+str(missing)+' in '+str(lookup)
-            s += ' or user-defined functions ' + self.user.keys()
-            raise LookupError, s
+            s += ' or user-defined functions ' + list(self.user.keys())
+            raise LookupError(s)
         
         # solve equations in terms of unknowns
         eqn = sympy.solve(self.eqn, unknowns, dict=True)
         if self.verbose:
-            print 'Solving equations for unknowns:', unknowns 
-            print self.eqn
-            print ' =', eqn, '\n'
+            print('Solving equations for unknowns:', unknowns) 
+            print(self.eqn)
+            print(' =', eqn, '\n')
         
         s = "  {0:s} = sympy.lambdify({1:s}, {2:s}, '{3:s}')" # verbose string
-        for k, v in eqn[0].iteritems():   
+        for k, v in eqn[0].items():   
             if k in self.hidden: # skip intermediate values
                 continue
             
             k = str(k) # convert output variable from sympy.Symbol
             
             if self.verbose:
-                print s.format(*map(str, (k, self.ins, v, (lookup, self.user.keys()) )))
+                print(s.format(*list(map(str, (k, self.ins, v, (lookup, list(self.user.keys())) )))))
             f = sympy.lambdify(self.ins, v, (lookup, self.user))
             # Update the function name and doc string from "<lambda> lambda x, y, theta"
             f.__name__ = "Block"
@@ -195,7 +195,7 @@
         assert len(args) == len(ins)
 
         # default kwargs values
-        if not kwargs.has_key('output'):
+        if 'output' not in kwargs:
             output=Block.outputMode
                    
         # compile expressions if needed
@@ -206,13 +206,13 @@
             s = '\nBlock.eval('
             s += ', '.join( map(lambda k, v: str(k)+'='+str(v), ins, args) )
             s += ', output='+repr(output)
-            print s+')\n'
+            print(s+')\n')
         
         if output == 'dict':            
             if self.name:
                 prefix=self.name+'.'
             else:
                 prefix=''
-            return { prefix+k:v(*args) for k, v in self.lambdas.iteritems() }
+            return { prefix+k:v(*args) for k, v in self.lambdas.items() }
         else: # output tuple in order of .outs
             return tuple( self.lambdas[k](*args) for k in self.outs )           
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: Refactored process.py
RefactoringTool: Files that were modified:
RefactoringTool: process.py

Success!


In [74]:
from process import *

In [75]:
for s in (parseExpr, Block):
    help(s)


Help on function parseExpr in module process:

parseExpr(expr='')
    Helper function to iterate through a list of equations

Help on class Block in module process:

class Block(builtins.object)
 |  Block(expr, inputs='', outputs='', functions={})
 |  Generic processing block that performs specified calculations on given inputs
 |  in such a way to ease documentation
 |  
 |  Methods defined here:
 |  
 |  __init__(self, expr, name='', inputs='', outputs='', functions={})
 |      Create a Block instance
 |  
 |  __repr__ = __str__(self)
 |  
 |  __str__(self)
 |      Support str calls on Block instances
 |  
 |  lambdify(*args, **kwargs) from builtins.type
 |      generate an executable function using NumPy and set the arguments to the variable names
 |  
 |  pretty(self)
 |      Show a SymPy pretty print version of Block equations
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  latex
 |      generate a latex version of Block equations
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  outputMode = 'dict'
 |  
 |  verbose = True

  • Python and Jupyter Notebooks
  • SymPy and LaTeX
  • SciPy and matplotlib

SymPy and LaTeX

Scientific Python Lectures: Symbolic algebra

Live SymPy console

Wolfram Alpha-style search engine powered by SymPy SymPy Tutorial

SymPy Modules

SymPy solvers module: Algebraic/Differential/Recurrence/Diophantine equations, Utilities, Systems of Polynomial Equations Equations, Inequalities

SymPy Simplification Functions: Function/Trigonometric/Powers/Exponentials/logarithms Simplification, Special Functions

SymPy Basic Operations: Substitution, string inputs, evalf, lambdify

SymPy Basics of Expressions

SymPy Expression Trees and Manipulations

Embed LaTeX math equations into Microsoft Word

Type math formulas in LaTeX way in Microsoft Word?

pyvideo.org videos for SymPy

SciPy and matplotlib

SciPy Signal Processing module: Convolution, Filters, Linear Systems, Function Generators, Windowing, Wavelets, Peak finding, Spectral Analysis

SciPy Special Function module: Elliptic, Bessel, Gamma, Error, Legendre, Hypergeometric, Mathieu, Wave, and other functions

SciPy Cookbook: BPSK: A simple BPSK example with AWGN (no coding)

Matplotlib Gallery: Example plots

Any Questions?

This presentation courtesy of Python

jupyter nbconvert --to slides Process.ipynb --post serve

[NbConvertApp] Converting notebook Process.ipynb to slides
[NbConvertApp] Writing 341651 bytes to Process.slides.html
[NbConvertApp] Redirecting reveal.js requests to https://cdn.jsdelivr.net/reveal.js/2.6.2
Serving your slides at http://127.0.0.1:8000/Process.slides.html
Use Control-C to stop this server
WARNING:tornado.access:404 GET /custom.css (127.0.0.1) 4.00ms
WARNING:tornado.access:404 GET /custom.css (127.0.0.1) 3.00ms

In [77]:
%%file slides.bat
jupyter nbconvert --to slides Process.ipynb --post serve


Writing slides.bat