Exemplo n.º 1
0
def idiff(eq, y, x, n=1):
    """Return ``dy/dx`` assuming that ``eq == 0``.

    Parameters
    ==========

    y : the dependent variable or a list of dependent variables (with y first)
    x : the variable that the derivative is being taken with respect to
    n : the order of the derivative (default is 1)

    Examples
    ========

    >>> from sympy.abc import x, y, a
    >>> from sympy.geometry.util import idiff

    >>> circ = x**2 + y**2 - 4
    >>> idiff(circ, y, x)
    -x/y
    >>> idiff(circ, y, x, 2).simplify()
    -(x**2 + y**2)/y**3

    Here, ``a`` is assumed to be independent of ``x``:

    >>> idiff(x + a + y, y, x)
    -1

    Now the x-dependence of ``a`` is made explicit by listing ``a`` after
    ``y`` in a list.

    >>> idiff(x + a + y, [y, a], x)
    -Derivative(a, x) - 1

    See Also
    ========

    sympy.core.function.Derivative: represents unevaluated derivatives
    sympy.core.function.diff: explicitly differentiates wrt symbols

    """
    if is_sequence(y):
        dep = set(y)
        y = y[0]
    elif isinstance(y, Symbol):
        dep = set([y])
    else:
        raise ValueError("expecting x-dependent symbol(s) but got: %s" % y)

    f = dict([(s, Function(
        s.name)(x)) for s in eq.atoms(Symbol) if s != x and s in dep])
    dydx = Function(y.name)(x).diff(x)
    eq = eq.subs(f)
    derivs = {}
    for i in range(n):
        yp = solve(eq.diff(x), dydx)[0].subs(derivs)
        if i == n - 1:
            return yp.subs([(v, k) for k, v in f.items()])
        derivs[dydx] = yp
        eq = dydx - yp
        dydx = dydx.diff(x)
Exemplo n.º 2
0
 def _main(expr):
     _new = []
     for a in expr.args:
         is_V = False
         if isinstance(a, V):
             is_V = True
             a = a.expr
         if a.is_Derivative:
             variables = a.atoms()
             func = a.expr
             variables.add(func)
             name = a.expr.__class__.__name__
             if ',' in name:
                 a = Function('%s' % name +
                       ''.join(map(str, a.variables)))(*variables)
             else:
                 a = Function('%s' % name + ',' +
                       ''.join(map(str, a.variables)))(*variables)
         #TODO add more, maybe all that have args
         elif a.is_Add or a.is_Mul or a.is_Pow:
             a = _main(a)
         if is_V:
             a = V(a)
             a.function = func
         _new.append( a )
     return expr.func(*tuple(_new))
Exemplo n.º 3
0
def test_latex_printer():
    r = Function('r')('t')
    assert VectorLatexPrinter().doprint(r ** 2) == "r^{2}"
    r2 = Function('r^2')('t')
    assert VectorLatexPrinter().doprint(r2.diff()) == r'\dot{r^{2}}'
    ra = Function('r__a')('t')
    assert VectorLatexPrinter().doprint(ra.diff().diff()) == r'\ddot{r^{a}}'
Exemplo n.º 4
0
def test_noncommutative_issue_15131():
    x = Symbol('x', commutative=False)
    t = Symbol('t', commutative=False)
    fx = Function('Fx', commutative=False)(x)
    ft = Function('Ft', commutative=False)(t)
    A = Symbol('A', commutative=False)
    eq = fx * A * ft
    eqdt = eq.diff(t)
    assert eqdt.args[-1] == ft.diff(t)
Exemplo n.º 5
0
def test_issue_7687():
    from sympy.core.function import Function
    from sympy.abc import x
    f = Function('f')(x)
    ff = Function('f')(x)
    match_with_cache = ff.matches(f)
    assert isinstance(f, type(ff))
    clear_cache()
    ff = Function('f')(x)
    assert isinstance(f, type(ff))
    assert match_with_cache == ff.matches(f)
Exemplo n.º 6
0
def test_lambdify_Derivative_arg_issue_16468():
    f = Function('f')(x)
    fx = f.diff()
    assert lambdify((f, fx), f + fx)(10, 5) == 15
    assert eval(lambdastr((f, fx), f/fx))(10, 5) == 2
    raises(SyntaxError, lambda:
        eval(lambdastr((f, fx), f/fx, dummify=False)))
    assert eval(lambdastr((f, fx), f/fx, dummify=True))(10, 5) == 2
    assert eval(lambdastr((fx, f), f/fx, dummify=True))(10, 5) == S.Half
    assert lambdify(fx, 1 + fx)(41) == 42
    assert eval(lambdastr(fx, 1 + fx, dummify=True))(41) == 42
Exemplo n.º 7
0
def test_find_simple_recurrence():
    a = Function('a')
    n = Symbol('n')
    assert find_simple_recurrence([fibonacci(k) for k in range(12)]) == (
        -a(n) - a(n + 1) + a(n + 2))

    f = Function('a')
    i = Symbol('n')
    a = [1, 1, 1]
    for k in range(15): a.append(5*a[-1]-3*a[-2]+8*a[-3])
    assert find_simple_recurrence(a, A=f, N=i) == (
        -8*f(i) + 3*f(i + 1) - 5*f(i + 2) + f(i + 3))
    assert find_simple_recurrence([0, 2, 15, 74, 12, 3, 0,
                                    1, 2, 85, 4, 5, 63]) == 0
Exemplo n.º 8
0
def test_simple():
    sympy.var('x, y, r')
    u = Function('u')(x, y)
    w = Function('w')(x, y)
    f = Function('f')(x, y)
    e = (u.diff(x) + 1./2*w.diff(x,x)**2)*f.diff(x,y) \
            + w.diff(x,y)*f.diff(x,x)
    return Vexpr(e, u, w)
