Пример #1
0
    def ode_is_lin_const_coeff(ode_symbol, ode_definition, shapes):
        """
        TODO: improve the original code: the function should take a list of shape names, not objects
        :param ode_symbol string encoding the LHS
        :param ode_definition string encoding RHS
        :param shapes A list with shape names
        :return true iff the ode definition is a linear and constant coefficient ODE
        """

        ode_symbol_sp = parse_expr(ode_symbol)
        ode_definition_sp = parse_expr(ode_definition)

        # Check linearity
        ddvar = diff(diff(ode_definition_sp, ode_symbol_sp), ode_symbol_sp)

        if simplify(ddvar) != 0:
            return False

        # Check coefficients
        dvar = diff(ode_definition_sp, ode_symbol_sp)

        for shape in shapes:
            for symbol in dvar.free_symbols:
                if shape == str(symbol):
                    return False
        return True
Пример #2
0
def get_source_cmb_cl(params, CMB_unit='muK'):
    r"""
    Get the angular power spectrum of emission angle and time delay sources :math:`\psi_t`, :math:`\psi_\zeta`,
    as well as the perpendicular velocity and E polarization.
    All are returned with 1 and 2 versions, for recombination and reionization respectively.
    Note that this function destroys any custom sources currently configured.

    :param params: :class:`.model.CAMBparams` instance with cosmological parameters etc.
    :param CMB_unit: scale results from dimensionless, use 'muK' for :math:`\mu K^2` units
    :return: dictionary of power spectra, with :math:`L(L+1)/2\pi` factors.
    """

    import sympy
    from sympy import diff
    from . import symbolic as cs

    assert (np.isclose(params.omk, 0))

    angdist = cs.tau0 - cs.t
    emission_sources = {
        'vperp': -(cs.sigma + cs.v_b) * cs.visibility / cs.k / angdist,
        'emit': 15 * diff(cs.polter * cs.visibility, cs.t) / 8 / cs.k ** 2 / angdist,
        'delay': 15 * diff(cs.polter * cs.visibility, cs.t) / 8 / cs.k ** 2 / angdist ** 2 * (cs.tau0 - cs.tau_maxvis),
        'E': cs.scalar_E_source}

    sources = {}
    for key, source in list(emission_sources.items()):
        sources[key + '1'] = sympy.Piecewise((source, 1 / cs.a - 1 > 30), (0, True))  # recombination
        sources[key + '2'] = sympy.Piecewise((source, 1 / cs.a - 1 <= 30), (0, True))  # reionization

    params.set_custom_scalar_sources(sources, source_ell_scales={'E1': 2, 'E2': 2})
    return camb.get_results(params).get_cmb_unlensed_scalar_array_dict(CMB_unit=CMB_unit)
Пример #3
0
def lhs_eq(t, m, b, s, u, damping='linear'):
    """Return lhs of differential equation as sympy expression."""
    v = sm.diff(u, t)
    if damping == 'linear':
        return m*sm.diff(u, t, t) + b*v + s(u)
    else:
        return m*sm.diff(u, t, t) + b*v*sm.Abs(v) + s(u)
Пример #4
0
    def __init__(self, nddistr=None, d=None):
        super(TwoVarsModel, self).__init__(nddistr, [d])
        self.eliminate_other([d])
        self.d = d
        self.vars = []
        self.symvars = []
        for var in nddistr.Vars: #self.free_rvs:
            self.vars.append(var)
            self.symvars.append(var.getSymname())
        #print "=====", self.vars
        #print self.symvars
        #print self.dep_rvs
        #print self.rv_to_equation
        self.symop = self.rv_to_equation[d]

        if len(self.vars) != 2:
            raise Exception("use it with two variables")
        x = self.symvars[0]
        y = self.symvars[1]
        z = sympy.Symbol("z")
        self.fun_alongx = eq_solve(self.symop, z, y)[0]
        self.fun_alongy = eq_solve(self.symop, z, x)[0]

        self.lfun_alongx = my_lambdify([x, z], self.fun_alongx, "numpy")
        self.lfun_alongy = my_lambdify([y, z], self.fun_alongy, "numpy")
        self.Jx = 1 * sympy.diff(self.fun_alongx, z)
        #print "Jx=", self.Jx
        #print "fun_alongx=", self.fun_alongx
        self.Jy = 1 * sympy.diff(self.fun_alongy, z)
        self.lJx = my_lambdify([x, z], self.Jx, "numpy")
        self.lJy = my_lambdify([y, z], self.Jy, "numpy")
        self.z = z
Пример #5
0
def Simple_manifold_with_scalar_function_derivative():
    Print_Function()
    coords = (x,y,z) = symbols('x y z')
    basis = (e1, e2, e3, grad) = MV.setup('e_1 e_2 e_3',metric='[1,1,1]',coords=coords)
    # Define surface
    mfvar = (u,v) = symbols('u v')
    X = u*e1+v*e2+(u**2+v**2)*e3
    print '\\f{X}{u,v} =',X
    MF = Manifold(X,mfvar)
    (eu,ev) = MF.Basis()
    # Define field on the surface.
    g = (v+1)*log(u)

    print '\\f{g}{u,v} =',g

    # Method 1: Using old Manifold routines.
    VectorDerivative = (MF.rbasis[0]/MF.E_sq)*diff(g,u) + (MF.rbasis[1]/MF.E_sq)*diff(g,v)
    print '\\eval{\\nabla g}{u=1,v=0} =', VectorDerivative.subs({u:1,v:0})

    # Method 2: Using new Manifold routines.
    dg = MF.Grad(g)
    print '\\eval{\\f{Grad}{g}}{u=1,v=0} =', dg.subs({u:1,v:0})
    dg = MF.grad*g
    print '\\eval{\\nabla g}{u=1,v=0} =', dg.subs({u:1,v:0})
    return
Пример #6
0
def test_order_could_be_zero():
    x, y = symbols('x, y')
    n = symbols('n', integer=True, nonnegative=True)
    m = symbols('m', integer=True, positive=True)
    assert diff(y, (x, n)) == Piecewise((y, Eq(n, 0)), (0, True))
    assert diff(y, (x, n + 1)) == S.Zero
    assert diff(y, (x, m)) == S.Zero
Пример #7
0
def test_atan2():
    assert atan2(0, 0) == S.NaN
    assert atan2(0, 1) == 0
    assert atan2(1, 1) == pi/4
    assert atan2(1, 0) == pi/2
    assert atan2(1, -1) == 3*pi/4
    assert atan2(0, -1) == pi
    assert atan2(-1, -1) == -3*pi/4
    assert atan2(-1, 0) == -pi/2
    assert atan2(-1, 1) == -pi/4

    u = Symbol("u", positive=True)
    assert atan2(0, u) == 0
    u = Symbol("u", negative=True)
    assert atan2(0, u) == pi

    assert atan2(y, oo) ==  0
    assert atan2(y, -oo)==  2*pi*Heaviside(re(y)) - pi

    assert atan2(y, x).rewrite(log) == -I*log((x + I*y)/sqrt(x**2 + y**2))
    assert atan2(y, x).rewrite(atan) == 2*atan(y/(x + sqrt(x**2 + y**2)))

    assert diff(atan2(y, x), x) == -y/(x**2 + y**2)
    assert diff(atan2(y, x), y) == x/(x**2 + y**2)

    assert simplify(diff(atan2(y, x).rewrite(log), x)) == -y/(x**2 + y**2)
    assert simplify(diff(atan2(y, x).rewrite(log), y)) ==  x/(x**2 + y**2)

    assert isinstance(atan2(2, 3*I).n(), atan2)
Пример #8
0
def test_derivative_appellf1():
    from sympy import diff
    a, b1, b2, c, x, y, z = symbols('a b1 b2 c x y z')
    assert diff(appellf1(a, b1, b2, c, x, y), x) == a*b1*appellf1(a + 1, b2, b1 + 1, c + 1, y, x)/c
    assert diff(appellf1(a, b1, b2, c, x, y), y) == a*b2*appellf1(a + 1, b1, b2 + 1, c + 1, x, y)/c
    assert diff(appellf1(a, b1, b2, c, x, y), z) == 0
    assert diff(appellf1(a, b1, b2, c, x, y), a) ==  Derivative(appellf1(a, b1, b2, c, x, y), a)
Пример #9
0
def test_derivative_evaluate():
    assert Derivative(sin(x), x) != diff(sin(x), x)
    assert Derivative(sin(x), x).doit() == diff(sin(x), x)

    assert Derivative(Derivative(f(x), x), x) == diff(f(x), x, x)
    assert Derivative(sin(x), x, 0) == sin(x)
    assert Derivative(sin(x), (x, y), (x, -y)) == sin(x)
Пример #10
0
    def __init__(self):
        self.num_lines, self.num_marks = 5, 2
        self._qp = {}

        function_types = ['product', 'quotient', 'composite']
        function_type = random.choice(function_types)

        if function_type == 'product':
            # 2008 1b: y = x * e**(3x), a = 0
            # 2011 1b: y = x**2 * sin(2x), a = pi / 6
            self.create_product_differentiation()

        elif function_type == 'quotient':
            # 2009 1b: y = cos(x) / (2x + 2), a = pi
            # 2012 1b: y = x / sin(x), a = pi / 2
            self.create_quotient_differentiation()

        elif function_type == 'composite':
            # I thought of including sin and cos, but I can't remember ever seeing a question where a quadratic was nested inside
            # of a trig function
            self.create_composite_differentiation()

        if function_type == 'quotient':
            # quotients are always written as one big fraction, but sympy always separates them into multiple fractions, so we have to factorise
            self._qp['derivative'] = sympy.diff(self._qp['equation']).together()
        else:
            self._qp['derivative'] = sympy.diff(self._qp['equation'])

        self._qp['answer'] = self._qp['derivative'].subs({x: self._qp['x_value']})
