Example #1
1
def comparison_plot(f, u, Omega, filename='tmp.pdf',
                    plot_title='', ymin=None, ymax=None,
                    u_legend='approximation'):
    """Compare f(x) and u(x) for x in Omega in a plot."""
    x = sm.Symbol('x')
    print 'f:', f

    f = sm.lambdify([x], f, modules="numpy")
    u = sm.lambdify([x], u, modules="numpy")
    if len(Omega) != 2:
        raise ValueError('Omega=%s must be an interval (2-list)' % str(Omega))
    # When doing symbolics, Omega can easily contain symbolic expressions,
    # assume .evalf() will work in that case to obtain numerical
    # expressions, which then must be converted to float before calling
    # linspace below
    if not isinstance(Omega[0], (int,float)):
        Omega[0] = float(Omega[0].evalf())
    if not isinstance(Omega[1], (int,float)):
        Omega[1] = float(Omega[1].evalf())

    resolution = 401  # no of points in plot
    xcoor = linspace(Omega[0], Omega[1], resolution)
    # Vectorized functions expressions does not work with
    # lambdify'ed functions without the modules="numpy"
    exact  = f(xcoor)
    approx = u(xcoor)
    plot(xcoor, approx, '-')
    hold('on')
    plot(xcoor, exact, '-')
    legend([u_legend, 'exact'])
    title(plot_title)
    xlabel('x')
    if ymin is not None and ymax is not None:
        axis([xcoor[0], xcoor[-1], ymin, ymax])
    savefig(filename)
Example #2
1
    def calculate_path(self):

        f, g, t, dt, s = (self.f, self.g, self.t, self.delta, self.s)
        der_f, der_g = [diff(coord, t) for coord in f, g]
        tanf, tang = [lambdify((t, s), coord + der * s, numpy) for coord, der in ((f, der_f), (g, der_g))]

        coords = lambdify(t, (f, g), numpy)
        print der_f.subs(t, t + dt)
        get_control_param = lambdify(t, (g - g.subs(t, t + dt)) / (der_g.subs(t, t + dt) - der_g), numpy)

        def control_coords(time):
            control_param = get_control_param(time)
            return (tangent(time, control_param) for tangent in (tanf, tang))

        x_o, y_o = coords(self.min)
        path = "M%f, %f" % (x_o, y_o)

        def append_curve(path, point, control_point):
            return "%s Q%f, %f %f, %f" % (path, point.x, point.y, control_point.x, control_point.y)

        for time in numpy.arange(self.min + self.delta, self.max - self.delta, self.delta):
            x, y = coords(time)
            x_c, y_c = control_coords(time)
            path = append_curve(path, Point(x, y), Point(x_c, y_c))

        x_f, y_f = coords(self.max)
        path = "%s T%f, %f" % (path, x_f, y_f)

        self.path = path
Example #3
1
 def fbenchmark(f, var=[Symbol('x')]):
     """
     Do some benchmarks with f using clambdify, lambdify and psyco.
     """
     global cf, pf, psyf
     start = time()
     cf = clambdify(var, f)
     print('compile time (including sympy overhead): %f s' % (
         time() - start))
     pf = lambdify(var, f, 'math')
     psyf = None
     psyco = import_module('psyco')
     if psyco:
         psyf = lambdify(var, f, 'math')
         psyco.bind(psyf)
     code = '''for x in (i/1000. for i in range(1000)):
     f(%s)''' % ('x,'*len(var)).rstrip(',')
     t1 = Timer(code, 'from __main__ import cf as f')
     t2 = Timer(code, 'from __main__ import pf as f')
     if psyf:
         t3 = Timer(code, 'from __main__ import psyf as f')
     else:
         t3 = None
     print('for x = (0, 1, 2, ..., 999)/1000')
     print('20 times in 3 runs')
     print('compiled:      %.4f %.4f %.4f' % tuple(t1.repeat(3, 20)))
     print('Python lambda: %.4f %.4f %.4f' % tuple(t2.repeat(3, 20)))
     if t3:
         print('Psyco lambda:  %.4f %.4f %.4f' % tuple(t3.repeat(3, 20)))
Example #4
0
def test_imag_real():
    f_re = lambdify([z], sympy.re(z))
    val = 3+2j
    assert f_re(val) == val.real

    f_im = lambdify([z], sympy.im(z))  # see #15400
    assert f_im(val) == val.imag
Example #5
0
def run_Lagrange_interp_abs_conv(N=[3, 6, 12, 24]):
    f = sm.abs(1-2*x)
    f = sm.sin(2*sm.pi*x)
    fn = sm.lambdify([x], f, modules='numpy')
    resolution = 50001
    import numpy as np
    xcoor = np.linspace(0, 1, resolution)
    fcoor = fn(xcoor)
    Einf = []
    E2 = []
    h = []
    for _N in N:
        psi, points = Lagrange_polynomials_01(x, _N)
        u = interpolation(f, psi, points)
        un = sm.lambdify([x], u, modules='numpy')
        ucoor = un(xcoor)
        e = fcoor - ucoor
        Einf.append(e.max())
        E2.append(np.sqrt(np.sum(e*e/e.size)))
        h.append(1./_N)
    print Einf
    print E2
    print h
    print N
    # Assumption: error = CN**(-N)
    print 'convergence rates:'
    for i in range(len(E2)):
        C1 = E2[i]/(N[i]**(-N[i]/2))
        C2 = Einf[i]/(N[i]**(-N[i]/2))
        print N[i], C1, C2
Example #6
0
def test_numpy_matrix():
    if not numpy:
        skip("numpy not installed.")
    A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
    sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]])
    #Lambdify array first, to ensure return to array as default
    f = lambdify((x, y, z), A, ['numpy'])
    numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
    #Check that the types are arrays and matrices
    assert isinstance(f(1, 2, 3), numpy.ndarray)

    # gh-15071
    class dot(Function):
        pass
    x_dot_mtx = dot(x, Matrix([[2], [1], [0]]))
    f_dot1 = lambdify(x, x_dot_mtx)
    inp = numpy.zeros((17, 3))
    assert numpy.all(f_dot1(inp) == 0)

    strict_kw = dict(allow_unknown_functions=False, inline=True, fully_qualified_modules=False)
    p2 = NumPyPrinter(dict(user_functions={'dot': 'dot'}, **strict_kw))
    f_dot2 = lambdify(x, x_dot_mtx, printer=p2)
    assert numpy.all(f_dot2(inp) == 0)

    p3 = NumPyPrinter(strict_kw)
    # The line below should probably fail upon construction (before calling with "(inp)"):
    raises(Exception, lambda: lambdify(x, x_dot_mtx, printer=p3)(inp))