Exemplo n.º 9
0
def test_solve_for_functions_derivatives():
    t = Symbol('t')
    x = Function('x')(t)
    y = Function('y')(t)
    a11,a12,a21,a22,b1,b2 = symbols('a11,a12,a21,a22,b1,b2')

    soln = solve([a11*x + a12*y - b1, a21*x + a22*y - b2], x, y)
    assert soln == {
        x : (a22*b1 - a12*b2)/(a11*a22 - a12*a21),
        y : (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
        }

    assert solve(x - 1, x) == [1]
    assert solve(3*x - 2, x) == [Rational(2, 3)]

    soln = solve([a11*x.diff(t) + a12*y.diff(t) - b1, a21*x.diff(t) +
            a22*y.diff(t) - b2], x.diff(t), y.diff(t))
    assert soln == { y.diff(t) : (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
            x.diff(t) : (a22*b1 - a12*b2)/(a11*a22 - a12*a21) }

    assert solve(x.diff(t)-1, x.diff(t)) == [1]
    assert solve(3*x.diff(t)-2, x.diff(t)) == [Rational(2,3)]

    eqns = set((3*x - 1, 2*y-4))
    assert solve(eqns, set((x,y))) == { x : Rational(1, 3), y: 2 }
    x = Symbol('x')
    f = Function('f')
    F = x**2 + f(x)**2 - 4*x - 1
    assert solve(F.diff(x), diff(f(x), x)) == [-((x - 2)/f(x))]

    # Mixed cased with a Symbol and a Function
    x = Symbol('x')
    y = Function('y')(t)

    soln = solve([a11*x + a12*y.diff(t) - b1, a21*x +
            a22*y.diff(t) - b2], x, y.diff(t))
    assert soln == { y.diff(t) : (a11*b2 - a21*b1)/(a11*a22 - a12*a21),
            x : (a22*b1 - a12*b2)/(a11*a22 - a12*a21) }
Exemplo n.º 10
0
from sympy import Function

from devito.symbolics import Macro


# OPS Conventions
namespace = OrderedDict()

# OPS API
namespace['ops_init'] = 'ops_init'
namespace['ops_partition'] = 'ops_partition'
namespace['ops_timing_output'] = 'ops_timing_output'
namespace['ops_exit'] = 'ops_exit'
namespace['ops_par_loop'] = 'ops_par_loop'

namespace['ops_decl_stencil'] = Function(name='ops_decl_stencil')
namespace['ops_decl_block'] = Function(name='ops_decl_block')
namespace['ops_decl_dat'] = Function(name='ops_decl_dat')
namespace['ops_arg_dat'] = Function(name='ops_arg_dat')
namespace['ops_arg_gbl'] = Function(name='ops_arg_gbl')

namespace['ops_read'] = Macro('OPS_READ')
namespace['ops_write'] = Macro('OPS_WRITE')

namespace['ops_stencil_type'] = 'ops_stencil'
namespace['ops_block_type'] = 'ops_block'
namespace['ops_dat_type'] = 'ops_dat'

# Naming conventions
namespace['ops_define_dimension'] = lambda i: '#define OPS_%sD' % i
namespace['ops_kernel'] = lambda i: 'OPS_Kernel_%s' % i
Exemplo n.º 11
0
def get_cumulant(xn, yn, zn):
    """
    :param xn: order of x-nth cumulant
    :param yn:
    :param zn:
    :return: cumulant_xn_yn_zn

    Order cumulant's subterms: xn + yn + zn
    ex 5th order = m012*m020
    """

    x, y, z = symbols('x y z')
    F = Function('F')(x, y, z)

    mgf = ln(F)
    deriv = Derivative(mgf, (x, xn), (y, yn), (z, zn))

    all_terms = deriv.doit()
    all_terms = all_terms * F  # Geier: C = c * m000

    all_terms = simplify(all_terms)

    # result = collect(result, F)  # Thank you sympy:  NotImplementedError: Improve MV Derivative support in collect
    # so lets start from highest (2,2,2) ...

    all_terms = all_terms.subs({
        sym.Derivative(F, (x, 2), (y, 2), (z, 2)): Symbol('m_{222}'),
    })

    all_terms = all_terms.subs({
        sym.Derivative(F, (x, 1), (y, 2), (z, 2)): Symbol('m_{122}'),
        sym.Derivative(F, (x, 2), (y, 1), (z, 2)): Symbol('m_{212}'),
        sym.Derivative(F, (x, 2), (y, 2), (z, 1)): Symbol('m_{221}'),
    })

    all_terms = all_terms.subs({
        sym.Derivative(F, (x, 0), (y, 2), (z, 2)): Symbol('m_{022}'),
        sym.Derivative(F, (x, 2), (y, 0), (z, 2)): Symbol('m_{202}'),
        sym.Derivative(F, (x, 2), (y, 2), (z, 0)): Symbol('m_{220}'),
        sym.Derivative(F, (x, 2), (y, 1), (z, 1)): Symbol('m_{211}'),
        sym.Derivative(F, (x, 1), (y, 2), (z, 1)): Symbol('m_{121}'),
        sym.Derivative(F, (x, 1), (y, 1), (z, 2)): Symbol('m_{112}'),
    })

    pretty_dict = {
        sym.Derivative(F, (x, 2), (y, 1), (z, 0)): Symbol('m_{210}'),
        sym.Derivative(F, (x, 1), (y, 2), (z, 0)): Symbol('m_{120}'),

        sym.Derivative(F, (x, 1), (y, 1), (z, 1)): Symbol('m_{111}'),

        sym.Derivative(F, (x, 0), (y, 1), (z, 2)): Symbol('m_{012}'),
        sym.Derivative(F, (x, 0), (y, 2), (z, 1)): Symbol('m_{021}'),

        sym.Derivative(F, (x, 1), (y, 0), (z, 2)): Symbol('m_{102}'),
        sym.Derivative(F, (x, 2), (y, 0), (z, 1)): Symbol('m_{201}'),
    }
    all_terms = all_terms.subs(pretty_dict)

    all_terms = all_terms.subs({
        sym.Derivative(F, (x, 2)): Symbol('m_{200}'),
        sym.Derivative(F, (y, 2)): Symbol('m_{020}'),
        sym.Derivative(F, (z, 2)): Symbol('m_{002}'),
        sym.Derivative(F, (x, 1), (y, 1), (z, 0)): Symbol('m_{110}'),
        sym.Derivative(F, (x, 1), (y, 0), (z, 1)): Symbol('m_{101}'),
        sym.Derivative(F, (x, 0), (y, 1), (z, 1)): Symbol('m_{011}'),
    })

    all_terms = all_terms.subs({
        sym.Derivative(F, (x, 1)): Symbol('m_{100}'),
        sym.Derivative(F, (y, 1)): Symbol('m_{010}'),
        sym.Derivative(F, (z, 1)): Symbol('m_{001}'),
        F: Symbol('m_{000}'),
    })

    # all_terms = collect(all_terms, Symbol('m_{100}'))  # does nothing
    all_terms = Poly(all_terms, F).all_terms()
    all_terms = sum(F ** n * term for (n,), term in all_terms)

    # order = 4
    # given_order_terms = sum(F ** n * term for (n,), term in all_terms if n <= order)
    # given_order_terms_inv = sum(F ** (-n) * term for (n,), term in all_terms if n <= order)

    all_terms = simplify(all_terms)  # does nothing agan

    lower_m000_terms = []
    # # PYDEVD_USE_FRAME_EVAL = NO
    for term in all_terms.args:
        # may crash in debug session... sympy - thank you again
        ht = Symbol('m_{000}')
        higher_terms = [ht**(-2), ht**(-3), ht**(-4)]
        is_lower_order = not any(elem in higher_terms for elem in term.args)
        if is_lower_order:
            lower_m000_terms.append(term)
            # pprint(term)
        # print("------------------------")

    # Wolfram Alpha  - Derivatives of Abstract Functions
    # d^2/(dy*dx)(log(f(x,y)))
    return all_terms, lower_m000_terms
Exemplo n.º 12
0
Lagrange formalism

@author: Topher
"""

from __future__ import division

import sympy as sp
from sympy import sin,cos,Function

t = sp.Symbol('t')
params = sp.symbols('M , G , J , J_ball , R')
M , G , J , J_ball , R = params

# ball position r
r_t = Function('r')(t)
d_r_t = r_t.diff(t)
dd_r_t = r_t.diff(t,2)
# beam angle theta
theta_t = Function('theta')(t)
d_theta_t = theta_t.diff(t)
dd_theta_t = theta_t.diff(t,2)
# torque of the beam
tau = Function('tau')

# kinetic energy
T = ((M + J_ball/R**2)*d_r_t**2 + (J + M*r_t**2 + J_ball)*d_theta_t**2)/2

# potential energy
V = M*G*r_t*sin(theta_t)
Exemplo n.º 13
0
print "r =", g2

#Propagation constants along the axes are related
g3 = alpha1**2 + beta1**2 + gamma1**2

# Simplifying
g3=g3.subs(sin(phi)**2, 1-cos(phi)**2).expand().simplify()

print r'%\alpha^{2} + \beta^{2} + \gamma^{2} = ', latex(g3)

x_hat = Matrix([
    rho * sin(theta) * cos(phi),
    rho * sin(theta) * sin(phi),
    rho * cos(theta)])

psi = Function("psi")

psi =exp(I*omega*t) * exp(-I*g2)
print "\Psi =", latex(psi)

#Derivatives of the wave function of the coordinates
dpsidx=psi.diff(x)
dpsidx=dpsidx.subs(psi,'Psi').expand().simplify()
print "d \Psi / dx =", latex(dpsidx)

dpsidy=psi.diff(y)
dpsidy=dpsidy.subs(psi,'Psi').expand().simplify()
print "d \Psi / dy =", latex(dpsidy)

dpsidz=psi.diff(z)
dpsidz=dpsidz.subs(psi,'Psi').expand().simplify()
Exemplo n.º 14
0
def test_karr_convention():
    # Test the Karr summation convention that we want to hold.
    # See his paper "Summation in Finite Terms" for a detailed
    # reasoning why we really want exactly this definition.
    # The convention is described on page 309 and essentially
    # in section 1.4, definition 3:
    #
    # \sum_{m <= i < n} f(i) 'has the obvious meaning'   for m < n
    # \sum_{m <= i < n} f(i) = 0                         for m = n
    # \sum_{m <= i < n} f(i) = - \sum_{n <= i < m} f(i)  for m > n
    #
    # It is important to note that he defines all sums with
    # the upper limit being *exclusive*.
    # In contrast, sympy and the usual mathematical notation has:
    #
    # sum_{i = a}^b f(i) = f(a) + f(a+1) + ... + f(b-1) + f(b)
    #
    # with the upper limit *inclusive*. So translating between
    # the two we find that:
    #
    # \sum_{m <= i < n} f(i) = \sum_{i = m}^{n-1} f(i)
    #
    # where we intentionally used two different ways to typeset the
    # sum and its limits.

    i = Symbol("i", integer=True)
    k = Symbol("k", integer=True)
    j = Symbol("j", integer=True)

    # A simple example with a concrete summand and symbolic limits.

    # The normal sum: m = k and n = k + j and therefore m < n:
    m = k
    n = k + j

    a = m
    b = n - 1
    S1 = Sum(i**2, (i, a, b)).doit()

    # The reversed sum: m = k + j and n = k and therefore m > n:
    m = k + j
    n = k

    a = m
    b = n - 1
    S2 = Sum(i**2, (i, a, b)).doit()

    assert simplify(S1 + S2) == 0

    # Test the empty sum: m = k and n = k and therefore m = n:
    m = k
    n = k

    a = m
    b = n - 1
    Sz = Sum(i**2, (i, a, b)).doit()

    assert Sz == 0

    # Another example this time with an unspecified summand and
    # numeric limits. (We can not do both tests in the same example.)
    f = Function("f")

    # The normal sum with m < n:
    m = 2
    n = 11

    a = m
    b = n - 1
    S1 = Sum(f(i), (i, a, b)).doit()

    # The reversed sum with m > n:
    m = 11
    n = 2

    a = m
    b = n - 1
    S2 = Sum(f(i), (i, a, b)).doit()

    assert simplify(S1 + S2) == 0

    # Test the empty sum with m = n:
    m = 5
    n = 5

    a = m
    b = n - 1
    Sz = Sum(f(i), (i, a, b)).doit()

    assert Sz == 0

    e = Piecewise((exp(-i), Mod(i, 2) > 0), (0, True))
    s = Sum(e, (i, 0, 11))
    assert s.n(3) == s.doit().n(3)
Exemplo n.º 15
0
def test_coeff2():
    r, kappa = symbols('r, kappa')
    psi = Function("psi")
    g = 1 / r**2 * (2 * r * psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
    g = g.expand()
    assert g.coeff((psi(r).diff(r))) == 2 / r
Exemplo n.º 16
0
import sys
import numpy as np
import sympy as sm
from sympy.solvers import solve
from sympy import Symbol, Function
import GUI as gui
import math
GCodeFile = open('C:\\3D Printer Calculus Project\\docs\\Sample.txt', 'w+')
x = Symbol('x')
f = Function('f')(x)
f = 0.5*x
xVals = []
yVals = []
zVals = []
SideArray = []
TotalVolume = 0
AxisChoice = gui.AxisRevScreen()
if AxisChoice == "X-axis":
	Bounds = gui.BoundsScreen()
	FirstBound = int(Bounds[0])
	FinalBound = int(Bounds[1])
	xInitialVal = FirstBound
	yInitialVal = f.subs(x, FirstBound)
	zInitialVal = 0
	xVals.append(xInitialVal)
	yVals.append(yInitialVal)
	zVals.append(zInitialVal)
	FinalBound1 = int(FinalBound * 10)
	FirstBound1 = int(FirstBound * 10)
	for t in range (FirstBound1, FinalBound1):
	### This for loop generates the x coordinates ###
Exemplo n.º 17
0
def test_issue_4194():
    # simplify should call cancel
    from sympy.abc import x, y
    f = Function('f')
    assert simplify((4 * x + 6 * f(y)) / (2 * x + 3 * f(y))) == 2
Exemplo n.º 18
0
    def __init__(self, basis, **kwargs):

        kwargs = test_init_slots(Metric.init_slots, **kwargs)

        self.name = 'GA' + str(Metric.count)
        Metric.count += 1

        if not utils.isstr(basis):
            raise TypeError('"' + str(basis) + '" must be string')

        X = kwargs['X']  # Vector manifold
        g = kwargs['g']  # Explicit metric or base metric for vector manifold
        debug = kwargs['debug']
        coords = kwargs['coords']  # Manifold coordinates (sympy symbols)
        norm = kwargs['norm']  # Normalize basis vectors
        self.sig = kwargs['sig']  # Hint for metric signature
        self.gsym = kwargs['gsym']
        self.Isq = kwargs[
            'Isq']  #: Sign of I**2, only needed if I**2 not a number

        self.debug = debug
        self.is_ortho = False  # Is basis othogonal
        self.coords = coords  # Manifold coordinates
        if self.coords is None:
            self.connect_flg = False
        else:
            self.connect_flg = True  # Connection needed for postion dependent metric
        self.norm = norm  # True to normalize basis vectors
        self.detg = None  #: Determinant of g
        self.g_adj = None  #: Adjugate of g
        self.g_inv = None  #: Inverse of g
        # Generate list of basis vectors and reciprocal basis vectors
        # as non-commutative symbols

        if ' ' in basis or ',' in basis or '*' in basis:  # bases defined by substrings separated by spaces or commas
            self.basis = symbols_list(basis)
            self.r_symbols = symbols_list(basis, sub=False)
        else:
            if coords is not None:  # basis defined by root string with symbol list as indices
                self.basis = symbols_list(basis, coords)
                self.r_symbols = symbols_list(basis, coords, sub=False)
                self.coords = coords
                if self.debug:
                    printer.oprint('x^{i}', self.coords)
            else:
                raise ValueError('for basis "' + basis +
                                 '" coords must be entered')

        if self.debug:
            printer.oprint('e_{i}', self.basis, 'e^{i}', self.r_symbols)
        self.n = len(self.basis)
        self.n_range = list(range(self.n))

        # Generate metric as list of lists of symbols, rationals, or functions of coordinates

        if g is None:
            if X is None:  # default metric from dot product of basis as symbols
                self.g = self.metric_symbols_list()
            else:  # Vector manifold
                if coords is None:
                    raise ValueError('For metric derived from vector field ' +
                                     ' coordinates must be defined.')
                else:  # Vector manifold defined by vector field
                    dX = []
                    for coord in coords:  # Get basis vectors by differentiating vector field
                        dX.append([diff(x, coord) for x in X])
                    g_tmp = []
                    for dx1 in dX:
                        g_row = []
                        for dx2 in dX:
                            dx1_dot_dx2 = trigsimp(
                                Metric.dot_orthogonal(dx1, dx2, g))
                            g_row.append(dx1_dot_dx2)
                        g_tmp.append(g_row)
                    self.g = Matrix(g_tmp)
                    if self.debug:
                        printer.oprint('X_{i}', X, 'D_{i}X_{j}', dX)

        else:  # metric is symbolic or list of lists of functions of coordinates
            if utils.isstr(g):  # metric elements are symbols or constants
                if g == 'g':  # general symbolic metric tensor (g_ij functions of position)
                    g_lst = []
                    g_inv_lst = []
                    for coord in self.coords:
                        i1 = str(coord)
                        tmp = []
                        tmp_inv = []
                        for coord2 in self.coords:
                            i2 = str(coord2)
                            tmp.append(
                                Function('g_' + i1 + '_' + i2)(*self.coords))
                            tmp_inv.append(
                                Function('g__' + i1 + '__' + i2)(*self.coords))
                        g_lst.append(tmp)
                        g_inv_lst.append(tmp_inv)
                    self.g = Matrix(g_lst)
                    self.g_inv = Matrix(g_inv_lst)
                else:  # specific symbolic metric tensor (g_ij are symbolic or numerical constants)
                    self.g = self.metric_symbols_list(
                        g)  # construct symbolic metric from string and basis
            else:  # metric is given as list of function or list of lists of function or matrix of functions
                if isinstance(g, Matrix):
                    self.g = g
                else:
                    if isinstance(g[0], list):
                        self.g = Matrix(g)
                    else:
                        m = eye(len(g))
                        for i in range(len(g)):
                            m[i, i] = g[i]
                        self.g = m

        self.g_raw = copy.deepcopy(
            self.g)  # save original metric tensor for use with submanifolds

        if self.debug:
            printer.oprint('g', self.g)

        # Determine if metric is orthogonal

        self.is_ortho = True

        for i in self.n_range:
            for j in self.n_range:
                if i < j:
                    if self.g[i, j] != 0:
                        self.is_ortho = False
                        break

        self.g_is_numeric = True

        for i in self.n_range:
            for j in self.n_range:
                if i < j:
                    if not self.g[i, j].is_number:
                        self.g_is_numeric = False
                        break

        if self.coords is not None:
            self.derivatives_of_basis()  # calculate derivatives of basis
            if self.norm:  # normalize basis, metric, and derivatives of normalized basis
                if not self.is_ortho:
                    raise ValueError(
                        '!!!!Basis normalization only implemented for orthogonal basis!!!!'
                    )
                self.e_norm = []
                for i in self.n_range:
                    self.e_norm.append(square_root_of_expr(self.g[i, i]))
                if debug:
                    printer.oprint('|e_{i}|', self.e_norm)
            else:
                self.e_norm = None

        if self.norm:
            if self.is_ortho:
                self.normalize_metric()
            else:
                raise ValueError(
                    '!!!!Basis normalization only implemented for orthogonal basis!!!!'
                )

        if not self.g_is_numeric:
            self.signature()
            # Sign of square of pseudo scalar
            self.e_sq_sgn = '+'
            if ((self.n * (self.n - 1)) // 2 + self.sig[1]) % 2 == 1:
                self.e_sq_sgn = '-'

        if self.debug:
            print('signature =', self.sig)
Exemplo n.º 19
0
from sympy import symbols, Function, exp, var, Piecewise
from ComputabilityGraphs.CMTVS import CMTVS
from bgc_md2.helper import bgc_md2_computers
from .source_minus_1 import mvs as mvs_base

Bib = mvs_base.get_BibInfo()
for name in Bib.sym_dict.keys():
    var(name)
mrso = Function('mrso')
tsl = Function('tsl')
NPP = Function('NPP')
subs_dict = {
    xi:
    Piecewise(
        (exp(E * (1 / (10 - T0) - 1 / (tsl(t) - T0))) * mrso(t) /
         (KM + mrso(t)), tsl(t) > T0),
        #(0,tsl(t)<T0)
        (0, True)  #catch all
    )
}

s = {
    mvs_base.get_InternalFluxesBySymbol().subs(subs_dict),
    mvs_base.get_OutFluxesBySymbol().subs(subs_dict)
}
mvs = mvs_base.update(s)
Exemplo n.º 20
0
def test_recurse_Application_args():
    F = Lambda((x, y), exp(2 * x + 3 * y))
    f = Function('f')
    A = f(x, f(x, x))
    C = F(x, F(x, x))
    assert A.subs(f, F) == A.replace(f, F) == C
Exemplo n.º 21
0
def test_equality_subs2():
    f = Function('f')
    eq = Eq(f(x)**2, 16)
    assert bool(eq.subs(f(x), 3)) is False
    assert bool(eq.subs(f(x), 4)) is True
Exemplo n.º 22
0
def test_deriv_sub_bug3():
    y = Symbol('y')
    f = Function('f')
    pat = Derivative(f(x), x, x)
    assert pat.subs(y, y**2) == Derivative(f(x), x, x)
    assert pat.subs(y, y**2) != Derivative(f(x), x)
Exemplo n.º 23
0
def test_3d_scalar_3():
    print('============== test_3d_scalar_3 ================')

    # ... define the weak formulation
    x, y, z = symbols('x y z')

    u = Symbol('u')
    v = Symbol('v')

    b = Function('b')

    a = Lambda((x, y, z, v, u), Dot(Grad(u), Grad(v)) + b(x, y, z) * u * v)
    # ...

    # ...  create a finite element space
    p1 = 2
    p2 = 2
    p3 = 2
    ne1 = 2
    ne2 = 2
    ne3 = 2
    # ...

    print('> Grid   :: [{},{},{}]'.format(ne1, ne2, ne3))
    print('> Degree :: [{},{},{}]'.format(p1, p2, p3))

    grid_1 = linspace(0., 1., ne1 + 1)
    grid_2 = linspace(0., 1., ne2 + 1)
    grid_3 = linspace(0., 1., ne3 + 1)

    V1 = SplineSpace(p1, grid=grid_1)
    V2 = SplineSpace(p2, grid=grid_2)
    V3 = SplineSpace(p3, grid=grid_3)

    V = TensorFemSpace(V1, V2, V3)

    # ...

    # ... user defined function
    def b(x, y, z):
        r = 1. + x * (1. - x) + y * (1. - y) + z * (1. - z)
        return r

    # ...

    # ... create an interactive pyccel context
    from pyccel.epyccel import ContextPyccel

    context = ContextPyccel(name='context_3')
    context.insert_function(b, ['double', 'double', 'double'],
                            kind='function',
                            results=['double'])

    context.compile()
    # ...

    # ...
    kernel_py = compile_kernel('kernel_scalar_3',
                               a,
                               V,
                               context=context,
                               verbose=True,
                               backend='python')

    kernel_f90 = compile_kernel('kernel_scalar_3',
                                a,
                                V,
                                context=context,
                                verbose=True,
                                backend='fortran')
    # ...

    # ...
    M_py = assemble_matrix(V, kernel_py)
    M_f90 = assemble_matrix(V, kernel_f90)
    # ...

    assert_identical_coo(M_py, M_f90)
Exemplo n.º 24
0
import sys
from argparse import ArgumentParser
from typing import List

from sympy import Function, diff, dsolve, integrate, solve, var

# TODO: fix it
sys.path.append("./")
from calculus_of_variations.abstract_problem import AbstractSolver

t = var("t")
x = Function("x")(t)
x_diff = diff(x, t)

# maximum 4 order derivatives
x_diff_2 = diff(x, t, 2)
x_diff_3 = diff(x, t, 3)
x_diff_4 = diff(x, t, 4)


class HigherDerivativesSolver(AbstractSolver):
    """
    Solver for simplest problem with higher derivatives in calculus of variation.

    Attributes:
        n: Order of differentiation.
        L: Integrand.
        t0: Lower limit of the integral.
        t1: Upper limit of the integral.
        x0: Boundary condition in t0.
        x1: Boundary condition in t1.
Exemplo n.º 25
0
"""
Created on Sun Jul 21 01:08:44 2019

@author: nina
"""

from IPython.display import display
import sympy
from sympy import Function, sqrt, dsolve, Eq, Derivative
from sympy import solve, Poly, Eq, Function, exp
from sympy import Indexed, IndexedBase, Tuple, sqrt

t = sympy.Symbol('t')
d = 0
o = 0.5
ro00 = Function('ro00')(t)
ro01 = Function('ro01')(t)
ro10 = Function('ro10')(t)
ro11 = Function('ro11')(t)
I = sympy.Symbol('I')

eq1 = Eq(Derivative(ro00, t), ro11 - I * (o * ro01 / 2 - o * ro10 / 2))
eq2 = Eq(Derivative(ro01, t),
         -ro01 - I * (-d * ro01 + o * ro00 / 2 - o * ro11 / 2))
eq3 = Eq(Derivative(ro10, t),
         -ro10 - I * (d * ro10 - o * ro00 / 2 + o * ro11 / 2))
eq4 = Eq(Derivative(ro11, t), -ro11 - I * (-o * ro01 / 2 + o * ro10 / 2))

"resenje je sa konstantama C1, C2 i C3"
soln = dsolve((eq1, eq2, eq3, eq4))
display(soln)
Exemplo n.º 26
0
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1) + exp(2)) == "e + e^{2}"

    f = Function('f')
    assert latex(f(x)) == '\\operatorname{f}{\\left (x \\right )}'

    beta = Function('beta')

    assert latex(beta(x)) == r"\beta{\left (x \right )}"
    assert latex(sin(x)) == r"\sin{\left (x \right )}"
    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
        r"\sin {2 x^{2}}"
    assert latex(sin(x**2), fold_func_brackets=True) == \
        r"\sin {x^{2}}"

    assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="full") == \
        r"\arcsin^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="power") == \
        r"\sin^{-1}{\left (x \right )}^{2}"
    assert latex(asin(x**2), inv_trig_style="power",
                 fold_func_brackets=True) == \
        r"\sin^{-1} {x^{2}}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(factorial2(k)) == r"k!!"
    assert latex(factorial2(-k)) == r"\left(- k\right)!!"

    assert latex(binomial(2, k)) == r"{\binom{2}{k}}"

    assert latex(FallingFactorial(3,
                                  k)) == r"{\left(3\right)}_{\left(k\right)}"
    assert latex(RisingFactorial(3, k)) == r"{\left(3\right)}^{\left(k\right)}"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)"
    assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
    assert latex(Abs(x)) == r"\lvert{x}\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x + y)) == r"\Re {\left (x + y \right )}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
    assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'

    assert latex(cot(x)) == r'\cot{\left (x \right )}'
    assert latex(coth(x)) == r'\coth{\left (x \right )}'
    assert latex(re(x)) == r'\Re{x}'
    assert latex(im(x)) == r'\Im{x}'
    assert latex(root(x, y)) == r'x^{\frac{1}{y}}'
    assert latex(arg(x)) == r'\arg{\left (x \right )}'
    assert latex(zeta(x)) == r'\zeta\left(x\right)'

    assert latex(zeta(x)) == r"\zeta\left(x\right)"
    assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)"
    assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)"
    assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)"
    assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)"
    assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)"
    assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)"
    assert latex(polylog(x,
                         y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)"
    assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)"
    assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)"

    assert latex(Ei(x)) == r'\operatorname{Ei}{\left (x \right )}'
    assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left (x \right )}'
    assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)'
    assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left (x \right )}'
    assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left (x \right )}'
    assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left (x \right )}'
    assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}{\left (x \right )}'

    # Test latex printing of function names with "_"
    assert latex(
        polar_lift(0)) == r"\operatorname{polar\_lift}{\left (0 \right )}"
    assert latex(polar_lift(0)**
                 3) == r"\operatorname{polar\_lift}^{3}{\left (0 \right )}"