Пример #11
0
    def __init__(self):
        self.num_lines, self.num_marks = 5, 2
        self._qp = {}

        function_type = random.choice(['sqrt', 'quadratic', 'product'])

        if function_type == 'sqrt':
            outer_function = all_functions.request_linear(difficulty=2).equation
            inner_function = all_functions.request_linear(difficulty=1).equation
            inner_function = inner_function.replace(lambda expr: expr.is_Symbol, lambda expr: sympy.sqrt(expr))

            self._qp['equation'] = outer_function.replace(x, inner_function)
            self._qp['derivative'] = sympy.diff(self._qp['equation'])

        elif function_type == 'quadratic':
            power_two_coeff = not_named_yet.randint_no_zero(-3, 3)
            power_one_coeff = not_named_yet.randint_no_zero(-5, 5)
            inner_function = power_two_coeff * x ** 2 + power_one_coeff * x
            index = random.randint(3, 5)

            self._qp['equation'] = inner_function ** index
            self._qp['derivative'] = sympy.diff(self._qp['equation'])

        elif function_type == 'product':
            left_function = x ** random.randint(1, 3)
            right_outer_function = random.choice([sympy.sin, sympy.cos, sympy.log, sympy.exp])
            right_inner_function = not_named_yet.randint_no_zero(-3, 3) * x

            self._qp['equation'] = left_function * right_outer_function(right_inner_function)
            self._qp['derivative'] = sympy.diff(self._qp['equation'])
Пример #12
0
def case0(f, N=3):
    B = 1 - x ** 3
    dBdx = sm.diff(B, x)

    # Compute basis functions and their derivatives
    phi = {0: [x ** (i + 1) * (1 - x) for i in range(N + 1)]}
    phi[1] = [sm.diff(phi_i, x) for phi_i in phi[0]]

    def integrand_lhs(phi, i, j):
        return phi[1][i] * phi[1][j]

    def integrand_rhs(phi, i):
        return f * phi[0][i] - dBdx * phi[1][i]

    Omega = [0, 1]

    u_bar = solve(integrand_lhs, integrand_rhs, phi, Omega, verbose=True, numint=False)
    u = B + u_bar
    print "solution u:", sm.simplify(sm.expand(u))

    # Calculate analytical solution

    # Solve -u''=f by integrating f twice
    f1 = sm.integrate(f, x)
    f2 = sm.integrate(f1, x)
    # Add integration constants
    C1, C2 = sm.symbols("C1 C2")
    u_e = -f2 + C1 * x + C2
    # Find C1 and C2 from the boundary conditions u(0)=0, u(1)=1
    s = sm.solve([u_e.subs(x, 0) - 1, u_e.subs(x, 1) - 0], [C1, C2])
    # Form the exact solution
    u_e = -f2 + s[C1] * x + s[C2]
    print "analytical solution:", u_e
    # print 'error:', u - u_e  # many terms - which cancel
    print "error:", sm.expand(u - u_e)
def test_gegenbauer():
    n = Symbol("n")
    a = Symbol("a")

    assert gegenbauer(0, a, x) == 1
    assert gegenbauer(1, a, x) == 2*a*x
    assert gegenbauer(2, a, x) == -a + x**2*(2*a**2 + 2*a)
    assert gegenbauer(3, a, x) == \
        x**3*(4*a**3/3 + 4*a**2 + 8*a/3) + x*(-2*a**2 - 2*a)

    assert gegenbauer(-1, a, x) == 0
    assert gegenbauer(n, S(1)/2, x) == legendre(n, x)
    assert gegenbauer(n, 1, x) == chebyshevu(n, x)
    assert gegenbauer(n, -1, x) == 0

    X = gegenbauer(n, a, x)
    assert isinstance(X, gegenbauer)

    assert gegenbauer(n, a, -x) == (-1)**n*gegenbauer(n, a, x)
    assert gegenbauer(n, a, 0) == 2**n*sqrt(pi) * \
        gamma(a + n/2)/(gamma(a)*gamma(-n/2 + S(1)/2)*gamma(n + 1))
    assert gegenbauer(n, a, 1) == gamma(2*a + n)/(gamma(2*a)*gamma(n + 1))

    assert gegenbauer(n, Rational(3, 4), -1) == zoo

    m = Symbol("m", positive=True)
    assert gegenbauer(m, a, oo) == oo*RisingFactorial(a, m)

    assert conjugate(gegenbauer(n, a, x)) == gegenbauer(n, conjugate(a), conjugate(x))

    assert diff(gegenbauer(n, a, x), n) == Derivative(gegenbauer(n, a, x), n)
    assert diff(gegenbauer(n, a, x), x) == 2*a*gegenbauer(n - 1, a + 1, x)
Пример #14
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)
Пример #15
0
 def grad(self, func):
     """
     Calculate the gradient of 'func'.
     """
     return Matrix([diff(func, self.xs[0]) / self.h[0], \
                    diff(func, self.xs[1]) / self.h[1], \
                    diff(func, self.xs[2]) / self.h[2]])
def test_Ynm():
    # http://en.wikipedia.org/wiki/Spherical_harmonics
    th, ph = Symbol("theta", real=True), Symbol("phi", real=True)
    from sympy.abc import n, m

    assert Ynm(0, 0, th, ph).expand(func=True) == 1 / (2 * sqrt(pi))
    assert Ynm(1, -1, th, ph) == -exp(-2 * I * ph) * Ynm(1, 1, th, ph)
    assert Ynm(1, -1, th, ph).expand(func=True) == sqrt(6) * sin(th) * exp(-I * ph) / (4 * sqrt(pi))
    assert Ynm(1, -1, th, ph).expand(func=True) == sqrt(6) * sin(th) * exp(-I * ph) / (4 * sqrt(pi))
    assert Ynm(1, 0, th, ph).expand(func=True) == sqrt(3) * cos(th) / (2 * sqrt(pi))
    assert Ynm(1, 1, th, ph).expand(func=True) == -sqrt(6) * sin(th) * exp(I * ph) / (4 * sqrt(pi))
    assert Ynm(2, 0, th, ph).expand(func=True) == 3 * sqrt(5) * cos(th) ** 2 / (4 * sqrt(pi)) - sqrt(5) / (4 * sqrt(pi))
    assert Ynm(2, 1, th, ph).expand(func=True) == -sqrt(30) * sin(th) * exp(I * ph) * cos(th) / (4 * sqrt(pi))
    assert Ynm(2, -2, th, ph).expand(func=True) == (
        -sqrt(30) * exp(-2 * I * ph) * cos(th) ** 2 / (8 * sqrt(pi)) + sqrt(30) * exp(-2 * I * ph) / (8 * sqrt(pi))
    )
    assert Ynm(2, 2, th, ph).expand(func=True) == (
        -sqrt(30) * exp(2 * I * ph) * cos(th) ** 2 / (8 * sqrt(pi)) + sqrt(30) * exp(2 * I * ph) / (8 * sqrt(pi))
    )

    assert diff(Ynm(n, m, th, ph), th) == (
        m * cot(th) * Ynm(n, m, th, ph) + sqrt((-m + n) * (m + n + 1)) * exp(-I * ph) * Ynm(n, m + 1, th, ph)
    )
    assert diff(Ynm(n, m, th, ph), ph) == I * m * Ynm(n, m, th, ph)

    assert conjugate(Ynm(n, m, th, ph)) == (-1) ** (2 * m) * exp(-2 * I * m * ph) * Ynm(n, m, th, ph)

    assert Ynm(n, m, -th, ph) == Ynm(n, m, th, ph)
    assert Ynm(n, m, th, -ph) == exp(-2 * I * m * ph) * Ynm(n, m, th, ph)
    assert Ynm(n, -m, th, ph) == (-1) ** m * exp(-2 * I * m * ph) * Ynm(n, m, th, ph)
Пример #17
0
    def __call__(self, scalar_field):
        """
        Represents the gradient of the given scalar field.

        Parameters
        ==========

        scalar_field : SymPy expression
            The scalar field to calculate the gradient of.

        Examples
        ========

        >>> from sympy.vector import CoordSysCartesian
        >>> C = CoordSysCartesian('C')
        >>> C.delop(C.x*C.y*C.z)
        C.y*C.z*C.i + C.x*C.z*C.j + C.x*C.y*C.k

        """

        scalar_field = express(scalar_field, self.system,
                               variables = True)
        vx = diff(scalar_field, self._x)
        vy = diff(scalar_field, self._y)
        vz = diff(scalar_field, self._z)

        return vx*self._i + vy*self._j + vz*self._k
Пример #18
0
def boundary_layer1D():
    import sympy as sym

    x, Pe = sym.symbols("x Pe")

    def u(x, Pe, module):
        return (1 - module.exp(x * Pe)) / (1 - module.exp(Pe))

    u_formula = u(x, Pe, sym)
    ux_formula = sym.diff(u_formula, x)
    uxx_formula = sym.diff(ux_formula, x)
    print ux_formula, uxx_formula
    print "u_x:", sym.simplify(ux_formula.subs(x, 1))
    print sym.simplify(ux_formula.subs(x, 1)).series(Pe, 0, 3)
    print "u_xx:", sym.simplify(uxx_formula.subs(x, 1))
    print sym.simplify(uxx_formula.subs(x, 1)).series(Pe, 0, 3)

    import matplotlib.pyplot as plt
    import numpy as np

    x = np.linspace(0, 1, 10001)
    Pe = 1
    u_num1 = u(x, Pe, np)
    Pe = 50
    u_num2 = u(x, Pe, np)
    plt.plot(x, u_num1, x, u_num2)
    plt.legend(["Pe=1", "Pe=50"], loc="upper left")
    plt.savefig("tmp.png")
    plt.savefig("tmp.pdf")
    plt.axis([0, 1, -0.1, 1])
    plt.show()