def calc_eigs_numerically(mat,h,k,l,S=1):
    """
    Give it a matrix, and the (h,k,l) values to substitute into that matrix, each in a separate list.
    S is automatically evaluated as one, but can be changed. h,k,l lists must be the same length.
    """
    #get rid of these
    S_SYM = sympy.Symbol('S')
    KX_SYM = sympy.Symbol('kx')
    KY_SYM = sympy.Symbol('ky')
    KZ_SYM = sympy.Symbol('kz')        

    #lambdification functionality
    syms = (S_SYM,KX_SYM,KY_SYM,KZ_SYM)
    matsym = mat.tolist()
    func = sympy.lambdify(syms,matsym,modules=["sympy"])
    
    eigarr = []
    Slist = S*N.ones(h.shape)
    
    # reduce symbolic matrix to numerical matrix and calculate the eigenvalues
    for i in range(len(h)):
        eigmat = N.array(func(Slist[i],h[i],k[i],l[i]))
        
        # Convert numpy array to sympy matrix and lambdify it to
        # exchange sympy.I with numpy's 1j. Then convert it back to 
        # a numpy array and append it to the list of eigs. 
        eigmat = sympy.Matrix(eigmat)
        I2jfunc = sympy.lambdify((sympy.I),eigmat,modules="numpy")
        eigmat = N.array(I2jfunc(1j))

        eigs,vects = N.linalg.eig(eigmat)
        eigarr.append(eigs)
    return N.array(eigarr)
Example #8
0
def error_of_methods():
	"""
	Complie test with returning error
	"""
	import math
	import numpy as np
	import sympy
	from sympy import cos
	from sympy import sin
	from sympy.utilities.lambdify import lambdify
	
	w,x, L ,t= sympy.symbols("w x L t")
	pi = math.pi	

	u = lambda x,t : cos(w*t)*cos(pi*x/L)
	q = lambda x : 1 + ( x -L/2.0)**4

	def source_term(u,q):
		return sympy.simplify(u(x,t).diff(t, t) - (u(x,t).diff(x)*q(x)).diff(x) )

	w=1
	L = 2
	T=10
	Nx=40

	f =  sympy.lambdify((x,t), source_term(u,q)  ,'numpy')
	q = sympy.lambdify(x,q(x) ,'numpy')
	I = sympy.lambdify(x, u(x,t).subs(t,0),'numpy')
	u = sympy.lambdify((x,t), u(x,t),'numpy')

	print solve_wave_eqn_with_variable_velocity(q,f,I, L,T,Nx,u_exact=u,neumann=sum_approximation)[1]
	print solve_wave_eqn_with_variable_velocity(q,f,I, L,T,Nx,u_exact=u,neumann=centered_difference)[1]
	print solve_wave_eqn_with_variable_velocity(q,f,I, L,T,Nx,u_exact=u,neumann=centered_difference)[1]
	print solve_wave_eqn_with_variable_velocity(q,f,I, L,T,Nx,u_exact=u,neumann=shifted_domain)[1]
Example #9
0
def test_matrix():
    A = Matrix([[x, x*y], [sin(z)+4, x**z]])
    sol = Matrix([[1, 2], [sin(3)+4, 1]])
    f = lambdify((x,y,z), A, modules="sympy")
    assert f(1,2,3) == sol
    f = lambdify((x,y,z), (A, [A]), modules="sympy")
    assert f(1,2,3) == (sol,[sol])
def run_Lagrange_interp_abs_Cheb(N, ymin=None, ymax=None):
    f = sp.Abs(1-2*x)
    fn = sp.lambdify([x], f)
    psi, points= Lagrange_polynomials(x, N, [0, 1],
                                      point_distribution='Chebyshev')
    u = interpolation(f, psi, points)
    comparison_plot(f, u, Omega=[0, 1],
                    filename='Lagrange_interp_abs_Cheb_%d' % (N+1),
                    plot_title='Interpolation by Lagrange polynomials '\
                    'of degree %d' % N, ymin=ymin, ymax=ymax)
    print 'Interpolation points:', points

    # Make figures of Lagrange polynomials (psi)
    plt.figure()
    xcoor = np.linspace(0, 1, 1001)
    legends = []
    for i in (2, (N+1)/2+1):
        fn = sp.lambdify([x], psi[i])
        ycoor = fn(xcoor)
        plt.plot(xcoor, ycoor)
        legends.append(r'$\psi_%d$' % i)
        plt.hold('on')
    plt.legend(legends)
    plt.plot(points, [0]*len(points), 'ro')
    #if ymin is not None and ymax is not None:
    #    axis([xcoor[0], xcoor[-1], ymin, ymax])
    plt.savefig('Lagrange_basis_Cheb_%d.pdf' % (N+1))
    plt.savefig('Lagrange_basis_Cheb_%d.png' % (N+1))