Exemplo n.º 27
0
A Lewis July 2017
"""

import ctypes
import os
import sympy
from sympy import diff, Eq, simplify, Function, Symbol
from sympy.abc import t, kappa, K, k

# Background variables

tau0 = Symbol('tau0', description='conformal time today')
tau_maxvis = Symbol('tau_maxvis', description='conformal time of peak visibility')

f_K = Function('f_K', description='comoving angular diameter distance')

H = Function('H', description='comoving hubble parameter', camb_var='adotoa')(t)
rho = Function('rho', description='total density', camb_var='grho', camb_sub='grho/kappa/a**2')(t)
P = Function('P', description='total pressure', camb_var='gpres', camb_sub='gpres/kappa/a**2')(t)
a = Function('a', description='scale factor')(t)

rho_b = Function('rho_b', description='baryon density', camb_var='grhob_t', camb_sub='grhob_t/kappa/a**2')(t)
rho_c = Function('rho_c', description='CDM density', camb_var='grhoc_t', camb_sub='grhoc_t/kappa/a**2')(t)
rho_g = Function('rho_g', description='photon density', camb_var='grhog_t', camb_sub='grhog_t/kappa/a**2')(t)
rho_r = Function('rho_r', description='massless neutrino density', camb_var='grhor_t', camb_sub='grhor_t/kappa/a**2')(t)
rho_nu = Function('rho_nu', description='massive neutrino density', camb_var='grhonu_t',
                  camb_sub='grhonu_t/kappa/a**2')(t)
rho_de = Function('rho_de', description='dark energy density', camb_var='grhov_t', camb_sub='grhov_t/kappa/a**2')(t)

p_b = Function('p_b', description='baryon pressure', camb_sub='0')(t)
Exemplo n.º 28
0
'''
    Module for symbolic computations.    
'''
import numpy as np
from sympy import (symbols, Function, diff, lambdify, simplify, sin, cos, sqrt)
from dec.helper import bunch
from dec.symform import form

# Coordinates
x, y, z = symbols('x y z')
# Vector Fields
u, v = Function('u')(x, y), Function('v')(x, y)
# Scalar Fields
f, g = Function('f')(x, y), Function('g')(x, y)
# Coordinates of Simplex Vertices
x0, y0, x1, y1, x2, y2 = symbols('x0, y0, x1, y1, x2, y2')
"""
V represents the velocity vector field.
"""
V = [(-2 * sin(y) * cos(x / 2)**2, 2 * sin(x) * cos(y / 2)**2),
     (-cos(x / 2) * sin(y / 2), sin(x / 2) * cos(y / 2)), (-sin(y), sin(x)),
     (-sin(2 * y), sin(x)), (1, 0)]
"""
p represents the pressure scalar field.
"""
p = [(-cos(2 * x) * (5 + 4 * cos(y)) - 5 *
      (4 * cos(y) + cos(2 * y)) - 4 * cos(x) * (5 + 5 * cos(y) + cos(2 * y))) /
     20, -(cos(x) + cos(y)) / 4, -cos(x) * cos(y),
     -4 * cos(x) * cos(2 * y) / 5, 0]

Exemplo n.º 29
0
def test_distribution_over_equality():
    f = Function('f')
    assert Product(Eq(x*2, f(x)), (x, 1, 3)).doit() == Eq(48, f(1)*f(2)*f(3))
    assert Sum(Eq(f(x), x**2), (x, 0, y)) == \
        Eq(Sum(f(x), (x, 0, y)), Sum(x**2, (x, 0, y)))
Exemplo n.º 30
0
from sympy import (symbols, factorial, sqrt, Rational, atan, I, log, fps, O,
                   Sum, oo, S, pi, cos, sin, Function, exp, Derivative, asin,
                   airyai, acos, acosh, gamma, erf, asech, Add, Integral, Mul,
                   integrate)
from sympy.series.formal import (rational_algorithm, FormalPowerSeries,
                                 rational_independent, simpleDE, exp_re,
                                 hyper_re)
from sympy.utilities.pytest import raises, XFAIL, slow

x, y, z = symbols('x y z')
n, m, k = symbols('n m k', integer=True)
f, r = Function('f'), Function('r')


def test_rational_algorithm():
    f = 1 / ((x - 1)**2 * (x - 2))
    assert rational_algorithm(f, x, k) == \
        (-2**(-k - 1) + 1 - (factorial(k + 1) / factorial(k)), 0, 0)

    f = (1 + x + x**2 + x**3) / ((x - 1) * (x - 2))
    assert rational_algorithm(f, x, k) == \
        (-15*2**(-k - 1) + 4, x + 4, 0)

    f = z / (y * m - m * x - y * x + x**2)
    assert rational_algorithm(f, x, k) == \
        (((-y**(-k - 1)*z) / (y - m)) + ((m**(-k - 1)*z) / (y - m)), 0, 0)

    f = x / (1 - x - x**2)
    assert rational_algorithm(f, x, k) is None
    assert rational_algorithm(f, x, k, full=True) == \
        (((-Rational(1, 2) + sqrt(5)/2)**(-k - 1) *
Exemplo n.º 31
0
        ICD11 ICD22 ICD33 ICD13 IEF11 IEF22 IEF33 IEF13 IF22 g')
# Declare coordinates and their time derivatives
q, qd = N.declare_coords('q', 11)
# Declare speeds and their time derivatives
u, ud = N.declare_speeds('u', 6)
# Unpack the lists
rr, rrt, rf, rft, lr, ls, lf, l1, l2, l3, l4, mcd, mef, IC22, ICD11, ICD22,\
        ICD33, ICD13, IEF11, IEF22, IEF33, IEF13, IF22, g = params
q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11 = q
q1d, q2d, q3d, q4d, q5d, q6d, q7d, q8d, q9d, q10d, q11d = qd
u1, u2, u3, u4, u5, u6 = u
u1d, u2d, u3d, u4d, u5d, u6d = ud

tan_lean = {sin(q2)/cos(q2): tan(q2)}
# Create variables for to act as place holders in the vector from FO to FN
g31 = Function('g31')(t)
g33 = Function('g33')(t)
g31_s, g33_s = symbols('g31 g33')
g31d_s, g33d_s = symbols('g31d g33d')

"""
# Some simplifying symbols / trig expressions
s1, s2, s3, s4, s5, s6, c1, c2, c3, c4, c5, c6, t2 = symbols('s1 \
        s2 s3 s4 s5 s6 c1 c2 c3 c4 c5 c6 t2')