Пример #19
0
def boundary_layer1D_scale2():
    import sympy as sym

    x, Pe = sym.symbols("x Pe")

    def u(x, Pe, module):
        return (1 - module.exp(x)) / (1 - module.exp(Pe))

    u_formula = u(x, Pe, sym)
    ux_formula = sym.diff(u_formula, x)
    uxx_formula = sym.diff(ux_formula, x)
    print ux_formula, uxx_formula
    print "u_x:", sym.simplify(ux_formula.subs(x, Pe))
    print sym.simplify(ux_formula).series(Pe, 0, 3)
    print "u_xx:", sym.simplify(uxx_formula.subs(x, Pe))
    print sym.simplify(uxx_formula).series(Pe, 0, 3)

    import matplotlib.pyplot as plt
    import numpy as np

    Pe_values = [1, 10, 25, 50]
    for Pe in Pe_values:
        x = np.linspace(0, Pe, 10001)
        u_num = u(x, Pe, np)
        plt.plot(x, u_num)
    plt.legend(["Pe=%d" % Pe for Pe in Pe_values], loc="lower left")
    plt.savefig("tmp.png")
    plt.savefig("tmp.pdf")
    plt.axis([0, max(Pe_values), -0.4, 1])
    plt.show()
def update_parameter_data(cx_str, cy_str, t):
    # string parsing
    cx_fun, cx_sym = my_bokeh_utils.string_to_function_parser(cx_str, ['t'])
    cy_fun, cy_sym = my_bokeh_utils.string_to_function_parser(cy_str, ['t'])

    from sympy import diff

    dcx_sym = diff(cx_sym, 't')
    dcy_sym = diff(cy_sym, 't')

    dcx_fun = my_bokeh_utils.sym_to_function_parser(dcx_sym, 't')
    dcy_fun = my_bokeh_utils.sym_to_function_parser(dcy_sym, 't')

    # crating sample
    x_val = cx_fun(t)
    y_val = cy_fun(t)

    dx_val = dcx_fun(t)
    dy_val = dcy_fun(t)
    xx, hx = np.linspace(source_view.data['x_start'][0], source_view.data['x_end'][0], curveintegral_settings.n_sample,
                         retstep=True)
    ssdict, spdict, _ = my_bokeh_utils.quiver_to_data(x=np.array(x_val), y=np.array(y_val), u=np.array(dx_val), v=np.array(dy_val), h=2*hx,
                                                           do_normalization=True, fix_at_middle=False)

    # save data
    source_param.data = dict(x=[x_val], y=[y_val], t=[t], x0=ssdict['x0'], y0=ssdict['y0'],
                             x1=ssdict['x1'], y1=ssdict['y1'], xs=spdict['xs'], ys=spdict['ys'])

    print "curve point was updated with t=%f" % (t)
Пример #21
0
def _extract_linear_components(expr, dvars):
    # TODO replace by helpers.extract_linear_components?
    # Those are the variables in the expression, inserted by the edge
    # discretizer.
    assert is_affine_linear(expr, dvars)

    # Get the coefficients of u0, u1.
    coeff00 = sympy.diff(expr, dvars[0])
    coeff01 = sympy.diff(expr, dvars[1])

    x0 = sympy.Symbol('x0')
    x1 = sympy.Symbol('x1')
    # Now construct the coefficients for the other way around.
    coeff10 = coeff01
    coeff10 = _swap(coeff10, dvars[0], dvars[1])
    coeff10 = _swap(coeff10, x0, x1)
    coeff11 = coeff00
    coeff11 = _swap(coeff11, dvars[0], dvars[1])
    coeff11 = _swap(coeff11, x0, x1)

    affine = expr.subs([(dvars[0], 0), (dvars[1], 0)])

    return (
        [[coeff00, coeff01], [coeff10, coeff11]],
        [affine, affine]
        )
Пример #22
0
def differentiate(C,a, b):
    diff1 = [0]*N
    diff1_anal = [0]*N
    diff2 = [0]*N
    diff2_anal = [0]*N
    i = arange(N)
    # Chebyshev nodes on [-1,1]
    x = -cos(pi*(2.0*i + 1.0)/(2.0*(N-1) + 2.0)) 

    #chebdiff1 = pow(2,1-i)*i*sin(i*arccos(x))/pow(1-x*x,0.5)
    #chebdiff2 = pow(2,1-i)*i*( x*sin(i*arccos(x))/pow(1-x*x,1.5) - i*cos(i*arccos(x))/(1-x*x))

    # scale to physical interval [a,b]
    xp = affineTransform(x, a, b)
    
    c = 2.0/(b-a)
    for i in range(0,N):
        for j in range(0, N):
            tmp = pow(2,1-j)*j*sin(j*arccos(x[i]))/pow(1-x[i]*x[i],0.5)
            diff1[i] += c*C[j]*tmp
            tmp = pow(2,1-j)*j*( x[i]*sin(j*arccos(x[i]))/pow(1-x[i]*x[i],1.5) - j*cos(j*arccos(x[i]))/(1-x[i]*x[i]))
            diff2[i] += c*c*C[j]*tmp
        diff1_anal[i] = (sympy.diff(sympy.exp(-sympy.abc.x*sympy.abc.x*beta), sympy.abc.x, 1)).subs(sympy.abc.x,xp[i])
        diff2_anal[i] = (sympy.diff(sympy.exp(-sympy.abc.x*sympy.abc.x*beta), sympy.abc.x, 2)).subs(sympy.abc.x,xp[i])
        
    # plot the Chebyshev nodes and the interpolation
    plot(xp, diff1, 'r--', label = "chebyshev derivative ord 1")
    plot(xp, diff1_anal, 'g.', label = "analytic derivative ord 1")
    plot(xp, diff2, 'y--', label = "chebyshev derivative ord 2")
    plot(xp, diff2_anal, 'b*', label = "analytic derivative ord 2")
    legend(loc="best")
    grid(True)
    show()
Пример #23
0
def Delp2(f):
    """ Laplacian in X-Z
    """
    d2fdx2 = diff(f, x, 2)
    d2fdz2 = diff(f, z, 2)

    return d2fdx2 + d2fdz2
Пример #24
0
def eleq(Lagrangian, Friction = 0, t = Symbol('t')):
    """
    Returns Euler-Lagrange equations of the lagrangian system.

    Examples
    ========

    >>> from sympy import *
    >>> t, k = symbols('t k')
    >>> x = symbols('x', cls=Function)
    >>> eleq(diff(x(t),t)**2/2 - k*x(t)**2/2)
    {a_x: -k*x}

    >>> a = symbols('a')
    >>> eleq(diff(x(t),t)**2/2 - k*x(t)**2/2, a*diff(x(t),t)**2/2)
    {a_x: -*a*v_x - k*x}
    """
    Lagrangian = simplify(Lagrangian)
    var_list = [list(x.atoms(Function))[0] for x in Lagrangian.atoms(Derivative)]
    nvar = len(var_list)
    ecu_list = [ diff(Lagrangian, variable) - diff(Lagrangian, diff(variable,t), t) -  diff(Friction, diff(variable,t)) for variable in var_list ]
    str_list = [ str(variable).replace("("+str(t)+")","") for variable in var_list ]
    a_subs = {diff(var_list[i],t,2): Symbol('a_' + str_list[i]) for i in range(nvar)}
    v_subs = {diff(var_list[i],t): Symbol('v_' + str_list[i]) for i in range(nvar)}
    x_subs = {var_list[i]: Symbol(str_list[i]) for i in range(nvar)}
    for i in range(nvar):
        if hasattr(ecu_list[i], "subs"):
            ecu_list[i] = ecu_list[i].subs(a_subs).subs(v_subs).subs(x_subs)
    a_list = sorted(list(a_subs.values()), key = str)
    return solveswc(ecu_list, a_list)
Пример #25
0
    def _derive_dw_dpsi():
        """Derive the slope dw_dpsi with sympy
        
        Returns
        -------
        dw_dpsi1 : sympy expression
            Derivative including correction factor.
        dw_dpsi2 : sympy expression
            Derivative with correction factor equal to one.
         """
        psi, a, n, m, psir, ws = sympy.symbols('psi, a, n, m, psir, ws')
        psi, ws, a, b, wr, s1, psir = sympy.symbols('psi, ws, a, b, wr, s1, psir')
        from sympy import log, exp        
        C1 = (1 - log(1 + psi / psir) / 
                          log(1.0 + 1.0e6 / psir))

        C2 = 1      
        
        l10 = sympy.symbols('l10')
        
        w = C1 * ((ws - s1 * log(psi)/l10 - wr) * a / (psi**b + a) + wr)
        dw_dpsi1 = sympy.diff(w, psi)                    
        
        w = C2 * ((ws - s1 * log(psi)/l10 - wr) * a / (psi**b + a) + wr)
        dw_dpsi2 = sympy.diff(w, psi)
        return  dw_dpsi1, dw_dpsi2
Пример #26
0
def test_legendre():
    raises(ValueError, lambda: legendre(-1, x))
    assert legendre(0, x) == 1
    assert legendre(1, x) == x
    assert legendre(2, x) == ((3*x**2 - 1)/2).expand()
    assert legendre(3, x) == ((5*x**3 - 3*x)/2).expand()
    assert legendre(4, x) == ((35*x**4 - 30*x**2 + 3)/8).expand()
    assert legendre(5, x) == ((63*x**5 - 70*x**3 + 15*x)/8).expand()
    assert legendre(6, x) == ((231*x**6 - 315*x**4 + 105*x**2 - 5)/16).expand()

    assert legendre(10, -1) == 1
    assert legendre(11, -1) == -1
    assert legendre(10, 1) == 1
    assert legendre(11, 1) == 1
    assert legendre(10, 0) != 0
    assert legendre(11, 0) == 0

    assert roots(legendre(4, x), x) == {
        sqrt(Rational(3, 7) - Rational(2, 35)*sqrt(30)): 1,
        -sqrt(Rational(3, 7) - Rational(2, 35)*sqrt(30)): 1,
        sqrt(Rational(3, 7) + Rational(2, 35)*sqrt(30)): 1,
        -sqrt(Rational(3, 7) + Rational(2, 35)*sqrt(30)): 1,
    }

    n = Symbol("n")

    X = legendre(n, x)
    assert isinstance(X, legendre)

    assert legendre(-n, x) == legendre(n - 1, x)
    assert legendre(n, -x) == (-1)**n*legendre(n, x)
    assert diff(legendre(n, x), x) == \
        n*(x*legendre(n, x) - legendre(n - 1, x))/(x**2 - 1)
    assert diff(legendre(n, x), n) == Derivative(legendre(n, x), n)