Example #11
0
    def _interpret_args(self, args, kwargs):
        f, gradient = None, self.gradient
        atoms, lists = self._sort_args(args)
        s = self._pop_symbol_list(lists)
        s = self._fill_in_vars(s)

        # prepare the error message for lambdification failure
        f_str = ', '.join(str(fa) for fa in atoms)
        s_str = (str(sa) for sa in s)
        s_str = ', '.join(sa for sa in s_str if sa.find('unbound') < 0)
        f_error = ValueError("Could not interpret arguments "
                             "%s as functions of %s." % (f_str, s_str))

        # try to lambdify args
        if len(atoms) == 1:
            fv = atoms[0]
            try: f = lambdify(s, [fv,fv,fv])
            except: raise f_error

        elif len(atoms) == 3:
            fr, fg, fb = atoms
            try: f = lambdify(s, [fr,fg,fb])
            except: raise f_error

        else: raise ValueError("A ColorScheme must provide 1 or 3 "
                               "functions in x, y, z, u, and/or v.")

        # try to intrepret any given color information
        if len(lists) == 0:
            gargs = []

        elif len(lists) == 1:
            gargs = lists[0]

        elif len(lists) == 2:
            try: (r1,g1,b1), (r2,g2,b2) = lists
            except: raise ValueError("If two color arguments are given, "
                                     "they must be given in the format "
                                     "(r1,g1,b1), (r2,g2,b2).")
            gargs = lists

        elif len(lists) == 3:
            try: (r1,r2), (g1,g2), (b1,b2) = lists
            except: raise ValueError("If three color arguments are given, "
                                     "they must be given in the format "
                                     "(r1,r2), (g1,g2), (b1,b2). To create "
                                     "a multi-step gradient, use the syntax "
                                     "[0, colorStart, step1, color1, ..., 1, "
                                     "colorEnd].")
            gargs = [[r1,g1,b1], [r2,g2,b2]]

        else: raise ValueError("Don't know what to do with collection "
                               "arguments %s." % (', '.join(str(l) for l in lists)))

        if gargs:
            try: gradient = ColorGradient(*gargs)
            except Exception, ex:
                raise ValueError(("Could not initialize a gradient "
                                  "with arguments %s. Inner "
                                  "exception: %s") % (gargs, str(ex)))
Example #12
0
def interpolation(f, phi, points):
    """
    Given a function f(x), return the approximation to
    f(x) in the space V, spanned by phi, that interpolates
    f at the given points. Must have len(points) = len(phi)
    """
    N = len(phi) - 1
    A = sm.zeros((N+1, N+1))
    b = sm.zeros((N+1, 1))
    # Wrap phi and f in Python functions rather than expressions
    # so that we can evaluate phi at points[i] (alternative to subs?)
    x = sm.Symbol('x')
    phi = [sm.lambdify([x], phi[i]) for i in range(N+1)]
    f = sm.lambdify([x], f)
    print '...evaluating matrix...'
    for i in range(N+1):
        for j in range(N+1):
            print '(%d,%d)' % (i, j)
            A[i,j] = phi[j](points[i])
        b[i,0] = f(points[i])
    print
    print 'A:\n', A, '\nb:\n', b
    c = A.LUsolve(b)
    print 'coeff:', c
    u = 0
    for i in range(len(phi)):
        u += c[i,0]*phi[i](x)
    # Alternative:
    # u = sum(c[i,0]*phi[i] for i in range(len(phi)))
    print 'approximation:', u
    return u
Example #13
0
def test_scipy_fns():
    if not scipy:
        skip("scipy not installed")

    single_arg_sympy_fns = [erf, erfc, factorial, gamma, loggamma, digamma]
    single_arg_scipy_fns = [scipy.special.erf, scipy.special.erfc,
        scipy.special.factorial, scipy.special.gamma, scipy.special.gammaln,
        scipy.special.psi]
    numpy.random.seed(0)
    for (sympy_fn, scipy_fn) in zip(single_arg_sympy_fns, single_arg_scipy_fns):
        test_values = 20 * numpy.random.rand(20)
        f = lambdify(x, sympy_fn(x), modules = "scipy")
        assert numpy.all(abs(f(test_values) - scipy_fn(test_values)) < 1e-15)

    double_arg_sympy_fns = [RisingFactorial, besselj, bessely, besseli,
        besselk]
    double_arg_scipy_fns = [scipy.special.poch, scipy.special.jn,
        scipy.special.yn, scipy.special.iv, scipy.special.kn]

    #suppress scipy warnings
    import warnings
    warnings.filterwarnings('ignore', '.*floating point number truncated*')

    for (sympy_fn, scipy_fn) in zip(double_arg_sympy_fns, double_arg_scipy_fns):
        for i in range(20):
            test_values = 20 * numpy.random.rand(2)
            f = lambdify((x,y), sympy_fn(x,y), modules = "scipy")
            assert abs(f(*test_values) - scipy_fn(*test_values)) < 1e-15
Example #14
0
def least_squares(f, psi, Omega, symbolic=True, print_latex=False):
    """
    Given a function f(x,y) on a rectangular domain
    Omega=[[xmin,xmax],[ymin,ymax]],
    return the best approximation to f(x,y) in the space V
    spanned by the functions in the list psi.
    """
    N = len(psi) - 1
    A = sym.zeros((N+1, N+1))
    b = sym.zeros((N+1, 1))
    x, y = sym.symbols('x y')
    print '...evaluating matrix...'
    for i in range(N+1):
        for j in range(i, N+1):
            print '(%d,%d)' % (i, j)

            integrand = psi[i]*psi[j]
            if symbolic:
                I = sym.integrate(integrand,
                                 (x, Omega[0][0], Omega[0][1]),
                                 (y, Omega[1][0], Omega[1][1]))
            if not symbolic or isinstance(I, sym.Integral):
                # Could not integrate symbolically, use numerical int.
                print 'numerical integration of', integrand
                integrand = sym.lambdify([x,y], integrand)
                I = sym.mpmath.quad(integrand,
                                   [Omega[0][0], Omega[0][1]],
                                   [Omega[1][0], Omega[1][1]])
            A[i,j] = A[j,i] = I
        integrand = psi[i]*f
        if symbolic:
            I = sym.integrate(integrand,
                             (x, Omega[0][0], Omega[0][1]),
                             (y, Omega[1][0], Omega[1][1]))
        if not symbolic or isinstance(I, sym.Integral):
            # Could not integrate symbolically, use numerical int.
            print 'numerical integration of', integrand
            integrand = sym.lambdify([x,y], integrand)
            I = sym.mpmath.quad(integrand,
                               [Omega[0][0], Omega[0][1]],
                               [Omega[1][0], Omega[1][1]])
        b[i,0] = I
    print
    print 'A:\n', A, '\nb:\n', b
    if symbolic:
        c = A.LUsolve(b)  # symbolic solve
        # c is a sympy Matrix object, numbers are in c[i,0]
        c = [c[i,0] for i in range(c.shape[0])]
    else:
        c = sym.mpmath.lu_solve(A, b)  # numerical solve
    print 'coeff:', c

    u = sum(c[i]*psi[i] for i in range(len(psi)))
    print 'approximation:', u
    print 'f:', sym.expand(f)
    if print_latex:
        print sym.latex(A, mode='plain')
        print sym.latex(b, mode='plain')
        print sym.latex(c, mode='plain')
    return u, c