symbol_subs_dict = {sin(q1): s1,
                    cos(q1): c1,
                    tan(q2): t2,
                    cos(q2): c2,
                    sin(q2): s2,
                    cos(q3): c3,
Exemplo n.º 32
0
def test_free_symbols():
    from sympy import Function
    f = Function('f')
    assert mellin_transform(f(x), x, s).free_symbols == set([s])
    assert mellin_transform(f(x) * a, x, s).free_symbols == set([s, a])
Exemplo n.º 33
0
from numpy import array, arange
from sympy import symbols, Function, S, solve, simplify, \
        collect, Matrix, lambdify

from pydy import ReferenceFrame, cross, dot, dt, express, expression2vector, \
    coeff

m, g, r1, r2, t = symbols("m, g r1 r2 t")
au1, au2, au3 = symbols("au1 au2 au3")
cf1, cf2, cf3 = symbols("cf1 cf2 cf3")
I, J = symbols("I J")
u3p, u4p, u5p = symbols("u3p u4p u5p")

q1 = Function("q1")(t)
q2 = Function("q2")(t)
q3 = Function("q3")(t)
q4 = Function("q4")(t)
q5 = Function("q5")(t)

def eval(a):
    subs_dict = {
        u3.diff(t): u3p,
        u4.diff(t): u4p,
        u5.diff(t): u5p,
        r1:1,
        r2:0,
        m:1,
        g:1,
        I:1,
        J:1,
        }
Exemplo n.º 34
0
def test_laplace_transform():
    from sympy import (fresnels, fresnelc, hyper)
    LT = laplace_transform
    a, b, c, = symbols('a b c', positive=True)
    t = symbols('t')
    w = Symbol("w")
    f = Function("f")

    # Test unevaluated form
    assert laplace_transform(f(t), t, w) == LaplaceTransform(f(t), t, w)
    assert inverse_laplace_transform(f(w), w, t,
                                     plane=0) == InverseLaplaceTransform(
                                         f(w), w, t, 0)

    # test a bug
    spos = symbols('s', positive=True)
    assert LT(exp(t), t, spos)[:2] == (1 / (spos - 1), True)

    # basic tests from wikipedia

    assert LT((t - a)**b*exp(-c*(t - a))*Heaviside(t - a), t, s) == \
        ((s + c)**(-b - 1)*exp(-a*s)*gamma(b + 1), -c, True)
    assert LT(t**a, t, s) == (s**(-a - 1) * gamma(a + 1), 0, True)
    assert LT(Heaviside(t), t, s) == (1 / s, 0, True)
    assert LT(Heaviside(t - a), t, s) == (exp(-a * s) / s, 0, True)
    assert LT(1 - exp(-a * t), t, s) == (a / (s * (a + s)), 0, True)

    assert LT((exp(2*t) - 1)*exp(-b - t)*Heaviside(t)/2, t, s, noconds=True) \
        == exp(-b)/(s**2 - 1)

    assert LT(exp(t), t, s)[:2] == (1 / (s - 1), 1)
    assert LT(exp(2 * t), t, s)[:2] == (1 / (s - 2), 2)
    assert LT(exp(a * t), t, s)[:2] == (1 / (s - a), a)

    assert LT(log(t / a), t,
              s) == ((log(a * s) + EulerGamma) / s / -1, 0, True)

    assert LT(erf(t), t, s) == ((-erf(s / 2) + 1) * exp(s**2 / 4) / s, 0, True)

    assert LT(sin(a * t), t, s) == (a / (a**2 + s**2), 0, True)
    assert LT(cos(a * t), t, s) == (s / (a**2 + s**2), 0, True)
    # TODO would be nice to have these come out better
    assert LT(exp(-a * t) * sin(b * t), t,
              s) == (b / (b**2 + (a + s)**2), -a, True)
    assert LT(exp(-a*t)*cos(b*t), t, s) == \
        ((a + s)/(b**2 + (a + s)**2), -a, True)
    # TODO sinh, cosh have delicate cancellation

    assert LT(besselj(0, t), t, s) == (1 / sqrt(1 + s**2), 0, True)
    assert LT(besselj(1, t), t, s) == (1 - 1 / sqrt(1 + 1 / s**2), 0, True)
    # TODO general order works, but is a *mess*
    # TODO besseli also works, but is an even greater mess

    # test a bug in conditions processing
    # TODO the auxiliary condition should be recognised/simplified
    assert LT(exp(t) * cos(t), t, s)[:-1] in [
        ((s - 1) / (s**2 - 2 * s + 2), -oo),
        ((s - 1) / ((s - 1)**2 + 1), -oo),
    ]

    # Fresnel functions
    assert laplace_transform(fresnels(t), t, s) == \
        ((-sin(s**2/(2*pi))*fresnels(s/pi) + sin(s**2/(2*pi))/2 -
            cos(s**2/(2*pi))*fresnelc(s/pi) + cos(s**2/(2*pi))/2)/s, 0, True)
    assert laplace_transform(
        fresnelc(t), t,
        s) == ((sin(s**2 / (2 * pi)) * fresnelc(s / pi) / s -
                cos(s**2 / (2 * pi)) * fresnels(s / pi) / s +
                sqrt(2) * cos(s**2 / (2 * pi) + pi / 4) / (2 * s), 0, True))
Exemplo n.º 35
0
from sympy import Function, Symbol, symbols, Derivative, preview, simplify, collect, Wild
from sympy import diff, ln, sin, pprint, sqrt, latex, Integral
import sympy as sym

x, y, z, t = symbols('x y z t')
f = Function('f')
F = Function('F')(x, y, z)
g = Function('g', real=True)(ln(F))

result = diff(sin(x), x)

print(result)
print(f(x * x).diff(x))
print(g.diff(x))

aaa = g.diff(x, 2)
# aaa._args[1] * aaa._args[0]
# init_printing()

pprint(Integral(sqrt(1 / x), x), use_unicode=True)
print(latex(Integral(sqrt(1 / x), x)))

print("\n\n")
pprint(g.diff((x, 1), (y, 0)), use_unicode=True)
# pprint(g.diff((x, 2),(y, 2)), use_unicode=True)

pprint(sym.diff(sym.tan(x), x))
pprint(sym.diff(g, x))

print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
from sympy import Derivative as D, collect, Function
Exemplo n.º 36
0
import sympy
from sympy import Function, dsolve, Symbol

# symbols
t = Symbol('t', positive=True)
wn = Symbol('\omega_n', positive=True)
zeta = Symbol('\zeta')
f0 = Symbol('f_0', positive=True)
wf = Symbol('\omega_f', positive=True)
u0 = Symbol('u_0', constant=True)
v0 = Symbol('v_0', constant=True)

# unknown function
u = Function('u')(t)

# solving ODE
f = f0 * sympy.cos(wf * t)
ics = {
    u.subs(t, 0): u0,
    u.diff(t).subs(t, 0): v0,
}
sol = dsolve(u.diff(t, t) + 2 * zeta * wn * u.diff(t) + wn**2 * u - f, ics=ics)

# sol.lhs ==> u(t)
# sol.rhs ==> solution
print(sol.rhs.simplify())
sympy.print_latex(sol.rhs.simplify())
Exemplo n.º 37
0
var("x y")
d_u = Symbol("D_u")
d_v = Symbol("D_v")
sigma = Symbol("SIGMA")
lam = Symbol("LAMBDA")
kappa = Symbol("KAPPA")
k = Symbol("K")

def eq1(u, v, f):
    return -d_u*d_u*(u.diff(x, 2) + u.diff(y, 2)) - f(u) + sigma*v

def eq2(u, v):
    return -d_v*d_v*(v.diff(x, 2) + v.diff(y, 2)) - u + v

u = Function("u")
v = Function("v")
print "Reaction-Diffusion Equations:"
def f(u):
    return lam*u-u**3-kappa
pprint(eq1(u(x, y), v(x, y), f))
pprint(eq2(u(x, y), v(x, y)))

print "\nSolution:"
u_hat = 1 - (exp(k*x)+exp(-k*x)) / (exp(k)+exp(-k))
pprint(Eq(Function("u_hat")(x), u_hat))

#test the Boundary Conditions:
assert u_hat.subs(x, -1) == 0
assert u_hat.subs(x, 1) == 0
Exemplo n.º 38
0
    def test_numerification(self):
        # apply a function defined with units

        def v_unit(t):
            # Note:
            # At the moment t has to be a scalar
            cond_1 = simplify(t) == 0
            cond_2 = dimsys_SI.equivalent_dims(SI.get_dimensional_expr(t),
                                               time)
            assert cond_1 | cond_2
            omega = 2 * pi / second
            # phi = 0
            phi = pi / 8
            V_0 = 20 * meter / second
            V_range = 5 * meter / second
            return V_0 + V_range * sin(omega * t + phi)

        # Note

        ts = [second * t for t in np.linspace(0, float(2 * pi), 100)]
        ysf = [v_unit(t) for t in ts]

        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        auto_plot_with_units(ax, ts, ysf)
        fig.savefig("example3_auto.pdf")
        t = Quantity("t")
        SI.set_quantity_dimension(t, time)

        # We can transform Expressions to numerical functions
        # This also works for Expressions of Quanteties and functions that
        # contain units

        v = Function("v")
        m = Quantity("m")
        # create an expression containing a function
        E = m / 2 * v(t)**2

        # print(v_unit(3*day))

        # substitute paramters
        E_parUnit = E.subs({m: 5 * kilogram})

        # lambify the expression to a function
        tup = (t, )
        E_funcUnit = lambdify(tup, E_parUnit, {"v": v_unit})

        # ysE = [E_funcUnit(t) for t in ts]
        #
        # fig = plt.figure()
        # ax = fig.add_subplot(1, 1, 1)
        # auto_plot_with_units(ax, ts, ysE)
        # fig.savefig("example4_auto.pdf")

        # ####################################################################################################
        #
        # Exampe 5
        # Here we assume that parameters, arguments and return values of functions
        # have units attached.
        # This is natural from sympys perspective and allows computations involving
        # quanteties ( numbers with units ) to be completely transparent.
        # E.g. a function or expression receiving a
        # length argument  will always compute the correct result since the argument
        # carries its unit with it. Also the result can be expressed in any unit
        # compatible with its dimension.
        #
        # However numerical computations in scipy like solving an ode require numbers
        # or functions that consume and return numbers (as opposed to quanteties)
        # To perform those computations we temporarily have to remove units from the
        # arguments before the computation and attach units to the results.
        # We can automatically convert 'numerify' a function working on quanteties
        # (f_quant) to  a function on number (f_num) if we choose the units for
        # arguments and return values.
        # The resulting purely numerical function f_num represents
        # f_quant faithfully for those units and for those units only.
        # This has several consequences:
        # - Along with f_num the untis of the arguments and the return value have to
        #   be remembered externally since they are no intrinsic part of f_num.
        # - The numerical representations of different functions and paramters
        #   should be consistent. E.g in f_quant(g_quant(x_qunat)) x_qant,f_quant
        #   and g_quant should be "numerified" making sure that x_num represents
        #   the original quantity with respect to the unit that f_num expects and
        #   that f_num returns its result w.r.t. the unit g_num expects...
        #   This is possible with the help of the unit system.
        # - Unfortunately the "numerification" of functions is computationally
        #   expensive as the numeric function f_num everytime it is called it will
        #   attach units call f_quant and remove units from the result.

        def numerify(f_quant, *units):
            def f_num(*num_args):
                target_unit = units[-1]
                u_args = tuple(num_arg * units[ind]
                               for ind, num_arg in enumerate(num_args))
                res_quant = f_quant(*u_args)
                # res_quant_target_unit = convert_to(res_quant, target_unit)
                # res_num = factor(res_quant_target_unit, target_unit)/target_unit
                res_num = simplify(res_quant / target_unit)
                return float(res_num)

            return f_num

        C_0 = describedQuantity("C_0", mass, "")
        C_1 = describedQuantity("C_1", mass, "")
        t = describedQuantity("t", time, "")
        k_01 = describedQuantity("k_01", 1 / time, "")
        k_10 = describedQuantity("k_10", 1 / time, "")
        k_0o = describedQuantity("k_0o", 1 / time, "")

        k_1o = Function("k_1o")

        state_variables = [C_0, C_1]  # order is important
        inputs = {
            0: sin(t) + 2,
            1: cos(t) + 2
        }  # input to pool 0  # input to pool 1
        outputs = {
            0: k_0o * C_0**3,  # output from pool 0
            1: k_1o(t) * C_1**3,  # output from pool 0
        }
        internal_fluxes = {
            (0, 1): k_01 * C_0 * C_1**2,  # flux from pool 0  to pool 1
            (1, 0): k_10 * C_0 * C_1,  # flux from pool 1 to pool 0
        }
        time_symbol = t
        srm = SmoothReservoirModel(state_variables, time_symbol, inputs,
                                   outputs, internal_fluxes)

        par_dict_quant = {
            k_01: 1 / 100 * 1 / day,
            k_10: 1 / 100 * 1 / day,
            k_0o: 1 / 2 * 1 / day,
        }

        def k_1o_func_quant(t):
            omega = 2 * pi / day
            phi = pi / 8
            V_0 = 20 * kilogram / day
            V_range = 5 * kilogram / day
            u_res = V_0 + V_range * sin(omega * t + phi)
            return u_res

        times_quant = np.linspace(0, 20, 16) * year
        start_values_quant = np.array([1 * gram, 2 * kilogram])

        # Note that the time units of the parameters the function and the time array
        # are different.  Also note that the components of the startvalue tuple are
        # given with respect to two different units (gigagram and kilogram)  and the
        # k_1o_func_quant uses kilogram/second as the unit for the return value.
        #
        # The different units are handled correctly by sympy, becuase the same quantety
        # can be represented with respect to differnt units (1*day=24*hour)
        #
        # If we convert ot purely numerical values and functions, we have to consider
        # the consistency of the whole ensemble The easiest way to achieve this is to
        # normalize all times to an arbitrary but common unit of time (e.g. year), and
        # all masses to an arbitrary unit of mass (e.g. kilogram)

        # create a numerical function expecting its argument to be a number measuring
        # years and returning a number to be interpreted as kilogram/year
        k_1o_func_num = numerify(k_1o_func_quant, year, kilogram / year)

        # create a par_dict of numbers (since all parameter in the dictionary are rates
        # we can deal with the whole dict at once
        par_dict_num = {
            k: to_number(v, 1 / year)
            for k, v in par_dict_quant.items()
        }

        # extract the times in years
        times_num = np.array([to_number(t, year) for t in times_quant])

        # crete numerical start values
        start_values_num = np.array(
            [to_number(v, kilogram) for v in start_values_quant])
        n_smr = SmoothModelRun(
            srm,
            par_dict_num,
            start_values_num,
            times_num,
            func_set={k_1o: k_1o_func_num},
        )
        before = tm.time()
        sol_num = n_smr.solve()  # extremely slow
        after = tm.time()
        print(before - after)

        def k_1o_func_num_manual(t):
            omega = 2 * pi
            phi = pi / 8
            V_0 = 20
            V_range = 5
            u_res = V_0 + V_range * sin(omega * t + phi)
            return u_res

        n_smr = SmoothModelRun(
            srm,
            par_dict_num,
            start_values_num,
            times_num,
            func_set={k_1o: k_1o_func_num_manual},
        )
        before = tm.time()
        sol_num = n_smr.solve()
        after = tm.time()
        print(before - after)
Exemplo n.º 39
0
def test_equality_subs1():
    f = Function("f")
    x = abc.x
    eq = Eq(f(x)**2, x)
    res = Eq(Integer(16), x)
    assert eq.subs(f(x), 4) == res
Exemplo n.º 40
0
def test_equality_subs2():
    f = Function("f")
    x = abc.x
    eq = Eq(f(x)**2, 16)
    assert bool(eq.subs(f(x), 3)) == False
    assert bool(eq.subs(f(x), 4)) == True
Exemplo n.º 41
0
def test_cylinder_clpt():
    '''Test case where the functional corresponds to the internal energy of
    a cylinder using the Classical Laminated Plate Theory (CLPT)

    '''
    from sympy import Matrix

    sympy.var('x, y, r')
    sympy.var('B11, B12, B16, B21, B22, B26, B61, B62, B66')
    sympy.var('D11, D12, D16, D21, D22, D26, D61, D62, D66')

    # displacement field
    u = Function('u')(x, y)
    v = Function('v')(x, y)
    w = Function('w')(x, y)
    # stress function
    f = Function('f')(x, y)
    # laminate constitute matrices B represents B*, see Jones (1999)
    B = Matrix([[B11, B12, B16],
                [B21, B22, B26],
                [B61, B62, B66]])
    # D represents D*, see Jones (1999)
    D = Matrix([[D11, D12, D16],
                [D12, D22, D26],
                [D16, D26, D66]])
    # strain-diplacement equations
    e = Matrix([[u.diff(x) + 1./2*w.diff(x)**2],
                [v.diff(y) + 1./r*w + 1./2*w.diff(y)**2],
                [u.diff(y) + v.diff(x) + w.diff(x)*w.diff(y)]])
    k = Matrix([[  -w.diff(x, x)],
                [  -w.diff(y, y)],
                [-2*w.diff(x, y)]])
    # representing the internal forces using the stress function
    N = Matrix([[  f.diff(y, y)],
                [  f.diff(x, x)],
                [ -f.diff(x, y)]])
    functional = N.T*V(e) - N.T*B*V(k) + k.T*D.T*V(k)
    return Vexpr(functional, u, v, w)
Exemplo n.º 42
0
# existance theorem
import sympy

from sympy.abc import t
from sympy import Function, Derivative, dsolve, Eq, solve

y = Function('y')

formula = 1 + y(t)**2

solutions = dsolve(Eq(Derivative(y(t), t), formula))

print solutions

solution = solutions.args[1].subs(
    'C1',
    solve(Eq(solutions.args[1].subs(t, 0), 0))[0])

#  uniqueness of solution

tdomain = np.linspace(-7, 7, 30)

formula = sympy.root(y(t), 3) * sympy.sin(2 * t)

solution1 = 0
solution2 = (8.0 / 27)**0.5 * (sympy.sin(t))**3
solution3 = -1 * (8.0 / 27)**0.5 * (sympy.sin(t))**3

plt.plot(tdomain, [0 for i in tdomain], 'blue', \
         tdomain, np.array([solution2.subs(t, tval) for tval in tdomain]), 'black',\
         tdomain, np.array([solution3.subs(t, tval) for tval in tdomain]), 'red')
Exemplo n.º 43
0
from sympy import cos, DiracDelta, Heaviside, Function, pi, S, sin, symbols, Rational
from sympy.integrals.deltafunctions import change_mul, deltaintegrate

f = Function("f")
x_1, x_2, x, y, z = symbols("x_1 x_2 x y z")


def test_change_mul():
    assert change_mul(x, x) == (None, None)
    assert change_mul(x * y, x) == (None, None)
    assert change_mul(x * y * DiracDelta(x), x) == (DiracDelta(x), x * y)
    assert change_mul(x * y * DiracDelta(x) * DiracDelta(y), x) == (
        DiracDelta(x),
        x * y * DiracDelta(y),
    )
    assert change_mul(DiracDelta(x)**2, x) == (DiracDelta(x), DiracDelta(x))
    assert change_mul(y * DiracDelta(x)**2,
                      x) == (DiracDelta(x), y * DiracDelta(x))


def test_deltaintegrate():
    assert deltaintegrate(x, x) is None
    assert deltaintegrate(x + DiracDelta(x), x) is None
    assert deltaintegrate(DiracDelta(x, 0), x) == Heaviside(x)
    for n in range(10):
        assert deltaintegrate(DiracDelta(x, n + 1), x) == DiracDelta(x, n)
    assert deltaintegrate(DiracDelta(x), x) == Heaviside(x)
    assert deltaintegrate(DiracDelta(-x), x) == Heaviside(x)
    assert deltaintegrate(DiracDelta(x - y), x) == Heaviside(x - y)
    assert deltaintegrate(DiracDelta(y - x), x) == Heaviside(x - y)
Exemplo n.º 44
0
def test_issue_17811():
    a = Function('a')
    assert sympify('a(x)*5', evaluate=False) == Mul(a(x), 5, evaluate=False)
Exemplo n.º 45
0
def _test_f():
    # FIXME: we get infinite recursion here:
    f = Function("f")
    assert residue(f(x)/x**5, x, 0) == f.diff(x, 4)/24
Exemplo n.º 46
0
def test_coeff2():
    var('r, kappa')
    psi = Function("psi")
    g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
    assert g.coeff(psi(r).diff(r)) == 2/r
Exemplo n.º 47
0
from sympy import Rational, sqrt, symbols, sin, exp, log, sinh, cosh, cos, pi, \
    I, erf, tan, asin, asinh, acos, Function, Derivative, diff, simplify, \
    LambertW, Eq, Piecewise, Symbol, Add, ratsimp, Integral, Sum
from sympy.integrals.heurisch import components, heurisch, heurisch_wrapper
from sympy.utilities.pytest import XFAIL, skip, slow, ON_TRAVIS

x, y, z, nu = symbols('x,y,z,nu')
f = Function('f')


def test_components():
    assert components(x * y, x) == set([x])
    assert components(1 / (x + y), x) == set([x])
    assert components(sin(x), x) == set([sin(x), x])
    assert components(sin(x)*sqrt(log(x)), x) == \
        set([log(x), sin(x), sqrt(log(x)), x])
    assert components(x*sin(exp(x)*y), x) == \
        set([sin(y*exp(x)), x, exp(x)])
    assert components(x**Rational(17, 54)/sqrt(sin(x)), x) == \
        set([sin(x), x**Rational(1, 54), sqrt(sin(x)), x])

    assert components(f(x), x) == \
        set([x, f(x)])
    assert components(Derivative(f(x), x), x) == \
        set([x, f(x), Derivative(f(x), x)])
    assert components(f(x)*diff(f(x), x), x) == \
        set([x, f(x), Derivative(f(x), x), Derivative(f(x), x)])


def test_heurisch_polynomials():
    assert heurisch(1, x) == x
Exemplo n.º 48
0
import sympy
from sympy import Function, dsolve, Symbol

# symbols
t = Symbol('t', positive=True)
wf = Symbol('wf', positive=True)

# unknown function
u = Function('u')(t)

# solving ODE with initial conditions
u0 = 0.4
v0 = 2
k = 150
m = 2
F0 = 10
wn = sympy.sqrt(k/m)
#wf = 2*sympy.sqrt(k/m)
F = F0*sympy.sin(wf*t)
ics = {u.subs(t, 0): u0, u.diff(t).subs(t, 0): v0}

sol = dsolve(m*u.diff(t, t) + k*u - F, ics=ics)

import matplotlib
matplotlib.use('TkAgg')
from sympy.plotting import plot3d
p1 = plot3d(sol.rhs, (t, 0, 10), (wf, 0.8*wn, 0.99*wn),
        xlabel='$t$', ylabel='$\omega_f$', zlabel='$u(t)$',
        nb_of_points_x=250, nb_of_points_y=25)