Пример #27
0
def hamiltonian(Lagrangian, t = Symbol('t'), delta = False):
    """
    Returns the Hamiltonian of the Lagrangian.

    Examples
    ========

    >>> from sympy import *
    >>> t, k = symbols('t k')
    >>> x = symbols('x', cls=Function)
    >>> hamiltonian(diff(x(t),t)**2/2 - k*x(t)**2/2)
    k*x**2/2 + v_x**2/2
    """
    Lagrangian = simplify(Lagrangian)
    var_list = [list(x.atoms(Function))[0] for x in Lagrangian.atoms(Derivative)]
    nvar = len(var_list)
    # New variables.
    str_list = [ str(variable).replace("("+str(t)+")","") for variable in var_list ]
    v_subs = {diff(var_list[i],t): Symbol('v_' + str_list[i]) for i in range(nvar)}
    x_subs = {var_list[i]: Symbol(str_list[i]) for i in range(nvar)}
    # Hamiltonian calculus.
    dxdLv = 0
    for variable in var_list:
        dxdLv += diff(variable,t)*diff(Lagrangian, diff(variable,t))
    result = simplify((dxdLv - Lagrangian).subs(v_subs).subs(x_subs))
    if delta:
        v0_subs = {Symbol('v_' + str_list[i]): Symbol('v_' + str_list[i] + "0") for i in range(nvar)}
        x0_subs = {Symbol(str_list[i]): Symbol(str_list[i] + "0") for i in range(nvar)}
        return result - result.subs(v0_subs).subs(x0_subs)
    else:
        return result
def ItoFormula_2(function,a,b,dt):
	func = compile(function,"",'eval')
	a=float(a)
	b=float(b)
	n=int((b-a)/dt)	
	WP = 0
	t = a
	for i in range(int(a/dt)):
		WP = WP+np.random.normal(0,math.sqrt(dt))
	part_1 = eval(func)
	f = sym.sympify(function)
	WP = sym.Symbol('WP')
	df = str(sym.diff(f,WP))
	ddf = str(sym.diff(df,WP))
	part_2 = 0
	part_3 = 0
	result_2 = 0
	WP = 0
	for i in range(0,n):
		t=dt*((a/dt)+i)
		WP = WP+np.random.normal(0,math.sqrt(dt))
		k2 = eval(df,valueDic)
		k3 = eval(ddf,valueDic)
		part_2 = part_2 + k2*(WT[i+1]-WT[i])
		part_3 = part_3 + k3*dt
	result_2 = part_1 + part_2 + part_3
	print 'ito formula result: '+str(result_2)
Пример #29
0
def make_qdiff_to_q012(x_names):
    qdiff_to_q012 = {}
    qdiff_0 = {}
    qdiff_1 = {}
    qdiff_2 = {}

    for date_str in ['tp1', 't', 'tm1']:
        dated_names = [name + date_str for name in x_names]
        dated_q_fun_sym = [sympy.Function(x)(q) for x in dated_names]

        dated_names_0 = [name + '_0' for name in dated_names]
        dated_names_0_sym = [sympy.Symbol(x) for x in dated_names_0]
        qdiff_0.update(dict(zip(dated_q_fun_sym, dated_names_0_sym)))

        dated_qdiffs_1 = [sympy.diff(x, q, 1) for x in dated_q_fun_sym]
        dated_names_1 = [name + '_1' for name in dated_names]
        dated_names_1_sym = [sympy.Symbol(x) for x in dated_names_1]
        qdiff_1.update(dict(zip(dated_qdiffs_1, dated_names_1_sym)))

        dated_qdiffs_2 = [sympy.diff(x, q, 2) for x in dated_q_fun_sym]
        dated_names_2 = [name + '_2' for name in dated_names]
        dated_names_2_sym = [sympy.Symbol(x) for x in dated_names_2]
        qdiff_2.update(dict(zip(dated_qdiffs_2, dated_names_2_sym)))

    qdiff_to_q012.update(qdiff_0)
    qdiff_to_q012.update(qdiff_1)
    qdiff_to_q012.update(qdiff_2)

    return qdiff_to_q012
def update_integral_data(u_str, v_str, cx_str, cy_str):
    #string parsing
    u_fun, _ = my_bokeh_utils.string_to_function_parser(u_str, ['x', 'y'])
    v_fun, _ = my_bokeh_utils.string_to_function_parser(v_str, ['x', 'y'])
    cx_fun, cx_sym = my_bokeh_utils.string_to_function_parser(cx_str, ['t'])
    cy_fun, cy_sym = my_bokeh_utils.string_to_function_parser(cy_str, ['t'])

    from sympy import diff

    dcx_sym = diff(cx_sym,'t')
    dcy_sym = diff(cy_sym,'t')

    dcx_fun = my_bokeh_utils.sym_to_function_parser(dcx_sym, 't')
    dcy_fun = my_bokeh_utils.sym_to_function_parser(dcy_sym, 't')

    t = np.linspace(curveintegral_settings.parameter_min,curveintegral_settings.parameter_max)

    f_I = lambda xx, tt: (u_fun(cx_fun(tt),cy_fun(tt)) * dcx_fun(tt) + v_fun(cx_fun(tt),cy_fun(tt)) * dcy_fun(tt))

    integrand = f_I(None,t)

    from scipy.integrate import odeint

    integral = odeint(f_I,0,t)

    source_integral.data = dict(t=t.tolist(),
                                integral=integral.tolist(),
                                integrand=integrand.tolist())
        p11, p12, p13, p14, \
            p22, p23, p24,  \
            p33, p34,       \
            p44                    \
            = symbols('p11 p12 p13 p14 \
                       p22 p23 p24 \
                       p33 p34 \
                       p44')

        P = Matrix([[p11, p12, p13, p14],
                    [p12, p22, p23, p24],
                    [p13, p23, p33, p34],
                    [p14, p24, p34, p44]])

        F = Matrix([[diff(h_dot, h),     diff(theta_dot, h),     diff(v_dot, h),     diff(gam_dot, h)],
                    [diff(h_dot, theta), diff(theta_dot, theta), diff(v_dot, theta), diff(gam_dot, theta)],
                    [diff(h_dot, v),     diff(theta_dot, v),     diff(v_dot, v),     diff(gam_dot, v)],
                    [diff(h_dot, gam),   diff(theta_dot, gam),   diff(v_dot, gam),   diff(gam_dot, gam)]]).T

        G = Matrix([[0, 0],
                    [0, 0],
                    [1, 0],
                    [0, 1]])

        theta_r = theta - theta_b

        Rho = sqrt(
            r_e ** 2 + r ** 2 - 2 * r * r_e * cos(theta - theta_b))  # sqrt(2*r_e*(r_e + h)*(1 - cos(theta_r)) + h**2)

        H = Matrix([[diff(Rho, h), diff(Rho, theta), diff(Rho, v), diff(Rho, gam)]])
Пример #32
0
def test_heurisch_symbolic_coeffs():
    assert heurisch(1 / (x + y), x) == log(x + y)
    assert heurisch(1 / (x + sqrt(2)), x) == log(x + sqrt(2))
    assert simplify(diff(heurisch(log(x + y + z), y), y)) == log(x + y + z)
Пример #33
0
def test_BVirial_Pitzer_Curl_calculus():
    from sympy import symbols, Rational, diff, lambdify, integrate
    # Derivatives check
    # Uses SymPy
    T, Tc, Pc, omega, R = symbols('T, Tc, Pc, omega, R')
    Tr = T/Tc
    B0 = Rational(1445,10000) - Rational(33,100)/Tr - Rational(1385,10000)/Tr**2 - Rational(121,10000)/Tr**3
    B1 = Rational(73,1000) + Rational(46,100)/Tr - Rational(1,2)/Tr**2 - Rational(97,1000)/Tr**3 - Rational(73,10000)/Tr**8
        
    # Note: scipy.misc.derivative was attempted, but found to given too
    # incorrect of derivatives for higher orders, so there is no reasons to 
    # implement it. Plus, no uses have yet been found for the higher 
    # derivatives/integrals. For integrals, there is no way to get the 
    # indefinite integral.
    
    # Test 160K points in vector form for order 1, 2, and 3
    # Use lambdify for fast evaluation
    _Ts = np.linspace(5,500,20)
    _Tcs = np.linspace(501,900,20)
    _Pcs = np.linspace(2E5, 1E7,20)
    _omegas = np.linspace(-1, 10,20)
    _Ts, _Tcs, _Pcs, _omegas = np.meshgrid(_Ts, _Tcs, _Pcs, _omegas)
    _Ts, _Tcs, _Pcs, _omegas = _Ts.ravel(), _Tcs.ravel(), _Pcs.ravel(), _omegas.ravel()
    for order in range(1,4):
        B0c = diff(B0, T, order)
        B1c = diff(B1, T, order)
        Br = B0c + omega*B1c
        BVirial = (Br*R*Tc/Pc).subs(R, _R)
        f = lambdify((T, Tc, Pc, omega), BVirial, "numpy")
        
        Bcalcs = f(_Ts, _Tcs, _Pcs, _omegas)
        Bcalc2 = BVirial_Pitzer_Curl(_Ts, _Tcs, _Pcs, _omegas, order)
        assert_allclose(Bcalcs, Bcalc2)
        

    # Check integrals using SymPy:
    for order in range(-2, 0):
        B0c = B0
        B1c = B1
        for i in range(abs(order)):
            B0c = integrate(B0c, T)
            B1c = integrate(B1c, T)
        Br = B0c + omega*B1c
        BVirial = (Br*R*Tc/Pc).subs(R, _R)
        f = lambdify((T, Tc, Pc, omega), BVirial, "numpy")
        
        Bcalcs = f(_Ts, _Tcs, _Pcs, _omegas)
        Bcalc2 = [BVirial_Pitzer_Curl(T2, Tc2, Pc2, omega2, order) for T2, Tc2, Pc2, omega2 in zip(_Ts, _Tcs, _Pcs, _omegas)]
        assert_allclose(Bcalcs, Bcalc2)


    # Check integrals using numerical methods - quad:
    for order in range(-2, 0):
        for trial in range(10):
            T1, T2 = np.random.random_integers(5, 500, 2)*np.random.rand(2)
            _Tc = np.random.choice(_Tcs)
            _Pc = np.random.choice(_Pcs)
            _omega = np.random.choice(_omegas)
            
            dBint = BVirial_Pitzer_Curl(T2, _Tc, _Pc, _omega, order) - BVirial_Pitzer_Curl(T1, _Tc, _Pc, _omega, order)
            dBquad = quad(BVirial_Pitzer_Curl, T1, T2, args=(_Tc, _Pc, _omega, order+1))[0]
            assert_allclose(dBint, dBquad, rtol=1E-5)