Example #15
0
 def __init__(self,
              fi=lambda t, theta: log(t),
              fi_inv=None, #lambda t, theta:(-sympy.log(t)) ** theta,
              theta=2,
              marginals=None):
     self.theta = float(theta)#Symbol('theta')
     self.t = Symbol('t')
     self.s = Symbol('s')
     self.d = len(marginals)
     self.fi_ = fi
     self.fi_inv_ = fi_inv
     self.sym_fi = fi(self.t, self.theta)
     self.sym_fi_deriv = sympy.diff(self.sym_fi, self.t)
     if fi_inv is  None:
         self.sym_fi_inv = sympy.solve(self.sym_fi - self.s, self.t)[0]
     else:
         self.sym_fi_inv = fi_inv(self.s, self.theta)
     self.sym_fi_inv_nth_deriv = sympy.diff(self.sym_fi_inv, self.s, self.d)
     #self.debug_info()
     super(ArchimedeanSymbolicCopula, self).__init__(fi=sympy.lambdify(self.t, self.sym_fi, "numpy"),
                                                     fi_deriv=sympy.lambdify(self.t, self.sym_fi_deriv, "numpy"),
                                                     fi_inv=sympy.lambdify(self.s, self.sym_fi_inv, "numpy"),
                                                     fi_inv_nth_deriv=sympy.lambdify(self.s, self.sym_fi_inv_nth_deriv, "numpy"),
                                                     marginals=marginals)
     vars = self.symVars
     si = 0
     for i in range(self.d):
         si += self.fi_(vars[i], self.theta)
     self.sym_C = self.fi_inv_(si, self.theta)
Example #16
0
    def initialize(self, args):
        self.E   = args[0]
        self.A   = args[1]
        self.I   = args[2]
        self.r   = args[3]
        self.rho = args[4]
        self.l   = args[5]
        self.g   = args[6]

        q = sym.Matrix(sym.symarray('q',6))
        E, A, I, r, rho, l, g = sym.symbols('E A I r rho l g')
        theta = sym.Matrix(['theta_1','theta_2'])
        omega = sym.Matrix(['omega_1','omega_2'])
        
        # Load symbolic needed matricies and vectors
        M_sym      = pickle.load( open( "gebf-mass-matrix.dump",  "rb" ) )
        beta_sym   = pickle.load( open( "gebf-force-vector.dump", "rb" ) )
        Gamma1_sym = pickle.load( open( "gebf-1c-matrix.dump",    "rb" ) )
        Gamma2_sym = pickle.load( open( "gebf-2c-matrix.dump",    "rb" ) )

        # Create numeric function of needed matrix and vector quantities
        # this is MUCH MUCH faster than .subs()
        # .subs() is unusably slow !!
        self.M      = lambdify((E, A, I, r, rho, l, g, q, theta, omega),      M_sym, "numpy")
        self.beta   = lambdify((E, A, I, r, rho, l, g, q, theta, omega),   beta_sym, "numpy")
        self.Gamma1 = lambdify((E, A, I, r, rho, l, g, q, theta, omega), Gamma1_sym, "numpy")
        self.Gamma2 = lambdify((E, A, I, r, rho, l, g, q, theta, omega), Gamma2_sym, "numpy")
Example #17
0
def Newton_solver_pq(error, hx, ht, gx, gt, x0):
    
    p, q  = symbols('p q')
    
    epsilon1 = gx*hx[-2]**p + gt*ht[-2]**q - error[-2]
    epsilon2 = gx*hx[-1]**p + gt*ht[-1]**q - error[-1]


    epsilon = [epsilon1, epsilon2]
    x = [p, q]
    
    def f(i,j):
        return diff(epsilon[i], x[j])
        
    Jacobi = Matrix(2, 2, f)

    JacobiInv = Jacobi.inv()
    epsilonfunc = lambdify(x, epsilon)
    JacobiInvfunc = lambdify(x, JacobiInv)
    x = x0
    
    
    

    F = np.asarray(epsilonfunc(x))
    
    for n in range(8):
        Jinv = np.asarray(JacobiInvfunc(x))
        F = np.asarray(epsilonfunc(x))
        x = x - np.dot(Jinv, F)

    return x