Пример #34
0
def test_BVirial_Tsonopoulos_extended():
    from sympy import symbols, Rational, diff, lambdify, integrate

    B = BVirial_Tsonopoulos_extended(510., 425.2, 38E5, 0.193, species_type='normal', dipole=0)
    assert_allclose(B, -0.00020935288308483694)

    B = BVirial_Tsonopoulos_extended(430., 405.65, 11.28E6, 0.252608, a=0, b=0, species_type='ketone', dipole=1.469)
    assert_allclose(B, -9.679715056695323e-05)

    with pytest.raises(Exception):
        BVirial_Tsonopoulos_extended(510., 425.2, 38E5, 0.193, order=-3)

    # Test all of the different types
    types = ['simple', 'normal', 'methyl alcohol', 'water', 'ketone',
    'aldehyde', 'alkyl nitrile', 'ether', 'carboxylic acid', 'ester', 'carboxylic acid',
    'ester', 'alkyl halide', 'mercaptan', 'sulfide', 'disulfide', 'alkanol']

    Bs_calc = [BVirial_Tsonopoulos_extended(430., 405.65, 11.28E6, 0.252608,
                                            a=0, b=0, species_type=i, dipole=0.1) for i in types]
    Bs = [-9.002529440027288e-05, -9.002529440027288e-05, -8.136805574379563e-05, -9.232250634010228e-05, -9.00558069055045e-05, -9.00558069055045e-05, -9.00558069055045e-05, -9.00558069055045e-05, -9.00558069055045e-05, -9.00558069055045e-05, -9.00558069055045e-05, -9.00558069055045e-05, -9.003495446399036e-05, -9.003495446399036e-05, -9.003495446399036e-05, -9.003495446399036e-05, -7.331247111785242e-05]
    assert_allclose(Bs_calc, Bs)


    # Use lambdify for fast evaluation
    _Ts = np.linspace(5,500,20)
    _Tcs = np.linspace(501,900,20)
    _Pcs = np.linspace(2E5, 1E7,20)
    _omegas = np.linspace(-1, 10,20)
    _Ts, _Tcs, _Pcs, _omegas = np.meshgrid(_Ts, _Tcs, _Pcs, _omegas)
    _Ts, _Tcs, _Pcs, _omegas = _Ts.ravel(), _Tcs.ravel(), _Pcs.ravel(), _omegas.ravel()

    T, Tc, Pc, omega, R = symbols('T, Tc, Pc, omega, R')
    Tr = T/Tc
    B0 = Rational(1445, 10000) - Rational(33,100)/Tr - Rational(1385,10000)/Tr**2 - Rational(121,10000)/Tr**3 - Rational(607,1000000)/Tr**8
    B1 = Rational(637,10000) + Rational(331,1000)/Tr**2 - Rational(423,1000)/Tr**3 - Rational(8,1000)/Tr**8
    B2 = 1/Tr**6
    B3 = -1/Tr**8

    a = 0.1
    b = 0.2

    for order in range(1,4):
        B0c = diff(B0, T, order)
        B1c = diff(B1, T, order)
        B2c = diff(B2, T, order)
        B3c = diff(B3, T, order)
        
        Br = B0c + omega*B1c + a*B2c + b*B3c
        BVirial = (Br*R*Tc/Pc).subs(R, _R)
        f = lambdify((T, Tc, Pc, omega), BVirial, "numpy")
        
        Bcalcs = f(_Ts, _Tcs, _Pcs, _omegas)
        Bcalc2 = BVirial_Tsonopoulos_extended(_Ts, _Tcs, _Pcs, _omegas, order=order, a=a, b=b)
        assert_allclose(Bcalcs, Bcalc2)


    # Check integrals using SymPy:
    for order in range(-2, 0):
        B0c = B0
        B1c = B1
        B2c = B2
        B3c = B3
        for i in range(abs(order)):
            B0c = integrate(B0c, T)
            B1c = integrate(B1c, T)
            B2c = integrate(B2c, T)
            B3c = integrate(B3c, T)
        Br = B0c + omega*B1c + a*B2c + b*B3c

        BVirial = (Br*R*Tc/Pc).subs(R, _R)
        f = lambdify((T, Tc, Pc, omega), BVirial, "numpy")
        
        Bcalcs = f(_Ts, _Tcs, _Pcs, _omegas)
        
        
        Bcalc2 = [BVirial_Tsonopoulos_extended(T2, Tc2, Pc2, omega2, a=a, b=b, order=order) for T2, Tc2, Pc2, omega2 in zip(_Ts, _Tcs, _Pcs, _omegas)]
        assert_allclose(Bcalcs, Bcalc2)


    # Check integrals using numerical methods - quad:
    for order in range(-2, 0):
        for trial in range(10):
            T1, T2 = np.random.random_integers(5, 500, 2)*np.random.rand(2)
            _Tc = np.random.choice(_Tcs)
            _Pc = np.random.choice(_Pcs)
            _omega = np.random.choice(_omegas)
            
            dBint = BVirial_Tsonopoulos_extended(T2, _Tc, _Pc, _omega, a=a, b=b, order=order) - BVirial_Tsonopoulos_extended(T1, _Tc, _Pc, _omega, a=a, b=b, order=order)
            dBquad = quad(BVirial_Tsonopoulos_extended, T1, T2, args=(_Tc, _Pc, _omega, a, b, '', 0, order+1))[0]
            assert_allclose(dBint, dBquad, rtol=3E-5)
Пример #35
0
def test_BVirial_Tsonopoulos():
    from sympy import symbols, Rational, diff, lambdify, integrate

    B = BVirial_Tsonopoulos(510., 425.2, 38E5, 0.193)
    assert_allclose(B, -0.00020935288308483694)

    with pytest.raises(Exception):
        BVirial_Tsonopoulos(510., 425.2, 38E5, 0.193, order=-3)

    T, Tc, Pc, omega, R = symbols('T, Tc, Pc, omega, R')
    Tr = T/Tc
    B0 = Rational(1445, 10000) - Rational(33,100)/Tr - Rational(1385,10000)/Tr**2 - Rational(121,10000)/Tr**3 - Rational(607,1000000)/Tr**8
    B1 = Rational(637,10000) + Rational(331,1000)/Tr**2 - Rational(423,1000)/Tr**3 - Rational(8,1000)/Tr**8

    # Test 160K points in vector form for order 1, 2, and 3
    # Use lambdify for fast evaluation
    _Ts = np.linspace(5,500,20)
    _Tcs = np.linspace(501,900,20)
    _Pcs = np.linspace(2E5, 1E7,20)
    _omegas = np.linspace(-1, 10,20)
    _Ts, _Tcs, _Pcs, _omegas = np.meshgrid(_Ts, _Tcs, _Pcs, _omegas)
    _Ts, _Tcs, _Pcs, _omegas = _Ts.ravel(), _Tcs.ravel(), _Pcs.ravel(), _omegas.ravel()


    for order in range(1,4):
        B0c = diff(B0, T, order)
        B1c = diff(B1, T, order)
        Br = B0c + omega*B1c
        BVirial = (Br*R*Tc/Pc).subs(R, _R)
        f = lambdify((T, Tc, Pc, omega), BVirial, "numpy")
        
        Bcalcs = f(_Ts, _Tcs, _Pcs, _omegas)
        Bcalc2 = BVirial_Tsonopoulos(_Ts, _Tcs, _Pcs, _omegas, order)
        assert_allclose(Bcalcs, Bcalc2)

    # Check integrals using SymPy:
    for order in range(-2, 0):
        B0c = B0
        B1c = B1
        for i in range(abs(order)):
            B0c = integrate(B0c, T)
            B1c = integrate(B1c, T)
        Br = B0c + omega*B1c
        BVirial = (Br*R*Tc/Pc).subs(R, _R)
        f = lambdify((T, Tc, Pc, omega), BVirial, "numpy")
        
        Bcalcs = f(_Ts, _Tcs, _Pcs, _omegas)
        
        
        Bcalc2 = [BVirial_Tsonopoulos(T2, Tc2, Pc2, omega2, order) for T2, Tc2, Pc2, omega2 in zip(_Ts, _Tcs, _Pcs, _omegas)]
        assert_allclose(Bcalcs, Bcalc2)


    # Check integrals using numerical methods - quad:
    for order in range(-2, 0):
        for trial in range(10):
            T1, T2 = np.random.random_integers(5, 500, 2)*np.random.rand(2)
            _Tc = np.random.choice(_Tcs)
            _Pc = np.random.choice(_Pcs)
            _omega = np.random.choice(_omegas)
            
            dBint = BVirial_Tsonopoulos(T2, _Tc, _Pc, _omega, order) - BVirial_Tsonopoulos(T1, _Tc, _Pc, _omega, order)
            dBquad = quad(BVirial_Tsonopoulos, T1, T2, args=(_Tc, _Pc, _omega, order+1))[0]
            assert_allclose(dBint, dBquad, rtol=1E-5)
Пример #36
0
 def derivative(self, diff):
     derivative = sympy.diff(self.expression, diff.symbol)
     result = SymDim(expression=derivative)
     result.evaluate()
     return result