def PlotFor2Param(k1, k2, x, y, yVal, eq1, eq2, eqDet, eqTr, valK1m, valK3m, valK2 = 0.95, valK3 = 0.0032):
    eqk1_1Det = solve(eqDet.subs(x, eq2), k1)
    eqForK1Det = eq1 - eqk1_1Det[0]
    eqK2Det = solve(eqForK1Det.subs(km1, valK1m).subs(km3, valK3m).subs(k3, valK3), k2)
    funcK2Det = lambdify(y, eqK2Det[0])
    funcK1Det = lambdify(y, eqk1_1Det[0].subs(x, eq2).subs(k2, eqK2Det[0]).subs(km1, valK1m).subs(km3, valK3m).subs(k3, valK3))
    k1DetAll = funcK1Det(yVal)
    k2DetAll = funcK2Det(yVal)
    k1DetPos = [k1DetAll[i] for i in range(len(k1DetAll)) if k1DetAll[i] > 0 and k2DetAll[i] > 0]
    k2DetPos = [k2DetAll[i] for i in range(len(k2DetAll)) if k1DetAll[i] > 0 and k2DetAll[i] > 0]
    hopf, = plt.plot(k1DetPos, k2DetPos, linestyle = '--', color = 'r', label = 'hopf line')

    eqk1_1Tr = solve(eqTr.subs(x, eq2), k1)
    eqForK1Tr = eq1 - eqk1_1Tr[0]
    eqK2Tr = solve(eqForK1Tr.subs(km1, valK1m).subs(km3, valK3m).subs(k3, valK3), k2)
    funcK2Tr = lambdify(y, eqK2Tr[0])
    funcK1Tr = lambdify(y, eq1.subs(x, eq2).subs(k2, eqK2Tr[0]).subs(km1, valK1m).subs(km3, valK3m).subs(k3, valK3))
    k1AllTr = funcK1Tr(yVal)
    k2AllTr = funcK2Tr(yVal)
    k1PosTr = [k1AllTr[i] for i in range(len(k1AllTr)) if k1AllTr[i] > 0 and k2AllTr[i] > 0]
    print(len(k1PosTr))
    k2PosTr = [k2AllTr[i] for i in range(len(k2AllTr)) if k1AllTr[i] > 0 and k2AllTr[i] > 0]
    print(len(k2PosTr))
    sadle, = plt.plot(k1PosTr, k2PosTr, color = 'g', label = 'sadle-nodle line')

    plt.xlim([0, 2])
    plt.ylim([0,5])
    plt.legend(handles=[hopf, sadle])
    plt.xlabel('k1')
    plt.ylabel('k2')
    plt.show()
Example #19
0
    def fbenchmark(f, var=[Symbol("x")]):
        """
        Do some benchmarks with f using clambdify, lambdify and psyco.
        """
        global cf, pf, psyf
        start = time()
        cf = clambdify(var, f)
        print "compile time (including sympy overhead): %f s" % (time() - start)
        pf = lambdify(var, f, "math")
        psyf = None
        try:
            import psyco

            psyf = lambdify(var, f, "math")
            psyco.bind(psyf)
        except ImportError:
            pass
        code = """for x in (i/1000. for i in range(1000)):
        f(%s)""" % (
            "x," * len(var)
        ).rstrip(
            ","
        )
        t1 = Timer(code, "from __main__ import cf as f")
        t2 = Timer(code, "from __main__ import pf as f")
        if psyf:
            t3 = Timer(code, "from __main__ import psyf as f")
        else:
            t3 = None
        print "for x = (0, 1, 2, ..., 999)/1000"
        print "20 times in 3 runs"
        print "compiled:      %.4f %.4f %.4f" % tuple(t1.repeat(3, 20))
        print "Python lambda: %.4f %.4f %.4f" % tuple(t2.repeat(3, 20))
        if t3:
            print "Psyco lambda:  %.4f %.4f %.4f" % tuple(t3.repeat(3, 20))
Example #20
0
def Newton_solver_gxgt(error, hx, ht, x0, p_value=1, q_value=1):
    
    gx, gt, p, q, hx1, hx2, ht1, ht2  = symbols('gx gt p q qhx1 hx2 ht1 ht2')
    epsilon1 = gx*hx1**p + gt*ht1**q - error[-2]
    epsilon2 = gx*hx2**p + gt*ht2**q - error[-1]


    epsilon = [epsilon1, epsilon2]
    x = [gx, gt]
    knowns = [p, q, hx1, hx2, ht1, ht2]
    
    def f(i,j):
        return diff(epsilon[i], x[j])
        
    Jacobi = Matrix(2, 2, f)

    JacobiInv = Jacobi.inv()
    epsilonfunc = lambdify([x, knowns], epsilon)
    JacobiInvfunc = lambdify([x, knowns], JacobiInv)
    x = x0
    knowns = [p_value, q_value, hx[-2], hx[-1], ht[-2], ht[-1]]
    F = np.asarray(epsilonfunc(x, knowns))
    
    for n in range(8):
        Jinv = np.asarray(JacobiInvfunc(x, knowns))
        F = np.asarray(epsilonfunc(x, knowns))
        x = x - np.dot(Jinv, F)

        print "n, x: ", n, x
    
    return x
Example #21
0
def velocity_field(psi): #takes a symbolic function and returns two lambda functions
#to evaluate the derivatives in both x and y.
   global w
   if velocity_components:
      u = lambdify((x,y), eval(x_velocity), modules='numpy')
      v = lambdify((x,y), eval(y_velocity), modules='numpy')
   else:
      if is_complex_potential:
         print "Complex potential, w(z) given"
         #define u, v symbolically as the imaginary part of the derivatives
         u = lambdify((x, y), sympy.im(psi.diff(y)), modules='numpy')
         v = lambdify((x, y), -sympy.im(psi.diff(x)), modules='numpy')
      else:
         #define u,v as the derivatives 
         print "Stream function, psi given"
         u = sympy.lambdify((x, y), psi.diff(y), 'numpy')
         v = sympy.lambdify((x, y), -psi.diff(x), 'numpy')
   if (branch_cuts): # If it's indicated that there are branch cuts in the mapping,
                      # then we need to return vectorized numpy functions to evaluate
                      # everything numerically, instead of symbolically 
                      # This of course results in a SIGNIFICANT time increase
                      #   (I don't know how to handle more than the primitive root
                      #   (symbolically in Sympy
      return np.vectorize(u),np.vectorize(v)
   else:
       # If there are no branch cuts, then return the symbolic lambda functions (MUCH faster)
      return u,v
Example #22
0
    def __init__(self, s=1, h1=0.2, h2=0.6, h3=0.2, v1=1, v2=1, v3=1,
                 base=None):
        """Inputs: s  - the stratification parameter
                   h1 - depth of layer 1
                   h2 - depth of layer 2
                   h3 - depth of layer 3
                   v1 - speed relation for layer 1
                   v2 - speed relation for layer 2
                   v3 - speed relation for layer 3.
                   base - optional precalculated base equation set
        """
        # Create functions of (a, b) for these given parameters
        self.F = self.F(v1=v1, v2=v2, v3=v3, h1=h1, h2=h2, h3=h3, s=s)
        self.G = self.G(v1=v1, v2=v2, v3=v3, h1=h1, h2=h2, h3=h3)
        self.f = sp.lambdify((a, b), self.F)
        self.g = sp.lambdify((a, b), self.G)

        self.H = h1, h2, h3
        self.V = v1, v2, v3

        self.base = base or LambBase(s=s, h1=h1, h2=h2, h3=h3)

        # Sample grid for finding F(a, b) = 0
        # resolution of rough zero search (np.arange)
        self.resolution = 0.01

        # bounds on physical solutions
        a_min, a_max = (-h1, 1 - h1)
        b_min, b_max = (-(h1 + h2), h3)

        s = 2 * self.resolution  # extra edge to consider
        x = np.arange(a_min - s, a_max + s, self.resolution)
        y = np.arange(b_min - s, b_max + s, self.resolution)

        self.AB = np.meshgrid(x, y)