Пример #37
0
p1 = sym.Symbol('p1')
p2 = sym.Symbol('p2')
p3 = sym.Symbol('p3')
p4 = sym.Symbol('p4')
q1 = sym.Symbol('q1')
q2 = sym.Symbol('q2')
q3 = sym.Symbol('q3')
q4 = sym.Symbol('q4')

R = sym.Symbol('R', constant=True)
S = sym.Symbol('S', constant=True)
T = sym.Symbol('T', constant=True)
P = sym.Symbol('P', constant=True)

D_SY = sym.Matrix( \
   [ [p1*q1-1, p1-1, q1-1, R],   \
    [p2*q3, p2-1, q3, T], \
    [p3*q2, p3, q2-1, S], \
    [p4*q4, p4, q4, P] ])

D_1 = sym.Matrix( \
   [ [p1*q1-1, p1-1, q1-1, 1],   \
    [p2*q3, p2-1, q3, 1], \
    [p3*q2, p3, q2-1, 1], \
    [p4*q4, p4, q4, 1] ])

up = sym.det(D_SY)
down = sym.det(D_1)

diff_up = sym.simplify(sym.diff(up, p1) * down - up * sym.diff(down, p1))
print(sym.simplify(sym.diff(diff_up, p1)))
        v_dot = g * sin(theta)

        writeList = [x_dot, y_dot, v_dot]

        # Covariance Calculations

        p11, p12, p13, \
        p22, p23, \
        p33 \
            = symbols('p11 p12 p13\
                       p22 p23 \
                       p33'                           )

        P = Matrix([[p11, p12, p13], [p12, p22, p23], [p13, p23, p33]])

        F = Matrix([[diff(x_dot, x),
                     diff(x_dot, y),
                     diff(x_dot, v)],
                    [diff(y_dot, x),
                     diff(y_dot, y),
                     diff(y_dot, v)],
                    [diff(v_dot, x),
                     diff(v_dot, y),
                     diff(v_dot, v)]])

        G = Matrix([[0], [0], [1]])

        h = v**2

        H = Matrix([[diff(h, x), diff(h, y), diff(h, v)]])
Пример #39
0
x0, y0, x1, y1, x2, y2, x3, y3 = symbols('x0 y0 x1 y1 x2 y2 x3 y3')

points = [(2, 3),
          (4, 4),
          (3, 2.5),
          (4.5, 5)
          ]


def f(x0, y0, x1, y1, x2, y2, x3, y3):
    _sum = 0
    for t, (x, y) in enumerate(points):
        _sum += distance(bezier(x0, x1, x2, x3, t), (x, y))


dx0 = Poly(diff(f(x0, y0, x1, y1, x2, y2, x3, y3), x0)).coeffs()
dy0 = Poly(diff(f(x0, y0, x1, y1, x2, y2, x3, y3), y0)).coeffs()
dx1 = Poly(diff(f(x0, y0, x1, y1, x2, y2, x3, y3), x1)).coeffs()
dy1 = Poly(diff(f(x0, y0, x1, y1, x2, y2, x3, y3), y1)).coeffs()
dx2 = Poly(diff(f(x0, y0, x1, y1, x2, y2, x3, y3), x2)).coeffs()
dy2 = Poly(diff(f(x0, y0, x1, y1, x2, y2, x3, y3), y2)).coeffs()
dx3 = Poly(diff(f(x0, y0, x1, y1, x2, y2, x3, y3), x3)).coeffs()
dy3 = Poly(diff(f(x0, y0, x1, y1, x2, y2, x3, y3), y3)).coeffs()

A = np.array([dx0[:-1], dy0[:-1], dx1[:-1], dy1[:-1], dx2[:-1], dy2[:-1], dx3[:-1], dy3[:-1]], dtype=float)

X = np.linalg.solve(A, B).flatten()