Example #23
0
def test_curly_matrix_symbol():
    # Issue #15009
    curlyv = sympy.MatrixSymbol("{v}", 2, 1)
    lam = lambdify(curlyv, curlyv)
    assert lam(1)==1
    lam = lambdify(curlyv, curlyv, dummify=True)
    assert lam(1)==1
Example #24
0
    def make_numpy_fns_of_d1d2xw(self, dg_first, dg_second):

        args = self.normal_x_s_d.values() + self.normal_w_s_d.values() + \
            self.param_sym_dict.values()

        args_values_x = [x.subs(self.normal_xw_s_ss_values_d)
                         for x in self.normal_x_s_d.values()]

        args_values_w = [w.subs(self.normal_xw_s_ss_values_d)
                         for w in self.normal_w_s_d.values()]

        args_values_p = [p.subs(self.par_to_values_dict)
                         for p in self.param_sym_dict.values()]

        args_values = args_values_x + args_values_w + args_values_p

#        print '\nargs for lambdify:', args
#        print '\nargs values for lambdify:', args_values
#        print '\nself.normal_xw_s_ss_values_d:', self.normal_xw_s_ss_values_d
#        print '\nself.par_to_values_dict:', self.par_to_values_dict

        dg_first_lam = sympy.lambdify(args, dg_first, dummify=False)
        dg_second_lam = sympy.lambdify(args, dg_second, dummify=False)

        return dg_first_lam, dg_second_lam, args_values
Example #25
0
def derivative_matrix(deg, basis_functions, unroll=True):
    '''
    Matrix of \int_{-1}^{1}(L_i, L_j`) for polynomials spanned by deg+1 
    basis_functions.
    '''
    # Numerical quadrature, mas degree of integrand 2*deg - 1 -> deg
    xq, wq = np.polynomial.legendre.leggauss(deg)
    # Fast eval of basis and asis derivative
    x = Symbol('x')
    basis = [lambdify(x, f, 'numpy') for f in basis_functions(deg)]
    dbasis = [lambdify(x, f.diff(x, 1), 'numpy') for f in basis_functions(deg)]
    
    # Save calls to eval
    if unroll:
        V = np.zeros((len(basis), len(xq)))
        # Basis functions evaluated in quadrature points
        for row, f in enumerate(basis): V[row, :] = f(xq)

        dV = np.zeros((len(xq), len(basis)))
        # Basis derivatives evaluated in quadrature points
        for col, df in enumerate(dbasis): dV[:, col] = df(xq)
        
        # Integrate 
        C = (wq*V).dot(dV)

    # Here there are more calls to eval
    else:
        C = np.zeros((len(basis), len(basis)))
        for i, v in enumerate(basis):
            for j, du in enumerate(dbasis):
                C[i, j] = np.sum(wq*v(xq)*du(xq))
    
    return C
def make_integral(f_str):
    x          = sympy.Symbol('x')
    func_expr  = sympy.sympify(f_str)
    f          = sympy.lambdify(x, func_expr)
    int_expr   = sympy.integrate(func_expr)
    F          = sympy.lambdify(x, int_expr)
    return f, F
Example #27
0
    def make_numpy_fns_of_d1d2xw(self, dg_first, dg_second):

        args_x = self.xvar_tp1_sym + self.xvar_t_sym + self.xvar_tm1_sym

        args_w = self.wvar_tp1_sym + self.wvar_t_sym 

        args = args_x + args_w + self.param_sym_dict.values() 

        # args_values_x =   [x.subs(self.normal_xw_s_ss_values_d)
        #                  for x in args_x]               

        # args_values_w =   [x.subs(self.normal_xw_s_ss_values_d)
        #                  for x in args_w]               
        
        # args_values_p = [p.subs(self.par_to_values_dict)
        #                  for p in self.param_sym_dict.values()]

        # args_values = args_values_x + args_values_w + args_values_p

        dg_first_lam = sympy.lambdify(args, dg_first)
        dg_second_lam = sympy.lambdify(args, dg_second)

        self.fun_d_first_numpy = dg_first_lam
        self.fun_d_second_numpy = dg_second_lam

        return dg_first_lam, dg_second_lam
Example #28
0
def test_quadratic():
    """Verify a quadratic solution."""
    I = 1.2; V = 3; m = 2; b = 0.9
    s = lambda u: 4*u
    t = sym.Symbol('t')
    dt = 0.2
    T = 2

    q = 2  # arbitrary constant
    u_exact = I + V*t + q*t**2
    F = sym.lambdify(t, lhs_eq(t, m, b, s, u_exact, 'linear'))
    u_exact = sym.lambdify(t, u_exact, modules='numpy')
    #u1, t1 = solver(I, V, m, b, s, F, dt, T, 'linear')
    u1, t1 = solver_bwdamping(I, V, m, b, s, F, dt, T, 'linear')
    diff = np.abs(u_exact(t1) - u1).max()
    print diff
    tol = 1E-13
    #assert diff < tol

    # In the quadratic damping case, u_exact must be linear
    # in order to exactly recover this solution
    u_exact = I + V*t
    F = sym.lambdify(t, lhs_eq(t, m, b, s, u_exact, 'quadratic'))
    u_exact = sym.lambdify(t, u_exact, modules='numpy')
    #u2, t2 = solver(I, V, m, b, s, F, dt, T, 'quadratic')
    u2, t2 = solver_bwdamping(I, V, m, b, s, F, dt, T, 'quadratic')
    diff = np.abs(u_exact(t2) - u2).max()
    print diff
    assert diff < tol
def make_derivative(f_str):
    x          = sympy.Symbol('x')
    func_expr  = sympy.sympify(f_str)
    f          = sympy.lambdify(x, func_expr)
    deriv_expr = sympy.diff(func_expr)
    df         = sympy.lambdify(x, deriv_expr)
    return f, df
Example #30
0
def comparison_plot(f, u, Omega, plotfile='tmp'):
    """Compare f(x,y) and u(x,y) for x,y in Omega in a plot."""
    x, y = sm.symbols('x y')

    f = sm.lambdify([x,y], f, modules="numpy")
    u = sm.lambdify([x,y], u, modules="numpy")
    # When doing symbolics, Omega can easily contain symbolic expressions,
    # assume .evalf() will work in that case to obtain numerical
    # expressions, which then must be converted to float before calling
    # linspace below
    for r in range(2):
        for s in range(2):
            if not isinstance(Omega[r][s], (int,float)):
                Omega[r][s] = float(Omega[r][s].evalf())

    resolution = 41  # no of points in plot
    xcoor = linspace(Omega[0][0], Omega[0][1], resolution)
    ycoor = linspace(Omega[1][0], Omega[1][1], resolution)
    xv, yv = ndgrid(xcoor, ycoor)
    # Vectorized functions expressions does not work with
    # lambdify'ed functions without the modules="numpy"
    exact  = f(xv, yv)
    approx = u(xv, yv)
    figure()
    surfc(xv, yv, exact, title='f(x,y)',
          colorbar=True, colormap=hot(), shading='flat')
    if plotfile:
        savefig('%s_f.pdf' % plotfile, color=True)
        savefig('%s_f.png' % plotfile)
    figure()
    surfc(xv, yv, approx, title='f(x,y)',
          colorbar=True, colormap=hot(), shading='flat')
    if plotfile:
        savefig('%s_u.pdf' % plotfile, color=True)
        savefig('%s_u.png' % plotfile)
def test_str_args():
    f = lambdify('x,y,z', 'z,y,x')
    assert f(3, 2, 1) == (1, 2, 3)
    assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0)
    # make sure correct number of args required
    raises(TypeError, lambda: f(0))
def test_bad_args():
    # no vargs given
    raises(TypeError, lambda: lambdify(1))
    # same with vector exprs
    raises(TypeError, lambda: lambdify([1, 2]))
phi = basis(d=1)
phi
element_matrix(phi, Omega_e=[0.1, 0.2], symbolic=True)
element_matrix(phi, Omega_e=[0.1, 0.2], symbolic=False)

h, x = sm.symbols('h x')
nodes = [0, h, 2 * h]
elements = [[0, 1], [1, 2]]
phi = basis(d=1)
f = x * (1 - x)
A, b = assemble(nodes, elements, phi, f, symbolic=True)
A
b
c = A.LUsolve(b)
c
fn = sm.lambdify([x], f)
[fn(xc) for xc in nodes]

# The corresponding numerical computations, as done by sympy and
# still based on symbolic integration, goes as follows:

nodes = [0, 0.5, 1]
elements = [[0, 1], [1, 2]]
phi = basis(d=1)
x = sm.Symbol('x')
f = x * (1 - x)
A, b = assemble(nodes, elements, phi, f, symbolic=False)
A
b
c = A.LUsolve(b)
c
def test_atoms():
    # Non-Symbol atoms should not be pulled out from the expression namespace
    f = lambdify(x, pi + x, {"pi": 3.14})
    assert f(0) == 3.14
    f = lambdify(x, I + x, {"I": 1j})
    assert f(1) == 1 + 1j
def test_Min_Max():
    # see gh-10375
    assert lambdify((x, y, z), Min(x, y, z))(1, 2, 3) == 1
    assert lambdify((x, y, z), Max(x, y, z))(1, 2, 3) == 3
def test_ITE():
    assert lambdify((x, y, z), ITE(x, y, z))(True, 5, 3) == 5
    assert lambdify((x, y, z), ITE(x, y, z))(False, 5, 3) == 3
def test_issue_2790():
    assert lambdify((x, (y, z)), x + y)(1, (2, 4)) == 3
    assert lambdify((x, (y, (w, z))), w + x + y + z)(1, (2, (3, 4))) == 10
    assert lambdify(x, x + 1, dummify=False)(1) == 2
def test_true_false():
    # We want exact is comparison here, not just ==
    assert lambdify([], true)() is True
    assert lambdify([], false)() is False
def test_lambdify_imps():
    # Test lambdify with implemented functions
    # first test basic (sympy) lambdify
    f = sympy.cos
    assert lambdify(x, f(x))(0) == 1
    assert lambdify(x, 1 + f(x))(0) == 2
    assert lambdify((x, y), y + f(x))(0, 1) == 2
    # make an implemented function and test
    f = implemented_function("f", lambda x: x + 100)
    assert lambdify(x, f(x))(0) == 100
    assert lambdify(x, 1 + f(x))(0) == 101
    assert lambdify((x, y), y + f(x))(0, 1) == 101
    # Can also handle tuples, lists, dicts as expressions
    lam = lambdify(x, (f(x), x))
    assert lam(3) == (103, 3)
    lam = lambdify(x, [f(x), x])
    assert lam(3) == [103, 3]
    lam = lambdify(x, [f(x), (f(x), x)])
    assert lam(3) == [103, (103, 3)]
    lam = lambdify(x, {f(x): x})
    assert lam(3) == {103: 3}
    lam = lambdify(x, {f(x): x})
    assert lam(3) == {103: 3}
    lam = lambdify(x, {x: f(x)})
    assert lam(3) == {3: 103}
    # Check that imp preferred to other namespaces by default
    d = {'f': lambda x: x + 99}
    lam = lambdify(x, f(x), d)
    assert lam(3) == 103
    # Unless flag passed
    lam = lambdify(x, f(x), d, use_imps=False)
    assert lam(3) == 102