print(f'y^ = {round(X[1], 3)}x + {round(X[0], 3)}')
Пример #40
0
            = symbols('p11 p12 p13 p14 p15 p16 \
                       p22 p23 p24 p25 p26 \
                       p33 p34 p35 p36 \
                       p44 p45 p46 \
                       p55 p56  \
                       p66'                           )

        P = Matrix([[p11, p12, p13, p14, p15, p16],
                    [p12, p22, p23, p24, p25, p26],
                    [p13, p23, p33, p34, p35, p36],
                    [p14, p24, p34, p44, p45, p46],
                    [p15, p25, p35, p45, p55, p56],
                    [p16, p26, p36, p46, p56, p66]])

        F = Matrix([[
            diff(x1_dot, x1),
            diff(x1_dot, y1),
            diff(x1_dot, theta1),
            diff(x1_dot, x2),
            diff(x1_dot, y2),
            diff(x1_dot, theta2)
        ],
                    [
                        diff(y1_dot, x1),
                        diff(y1_dot, y1),
                        diff(y1_dot, theta1),
                        diff(y1_dot, x2),
                        diff(y1_dot, y2),
                        diff(y1_dot, theta2)
                    ],
                    [
Пример #41
0
def differentiate(expr, wrt=None, wrt_list=None):
    """Return derivative of expression.

    This function returns an expression or list of expression objects
    corresponding to the derivative of the passed expression 'expr' with
    respect to a variable 'wrt' or list of variables 'wrt_list'

    Args:
        expr (Expression): Pyomo expression
        wrt (Var): Pyomo variable
        wrt_list (list): list of Pyomo variables

    Returns:
        Expression or list of Expression objects

    """
    if not sympy_available:
        raise RuntimeError(
            "The sympy module is not available.\n\t"
            "Cannot perform automatic symbolic differentiation.")
    if not ((wrt is None) ^ (wrt_list is None)):
        raise ValueError(
            "differentiate(): Must specify exactly one of wrt and wrt_list")
    import sympy
    #
    # Convert the Pyomo expression to a sympy expression
    #
    objectMap, sympy_expr = sympyify_expression(expr)
    #
    # The partial_derivs dict holds intermediate sympy expressions that
    # we can re-use.  We will prepopulate it with None for all vars that
    # appear in the expression (so that we can detect wrt combinations
    # that are, by definition, 0)
    #
    partial_derivs = dict((x, None) for x in objectMap.sympyVars())
    #
    # Setup the WRT list
    #
    if wrt is not None:
        wrt_list = [wrt]
    else:
        # Copy the list because we will normalize things in place below
        wrt_list = list(wrt_list)
    #
    # Convert WRT vars into sympy vars
    #
    ans = [None] * len(wrt_list)
    for i, target in enumerate(wrt_list):
        if target.__class__ is not tuple:
            target = (target, )
        wrt_list[i] = tuple(objectMap.getSympySymbol(x) for x in target)
        for x in wrt_list[i]:
            if x not in partial_derivs:
                ans[i] = 0.
                break
    #
    # We assume that users will not request duplicate derivatives.  We
    # will only cache up to the next-to last partial, and if a user
    # requests the exact same derivative twice, then we will just
    # re-calculate it.
    #
    last_partial_idx = max(len(x) for x in wrt_list) - 1
    #
    # Calculate all the derivatives
    #
    for i, target in enumerate(wrt_list):
        if ans[i] is not None:
            continue
        part = sympy_expr
        for j, wrt_var in enumerate(target):
            if j == last_partial_idx:
                part = sympy.diff(part, wrt_var)
            else:
                partial_target = target[:j + 1]
                if partial_target in partial_derivs:
                    part = partial_derivs[partial_target]
                else:
                    part = sympy.diff(part, wrt_var)
                    partial_derivs[partial_target] = part
        ans[i] = sympy2pyomo_expression(part, objectMap)
    #
    # Return the answer
    #
    return ans if wrt is None else ans[0]
Пример #42
0

pF = normal(s, g(mux), Sigma_s) \
    * normal(dmux, f(mux, munu), Sigma_x)\
    * normal(dmunu, munu, Sigma_nu)

# %%
F = -log(pF[0]) - C
F = F.expand(force=True)
F = F.collect(Sigma_s)
F = F.collect(Sigma_x)
F = F.collect(Sigma_nu)
display(F)

# %%
d_mux = Eq(-diff("F", mux, evaluate=False),
           -syp.separatevars(diff(F, mux), force=True),
           evaluate=False)
display(d_mux)
print(syp.latex(d_mux))

# %%
d_dmux = Eq(-diff("F", dmux, evaluate=False),
            -diff(F, dmux).simplify(),
            evaluate=False)
display(d_dmux)
print(syp.latex(d_dmux))

# %%
a = symbols("a", real=True)
spa = syp.Function("s_p")(a)
Пример #43
0
import sympy as sp

x = sp.Symbol('x')
y = x**10 + 2 * (x - 10)**9
for n in range(1, 12):
    y = d = sp.diff(y)
    print('第%2d阶导数为:%s' % (n, d))
def find_inflections(path, file, study, format_type, record, sensor, segment,
                     range):
    """

    """

    source = os.path.join('studies', study, 'formatted', format_type, record,
                          segment, sensor + '.csv')
    print('source = ' + source)
    df = pd.read_csv(source)
    print('df = ')
    print(df)

    for colName in df.columns:

        # remove extra columns because the dataframe will be saved
        if 'Unnamed' in str(colName):
            del df[colName]

        # save the timestamps as a list
        elif 'Minutes' in str(colName):
            timeMinutes = list(df[colName])

        elif 'meas' in colName:

            # add new columns to the dataframe to save the new variables
            newColNames = [
                'inflectionDecision', 'inflectionLocation',
                'polyfitCoefficients', 'polyfitEquation', 'polyfitSolution',
                'derivativeEquation', 'derivativeSolution'
            ]
            colNameSplit = colName.split('_')
            print('colNameSplit[0] = ' + colNameSplit[0])

            for suffix in newColNames:
                label = str(colNameSplit[0] + '_' + suffix)
                print('label = ' + label)
                if label not in df.columns:
                    df[label] = [None] * len((list(df['timeMinutes'])))

            df['timeBegin'] = [None] * len((list(df['timeMinutes'])))
            df['timeEnd'] = [None] * len((list(df['timeMinutes'])))

            for timeMinute in timeMinutes:

                i = df[df['timeMinutes'] == timeMinute].index.values[0]

                timeDif = (float(df.loc[2, 'timeMinutes']) -
                           float(df.loc[1, 'timeMinutes']))
                timeTolerance = timeDif / 2
                iRange = int(range / 60 * 1 / (timeDif))
                # print('iRange = ' + str(iRange))

                if len(list(df['timeMinutes'])) - i <= iRange + 2:
                    continue

                timeMedian = df.loc[int(i + iRange / 2), 'timeMinutes']
                timeBegin = df.loc[int(i), 'timeMinutes']
                timeEnd = df.loc[int(i + iRange), 'timeMinutes']

                # print('timeMedian = ' + str(timeMedian) + ' timeBegin = ' + str(timeBegin) + ' timeEnd = ' + str(timeEnd))
                # print('range = ' + str(range/60) +  ' timeEnd-timeBegin = ' + str(timeEnd-timeBegin) + ' % = ' + str(range/60/(timeEnd-timeBegin)))

                df_truncate = df[df['timeMinutes'] >= timeMinute]
                df_truncate = df_truncate[
                    df_truncate['timeMinutes'] <= timeMinute + range / 60]
                # df_truncate = df[df['timeMinutes'] >= timeMinute & df_truncate['timeMinutes'] <= timeMinute + range/60]

                timeTruncate = list(df_truncate['timeMinutes'])
                df.loc[int(i + iRange / 2), 'timeBegin'] = min(timeTruncate)
                df.loc[int(i + iRange / 2), 'timeEnd'] = max(timeTruncate)

                measTruncate = list(df_truncate[colName])

                coef = np.polyfit(timeTruncate, measTruncate, 2)
                x = sym.Symbol('x')
                f = coef[0] * x * x + coef[1] * x + coef[2]
                dff = sym.diff(f, x)
                solf = sym.solve(f)
                soldf = sym.solve(dff)
                soldf = soldf[0]

                label = str(colNameSplit[0] + '_' + 'inflectionDecision')
                df.loc[int(i + iRange / 2), label] = 'No'

                label = str(colNameSplit[0] + '_' + 'inflectionLocation')
                df.loc[int(i + iRange / 2), label] = timeMinute

                label = str(colNameSplit[0] + '_' + 'polyfitCoefficients')
                df.loc[int(i + iRange / 2),
                       label] = str(''.join([str(x) for x in coef]))

                label = str(colNameSplit[0] + '_' + 'polyfitEquation')
                df.loc[int(i + iRange / 2), label] = str(f)

                label = str(colNameSplit[0] + '_' + 'polyfitSolution')
                df.loc[int(i + iRange / 2),
                       label] = str(''.join([str(x) for x in solf]))

                label = str(colNameSplit[0] + '_' + 'derivativeEquation')
                df.loc[int(i + iRange / 2), label] = str(dff)

                label = str(colNameSplit[0] + '_' + 'derivativeSolution')
                df.loc[int(i + iRange / 2), label] = str(soldf)

                if soldf < timeMedian + timeTolerance:

                    if soldf > timeMedian - timeTolerance:

                        print('inflection found at time = ' + str(soldf))
                        label = str(colNameSplit[0] + '_' +
                                    'inflectionDecision')
                        df.loc[int(i + iRange / 2), label] = 'Yes'

    path = build_path(path)
    file = os.path.join(path, sensor + ".csv")
    df.to_csv(file)
    print('inflection list saved : ' + file)
    return (file)
Пример #45
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
import sympy as sym
from functools import partial

x = sym.symbols('x0 x1')
F0 = sym.tan(x[0] * x[1] + 0.5) - x[0]**2
F1 = x[0]**2 + x[1]**2 - 1
J1 = sym.lambdify(x, sym.diff(F0, x[0]))
J2 = sym.lambdify(x, sym.diff(F0, x[1]))
J3 = sym.lambdify(x, sym.diff(F1, x[0]))
J4 = sym.lambdify(x, sym.diff(F1, x[1]))


def newton_method(f, J, x, eps):
    f_value = f(x)
    f_norm = np.linalg.norm(f_value, ord=2)
    while abs(f_norm) > eps:
        delta = np.linalg.solve(J(x), -f_value)
        x += delta
        f_value = f(x)
        f_norm = np.linalg.norm(f_value, ord=2)
    return x


def newton_method_mod(f, J, x, eps):
    f_value = f(x)
    f_norm = np.linalg.norm(f_value, ord=2)
    jacobian = J(x)
Пример #46
0
             print ("")
             sympy.pprint(res)
             time.sleep(delay)
             cls()
         else:
             print("Я не знаю, что вы ввели, попробуйте ещё раз")
 ##############################################################################################################################
 # Высшая математика
 elif (value == 5):
     value = int(input("\n 15) Производная  \n 25) Интеграл \n 35) Лимит (x->оо) \n 45) Лимит (x->0) \n 55) Лимит (x->1) \n 65) Лимит (любое число) \n 75) Определённый интеграл \n \n "))
     # Производная
     if (value == 15):
         print ("")
         input_string = raw_input(' Выражение: ')
         print ("")
         res = sum(sympy.diff(input_string, var) for var in [x, y])
         sympy.pprint(res)
         time.sleep(delay)
         cls()
     # Интеграл
     elif (value == 25):
         print ("")
         x = Symbol("x")
         y = Symbol("y")
         input_string = input(' Выражение: ')
         print ("")
         sympy.pprint(sympy.Integral(input_string, x))
         print ("")
         sympy.pprint(integrate(input_string, x))
         time.sleep(delay)
         cls()
Пример #47
0
                cur_obs_lat = obs_lat_vector[i_obs][0, 0]
                cur_obs_lon = obs_lon_vector[i_obs][0, 0]
                cur_obs_operator_input = {}
                for required_bk_var in required_bk_vars:
                    start_index = background_type_vector.tolist().index(
                        [str(required_bk_var)])
                    cur_obs_operator_input[str(
                        required_bk_var)] = background_data_vector[start_index
                                                                   + n][0, 0]
                    cur_distance0 = math.sqrt((cur_obs_lat - cur_bk_lat)**2 +
                                              (cur_obs_lon - cur_bk_lon)**2)
                    distance_conversion0 = cur_distance0 / float(
                        total_distance)
                    linearized_observation_operator[
                        i_obs, start_index + n] = sympy.diff(
                            direct_obs_operator[cur_obs_type],
                            background_type_vector[start_index + n][0, 0])

                bkg_weight_0 = 0
                bkg_weight_1 = 0
                for ii in range(0, bkg_shape[0]):
                    for jj in range(0, bkg_shape[1]):
                        cur_bk_lat = background_data_dict['lat'][ii, jj]
                        cur_bk_lon = background_data_dict['lon'][ii, jj]
                        cur_distance = math.sqrt((cur_obs_lat -
                                                  cur_bk_lat)**2 +
                                                 (cur_obs_lon - cur_bk_lon)**2)
                        cur_distance_weight_0 = (
                            direct_obs_operator[cur_obs_type].subs(
                                cur_obs_operator_input)) / float(cur_distance**
                                                                 2)
Пример #48
0
fnlfid = values['fnlfid']

shot = 1./dic['ngal']+0.*Pgg


#### Define symbols

b, fnl, nbar, Pnl, func = sp.symbols('b fnl nbar Pnl func')

bias = b+fnl*func
P_total = bias**2.+1/nbar


print(P_total)

print(sp.diff(P_total, b))

derb_P_s = sp.diff(P_total, b)
derb_P = sp.lambdify([b, fnl, nbar, Pnl, func], derb_P_s, 'numpy')

result = derb_P(1., 0., 1., Pnn*0.+1., Pgn*0.+1.)
print(result)
'''

fig, ax = plt.subplots( nrows=1, ncols=1 )
#plt.xlim(0.01, 0.1)
#plt.ylim(1e1, 1e8)
plt.xlabel('$K$ $(h Mpc^{-1})$')
plt.ylabel('$P$ $(h^{-3} Mpc^{3})$')
ax.plot(K, Pgg, label = 'Pgg for fnl='+str(fnlfid))
ax.plot(K, Pnn, label = 'Pnn, n = growth est')
Пример #49
0
# July 2020
# OBJECCTIVE: 1. Sympy: SymPy is a Python library for symbolic mathematics (Linear algebra). It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python.
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
from sympy import init_session
my_teaser_array = np.array([1, 7, 19, 37, 61, 91, 127, 169, 217, 271, 331])

# 1. Diff in numpy: Substracts the elements
print('Onee time: ',np.diff(my_teaser_array))
print('Two times',np.diff(my_teaser_array,2))
print('Three times',np.diff(my_teaser_array,3))

# 2. DIFF in sympy
from sympy import init_session
# init_session() # Create interactive platform
x=sym.Symbol('x')
print(sym.diff(x**3))
print(sym.diff(x**3,x,3))



Пример #50
0
ax.plot_surface(x_4, y_4, f(x_4, y_4), cmap=cm.coolwarm, alpha=0.4)

plt.show()

# # Partial Derivatives & Symbolic Computation
# # $$\frac{\partial f}{\partial x} = \frac{2x \ln(3) \cdot 3^{-x^2 - y^2}}{\left( 3^{-x^2 - y^2} + 1 \right) ^2}$$
#
# # $$\frac{\partial f}{\partial y} = \frac{2y \ln(3) \cdot 3^{-x^2 - y^2}}{\left( 3^{-x^2 - y^2} + 1 \right) ^2}$$

# In[27]:

a, b = symbols('x,y')

print('Our cost function f(x,y) is:', f(a, b))
print('partial derivatives wrt x is:', diff(f(a, b), a))
print('Value of f(x,y) at x =1.8 y=1;0 ', f(a, b).evalf(subs={a: 1.8, b: 1.0}))

print('', diff(f(a, b), a).evalf(subs={a: 1.8, b: 1.0}))

# In[ ]:

# # Batch Gradiet Descent with SymPy

# In[28]:

# setup

multiplier = 0.1
max_iter = 500
params = np.array([1.8, 1.0])  # intial guess
Пример #51
0
    def apply_constraints(self, f, vars, evaluation):
        "Minimize[f_List, vars_List]"
        head_name = vars.get_head_name()
        vars_or = vars
        vars = vars.leaves
        for var in vars:
            if ((var.is_atom() and not var.is_symbol()) or head_name in (
                    "System`Plus", "System`Times", "System`Power")  # noqa
                    or "System`Constant" in var.get_attributes(
                        evaluation.definitions)):

                evaluation.message("Minimize", "ivar", vars_or)
                return

        vars_sympy = [var.to_sympy() for var in vars]
        constraints = [function for function in f.leaves]
        objective_function = constraints[0].to_sympy()

        constraints = constraints[1:]

        g_functions = []
        h_functions = []

        g_variables = []
        h_variables = []

        for constraint in constraints:
            left, right = constraint.leaves
            head_name = constraint.get_head_name()

            left = left.to_sympy()
            right = right.to_sympy()

            if head_name == "System`LessEqual" or head_name == "System`Less":
                eq = left - right
                eq = sympy.together(eq)
                eq = sympy.cancel(eq)

                g_functions.append(eq)
                g_variables.append(
                    sympy.Symbol("kkt_g" + str(len(g_variables))))

            elif head_name == "System`GreaterEqual" or head_name == "System`Greater":
                eq = -1 * (left - right)
                eq = sympy.together(eq)
                eq = sympy.cancel(eq)

                g_functions.append(eq)
                g_variables.append(
                    sympy.Symbol("kkt_g" + str(len(g_variables))))

            elif head_name == "System`Equal":
                eq = left - right
                eq = sympy.together(eq)
                eq = sympy.cancel(eq)

                h_functions.append(eq)
                h_variables.append(
                    sympy.Symbol("kkt_h" + str(len(h_variables))))

        equations = []

        for variable in vars_sympy:
            equation = sympy.diff(objective_function, variable)

            for i in range(len(g_variables)):
                g_variable = g_variables[i]
                g_function = g_functions[i]

                equation = equation + g_variable * sympy.diff(
                    g_function, variable)

            for i in range(len(h_variables)):
                h_variable = h_variables[i]
                h_function = h_functions[i]

                equation = equation + h_variable * sympy.diff(
                    h_function, variable)

            equations.append(equation)

        for i in range(len(g_variables)):
            g_variable = g_variables[i]
            g_function = g_functions[i]

            equations.append(g_variable * g_function)

        for i in range(len(h_variables)):
            h_variable = h_variables[i]
            h_function = h_functions[i]

            equations.append(h_variable * h_function)

        all_variables = vars_sympy + g_variables + h_variables

        candidates_tmp = sympy.solve(equations, all_variables, dict=True)
        candidates = []

        for candidate in candidates_tmp:
            if len(candidate) != len(vars_sympy):
                for variable in candidate:
                    for i in range(len(candidate), len(vars_sympy)):
                        candidate[variable] = candidate[variable].subs(
                            {vars_sympy[i]: 1})
                for i in range(len(candidate), len(vars_sympy)):
                    candidate[vars_sympy[i]] = 1

            candidates.append(candidate)

        kkt_candidates = []

        for candidate in candidates:
            kkt_ok = True

            sum_constraints = 0

            for i in range(len(g_variables)):
                g_variable = g_variables[i]
                g_function = g_functions[i]

                if candidate[g_variable] < 0:
                    kkt_ok = False

                if candidate[g_variable] * g_function.subs(candidate) != 0:
                    kkt_ok = False

                sum_constraints = sum_constraints + candidate[g_variable]

            for i in range(len(h_variables)):
                h_variable = h_variables[i]
                h_function = h_functions[i]

                sum_constraints = sum_constraints + abs(candidate[h_variable])

            if sum_constraints <= 0:
                kkt_ok = False

            if not kkt_ok:
                continue

            kkt_candidates.append(candidate)

        hessian = sympy.Matrix([[sympy.diff(deriv, x) for x in all_variables]
                                for deriv in equations])

        for i in range(0, len(all_variables) - len(vars_sympy)):
            hessian.col_del(len(all_variables) - i - 1)
            hessian.row_del(len(all_variables) - i - 1)

        minimum_list = []

        for candidate in kkt_candidates:
            eigenvals = hessian.subs(candidate).eigenvals()

            positives_eigenvalues = 0
            negatives_eigenvalues = 0

            for val in eigenvals:
                val = complex(sympy.N(val, chop=True))

                if val.imag == 0:
                    val = val.real
                    if val < 0:
                        negatives_eigenvalues += 1
                    elif val > 0:
                        positives_eigenvalues += 1

            if positives_eigenvalues + negatives_eigenvalues != len(eigenvals):
                continue

            if positives_eigenvalues == len(eigenvals):
                for g_variable in g_variables:
                    del candidate[g_variable]
                for h_variable in h_variables:
                    del candidate[h_variable]

                minimum_list.append(candidate)

        return Expression(
            "List",
            *(Expression(
                "List",
                from_sympy(objective_function.subs(minimum).simplify()),
                [
                    Expression(
                        "Rule",
                        from_sympy(list(minimum.keys())[i]),
                        from_sympy(list(minimum.values())[i]),
                    ) for i in range(len(vars_sympy))
                ],
            ) for minimum in minimum_list))
Пример #52
0
def test_Quantity_derivative():
    x = symbols("x")
    assert diff(x * meter, x) == meter
    assert diff(x**3 * meter**2, x) == 3 * x**2 * meter**2
    assert diff(meter, meter) == 1
    assert diff(meter**2, meter) == 2 * meter
Пример #53
0
 def calc_Dxi_x_matrix(x, i):
     return sympy.Matrix(2, 2,
                         lambda r, c: sympy.diff(x.matrix()[r, c], x[i]))
Пример #54
0
    def apply_multiplevariable(self, f, vars, evaluation):
        "Minimize[f_?NotListQ, vars_List]"

        head_name = vars.get_head_name()
        vars_or = vars
        vars = vars.leaves
        for var in vars:
            if ((var.is_atom() and not var.is_symbol()) or head_name in (
                    "System`Plus", "System`Times", "System`Power")  # noqa
                    or "System`Constant" in var.get_attributes(
                        evaluation.definitions)):

                evaluation.message("Minimize", "ivar", vars_or)
                return

        vars_sympy = [var.to_sympy() for var in vars]
        sympy_f = f.to_sympy()

        jacobian = [sympy.diff(sympy_f, x) for x in vars_sympy]
        hessian = sympy.Matrix([[sympy.diff(deriv, x) for x in vars_sympy]
                                for deriv in jacobian])

        candidates_tmp = sympy.solve(jacobian, vars_sympy, dict=True)
        candidates = []

        for candidate in candidates_tmp:
            if len(candidate) != len(vars_sympy):
                for variable in candidate:
                    for i in range(len(candidate), len(vars_sympy)):
                        candidate[variable] = candidate[variable].subs(
                            {vars_sympy[i]: 1})

                for i in range(len(candidate), len(vars_sympy)):
                    candidate[vars_sympy[i]] = 1

            candidates.append(candidate)

        minimum_list = []

        for candidate in candidates:
            eigenvals = hessian.subs(candidate).eigenvals()

            positives_eigenvalues = 0
            negatives_eigenvalues = 0

            for val in eigenvals:
                if val.is_real:
                    if val < 0:
                        negatives_eigenvalues += 1
                    elif val >= 0:
                        positives_eigenvalues += 1

            if positives_eigenvalues + negatives_eigenvalues != len(eigenvals):
                continue

            if positives_eigenvalues == len(eigenvals):
                minimum_list.append(candidate)

        return Expression(
            "List",
            *(Expression(
                "List",
                from_sympy(sympy_f.subs(minimum).simplify()),
                [
                    Expression(
                        "Rule",
                        from_sympy(list(minimum.keys())[i]),
                        from_sympy(list(minimum.values())[i]),
                    ) for i in range(len(vars_sympy))
                ],
            ) for minimum in minimum_list))
Пример #55
0
 def calc_Dx_exp_x(x):
     return sympy.Matrix(2, 1, lambda r, c: sympy.diff(So2.exp(x)[r], x))
Пример #56
0
 def calc_Dx_exp_x_matrix_at_0(x):
     return sympy.Matrix(
         2, 2,
         lambda r, c: sympy.diff(So2.exp(x).matrix()[r, c], x)).limit(x, 0)
Пример #57
0
 def calc_Dx_log_this(self):
     return sympy.diff(self.log(), self[0])
Пример #58
0
 def calc_Dx_this_mul_exp_x_at_0(self, x):
     return sympy.Matrix(2, 1, lambda r, c:
                         sympy.diff((self * So2.exp(x))[r], x))\
         .limit(x, 0)
Пример #59
0
# @E-mail: [email protected]
# @Site:
# @Time: Jul 30, 2021
# ---

from sympy import symbols, cos, sin, diff
import numpy as np

t, x, y, nu, pi = symbols('t x y nu pi')
epsilon, eta, m = symbols('epsilon eta m')

# --- ex0 --- #
u = cos(pi * x) * cos(pi * y) * sin(t)
h = epsilon / eta**2 * u * (u**2 - 1)

u_t = diff(u, t)
u_x = diff(u, x)
u_y = diff(u, y)
u_xx = diff(u_x, x)
u_yy = diff(u_y, y)

laplace_u = u_xx + u_yy
laplace_x = diff(laplace_u, x)
laplace_y = diff(laplace_u, y)

c = -epsilon * laplace_u + h
c_x = diff(c, x)
c_xx = diff(c_x, x)
c_y = diff(c, y)
c_yy = diff(c_y, y)
laplace_c = c_xx + c_yy
Пример #60
0
 def calc_Dx_log_exp_x_times_this_at_0(self, x):
     return sympy.diff((So2.exp(x) * self).log(), x).limit(x, 0)