def test_own_module():
    f = lambdify(x, sin(x), math)
    assert f(0) == 0.0
def test_sym_integral():
    f = Lambda(x, exp(-x**2))
    l = lambdify(x, Integral(f(x), (x, -oo, oo)), modules="sympy")
    assert l(y).doit() == sqrt(pi)
def test_own_namespace():
    myfunc = lambda x: 1
    f = lambdify(x, sin(x), {"sin": myfunc})
    assert f(0.1) == 1
    assert f(100) == 1
def test_sym_single_arg():
    f = lambdify(x, x * y)
    assert f(z) == z * y
def test_sym_list_args():
    f = lambdify([x, y], x + y + z)
    assert f(1, 2) == 3 + z
Example #45
0
    else:
        if n == 0:
            return 0
        else:
            return -1 / (n * np.pi)


t = sp.Symbol("t")
f0 = sp.Symbol("f0")

# dit zijn de formules voor de driehoeksgolf, zaagtandgolf en een sinus
D = 4 * sp.Abs(f0 * t + 1 / 4 - sp.floor(f0 * t + 3 / 4)) - 1
Z = f0 * t - sp.floor(f0 * t) - 1 / 2
Sin = sp.sin(2 * sp.pi * f0 * t)

Dt = sp.lambdify([t, f0], D, "numpy")
Zt = sp.lambdify([t, f0], Z, "numpy")
Sint = sp.lambdify([t, f0], Sin, "numpy")
print("setup klaar")

fig1 = plt.figure("figuur 1", dpi=500)

twaarden = np.linspace(0, 2, 10000)
f0waarde = 2

line1, = plt.plot(twaarden, Dt(twaarden, f0waarde))
line2, = plt.plot(twaarden, Zt(twaarden, f0waarde))
line3, = plt.plot(twaarden, Sint(twaarden, f0waarde))

plt.xlim(0, 2)
def test_integral():
    f = Lambda(x, exp(-x**2))
    l = lambdify(x, Integral(f(x), (x, -oo, oo)), modules="sympy")
    assert l(x) == Integral(exp(-x**2), (x, -oo, oo))
def test_trig_symbolic():
    f = lambdify([x], [cos(x), sin(x)])
    d = f(pi)
    assert abs(d[0] + 1) < 0.0001
    assert abs(d[1] - 0) < 0.0001
def test_number_precision():
    mpmath.mp.dps = 50
    sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
    f = lambdify(x, sin02, "mpmath")
    prec = 1e-49  # mpmath precision is around 50 decimal places
    assert -prec < f(0) - sin02 < prec
def test_vector_discontinuous():
    f = lambdify(x, (-1 / x, 1 / x))
    raises(ZeroDivisionError, lambda: f(0))
    assert f(1) == (-1.0, 1.0)
    assert f(2) == (-0.5, 0.5)
    assert f(-2) == (0.5, -0.5)
def test_python_div_zero_issue_11306():
    if not numpy:
        skip("numpy not installed.")
    p = Piecewise((1 / x, y < -1), (x, y <= 1), (1 / x, True))
    lambdify([x, y], p, modules='numpy')(0, 1)
def test_vector_simple():
    f = lambdify((x, y, z), (z, y, x))
    assert f(3, 2, 1) == (1, 2, 3)
    assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0)
    # make sure correct number of args required
    raises(TypeError, lambda: f(0))
def test_list_args():
    f = lambdify([x, y], x + y)
    assert f(1, 2) == 3
def test_single_arg():
    f = lambdify(x, 2 * x)
    assert f(1) == 2
def test_numpy_inverse():
    if not numpy:
        skip("numpy not installed.")
    A = Matrix([[1, x], [0, 1]])
    f = lambdify((x), A**-1, modules="numpy")
    numpy.testing.assert_array_equal(f(2), numpy.array([[1, -2], [0, 1]]))
def test_sin():
    f = lambdify(x, sin(x)**2)
    assert isinstance(f(2), float)
    f = lambdify(x, sin(x)**2, modules="math")
    assert isinstance(f(2), float)
def test_numpy_transpose():
    if not numpy:
        skip("numpy not installed.")
    A = Matrix([[1, x], [0, 1]])
    f = lambdify((x), A.T, modules="numpy")
    numpy.testing.assert_array_equal(f(2), numpy.array([[1, 0], [2, 1]]))
def test_no_args():
    f = lambdify([], 1)
    raises(TypeError, lambda: f(-1))
    assert f() == 1
def test_math():
    f = lambdify((x, y), sin(x), modules="math")
    assert f(0, 5) == 0
Example #59
0
t = sympy.symbols("t", real=True)
x = ss.ChiSquared("x", 1)
""" 
To get the left side of the Chebyshev inequality, we have to write this out 
as the following conditional probability,
"""

r = ss.P((x - 1) > t, x > 1) + ss.P(-(x - 1) > t, x < 1)
"""
Note that we cannot use vectorized inputs for the lambdify function because it contains embedded functions that are only
available in Sympy. Otherwise, we could have used lambdify(t,fw,numpy) to specify the corresponding functions in Numpy
to use for the expression.

This is because of certain limitations in the statistics module at this point in its devel- opment regarding the
absolute value function. We could take the above expression, which is a function of t and attempt to compute the
integral, but that would take a very long time (the expression is very long and complicated, which is why we did
not print it out above). This is because Sympy is a pure-python module that does not utilize any C-level optimizations
under the hood. In this situation, it’s better to use the built-in cumulative density function as in the following
(after some rearrangement of the terms),
"""

w = (1 - ss.cdf(x) * (t + 1)) + ss.cdf(x) * (1 - t)
fw = sympy.lambdify(t, w)
"""
To plot this, we can evaluate it at a variety of t values by using the .subs substitution method, but it is more
convenient to use the lambdify method to convert the expression to a function.
"""

map(fw, [0, 1, 2, 3, 4])
def test_trig_float():
    f = lambdify([x], [cos(x), sin(x)])
    d = f(3.14159)
    assert abs(d[0] + 1) < 0.0001
    assert abs(d[1] - 0) < 0.0001