예제 #1
0
def gm2_strategy(kurtosis, b=2):
    '''Use sympy to solve for "a" in Proposition 2 numerically.'''
    #  sym.init_printing(use_unicode=True)
    #  #        ^required if symbolic output is desired.
    a = sym.symbols('a')
    K = kurtosis / 3.0
    #  Use equation from Prop. 2
    LHS = (K - (b**4)) / ((a**4) - (b**4))
    RHS = (1 - (b**2)) / ((a**2) - (b**2))
    a_solved = sym.solveset(sym.Eq(LHS, RHS), a, domain=sym.S.Reals)
    #  ... expect negative and positve real solutions
    #      provided in sympy's FiniteSet format.
    if a_solved == sym.S.EmptySet:
        #               ^when no feasible solution was found in domain.
        #                Do not accept imaginary solutions.
        raise OverflowError("Extreme kurtosis: Retry using larger b.")
        #     ^dies when kurtosis > 12 and b=2, for example.
        #           SPX returns since 1957 have kurtosis around 31.6
        #           which is very high, requiring b>3.4 for feasiblity.
    else:
        #  But a>0 by construction, so extract the positive real number:
        a_positive = max(list(a_solved))
    return a_positive
예제 #2
0
파일: laplace.py 프로젝트: mhurta3/lcapy
def inverse_laplace_transform(expr, s, t, **assumptions):
    """Calculate inverse Laplace transform of X(s) and return x(t).

    The unilateral Laplace transform cannot determine x(t) for t < 0
    unless given additional information in the way of assumptions.

    The assumptions are:
    dc -- x(t) = constant so X(s) must have the form constant / s
    causal -- x(t) = 0 for t < 0.
    ac -- x(t) = A cos(a * t) + B * sin(b * t)
    """

    if expr.is_Equality:
        return sym.Eq(inverse_laplace_transform(expr.args[0], s, t,
                                                **assumptions),
                      inverse_laplace_transform(expr.args[1], s, t,
                                                **assumptions))    

    if expr.has(t):
        raise ValueError('Cannot inverse Laplace transform for expression %s that depends on %s' % (expr, t))

    const, cresult, uresult = inverse_laplace_transform1(expr, s, t, **assumptions)
    return inverse_laplace_make(t, const, cresult, uresult, **assumptions)    
예제 #3
0
 def print_Chain(self, rule):
     with self.new_step(), self.new_u_vars() as (u, du):
         self.append("Sea {}.".format(
             self.format_math(sympy.Eq(u, rule.inner))))
         self.print_rule(replace_u_var(rule.substep, rule.u_var, u))
     with self.new_step():
         if isinstance(rule.innerstep, FunctionRule):
             self.append(
                 "Entonces, aplicando la regla de la cadena. Multipicamos por {}:"
                 .format(
                     self.format_math(
                         sympy.Derivative(rule.inner, rule.symbol))))
             self.append(self.format_math_display(diff(rule)))
         else:
             self.append(
                 "Entonces, aplicando la regla de la cadena. Multipicamos por {}:"
                 .format(
                     self.format_math(
                         sympy.Derivative(rule.inner, rule.symbol))))
             with self.new_level():
                 self.print_rule(rule.innerstep)
             self.append("El resultado de la regla de la cadena:")
             self.append(self.format_math_display(diff(rule)))
예제 #4
0
def convert_relation(rel):
    if rel.expr():
        return convert_expr(rel.expr())

    lh = convert_relation(rel.relation(0))
    rh = convert_relation(rel.relation(1))
    if rel.LT():
        return sympy.StrictLessThan(lh, rh, evaluate=False)
    elif rel.LTE():
        return sympy.LessThan(lh, rh, evaluate=False)
    elif rel.GT():
        return sympy.StrictGreaterThan(lh, rh, evaluate=False)
    elif rel.GTE():
        return sympy.GreaterThan(lh, rh, evaluate=False)
    elif rel.EQUAL():
        return sympy.Eq(lh, rh, evaluate=False)
    elif rel.ASSIGNMENT():
        # !Use Global variances
        variances[lh] = rh
        var[str(lh)] = rh
        return rh
    elif rel.UNEQUAL():
        return sympy.Ne(lh, rh, evaluate=False)
예제 #5
0
def get_transfer_functions(t, x_vec, u_vec, equations_of_motion):
    s = sp.symbols('s')

    X_vec = np.array([sp.Function(x.name.capitalize())(s) for x in x_vec[::2]])
    U_vec = np.array([sp.Function(u.name.capitalize())(s) for u in u_vec])

    laplace_tf = {}
    for x, X in zip(x_vec[::2], X_vec):
        laplace_tf[x] = X
        laplace_tf[sp.diff(x)] = s * X
        laplace_tf[sp.diff(x, (t, 2))] = s**2 * X
    for u, U in zip(u_vec, U_vec):
        laplace_tf[u] = U

    laplace_equations = [
        sp.Eq(sp.diff(x, t), eq).subs(laplace_tf)
        for x, eq in zip(x_vec[1::2], equations_of_motion[1::2])
    ]
    result = sp.solve(laplace_equations, list(
        X_vec))  # need to convert to list because sympy doesn't support numpy

    laplace_transforms = [sp.simplify(result[X]) for X in X_vec]
    return s, X_vec, U_vec, laplace_transforms
 def validator(user_answer):
     try:
         # pass
         user_answer = user_answer.lower()
         user_answer = user_answer.replace(' ', '')
         user_answer = user_answer.replace('f(x)', 'y')
         user_answer = user_answer.replace('^', '**')
         lhs, rhs = user_answer.split('=')
         lhs = parse_expr(lhs, transformations=transformations)
         rhs = parse_expr(rhs, transformations=transformations)
         user_answer = sy.Eq(lhs, rhs)
         y = sy.Symbol('y')
         user_answer = sy.solve(user_answer, y)[0]
         lc = get_coeff(user_answer)
         if lc == 1:
             fmt_lc = ''
         elif lc == -1:
             fmt_lc = '-'
         else:
             fmt_lc = sy.latex(lc)
         expr = user_answer/lc
     except:
         raise SyntaxError
    def __add_terms(self, var, left_side, right_side):

        #Add random x**2 term at both sides
        if random.randint(1, 100) < self.prob_moreterms:
            coeficient = get_random_number(self.maxcoef, [
                0,
            ])
            left_side += coeficient * var**2
            right_side += coeficient * var**2

        #Add random x term at both sides
        if random.randint(1, 100) < self.prob_moreterms:
            coeficient = get_random_number(self.maxcoef, [
                0,
            ])
            left_side += coeficient * var
            right_side += coeficient * var

        #Add random independent term at both sides
        if random.randint(1, 100) < self.prob_moreterms:
            coeficient = get_random_number(self.maxcoef, [
                0,
            ])
            left_side += coeficient
            right_side += coeficient

        #Multiply both side by a number
        if random.randint(1, 100) < self.prob_mult:
            coeficient = get_random_number(self.maxcoef, [
                0,
            ])
            left_side = coeficient * left_side
            right_side = coeficient * right_side

        left_side = sympy.expand(left_side)
        right_side = sympy.expand(right_side)
        return sympy.Eq(left_side, right_side)
def get_transfer_function(hardware_major_version, solve_for=None, Zs=None):
    '''
    Parameters
    ----------
    hardware_major_version : int
        Major version of control board hardware *(1 or 2)*.
    solve_for : str, optional
        Rearrange equality with ``solve_for`` symbol as LHS.
    Zs : list
      List of impedance (i.e., ``Z``) to substitute with resistive and
      capacitive terms.

      By default, all ``Z`` terms are substituted with corresponding ``R`` and
      ``C`` values.

    Returns
    -------
    sympy.Equality
        Feedback measurement circuit symbolic transfer function for specified
        control board hardware version.

    Note
    ----
    This function is memoized, to improve performance for repeated calls with
    the same arguments.
    '''
    xfer_func = z_transfer_functions()[hardware_major_version]
    symbols = OrderedDict([(s.name, s) for s in xfer_func.atoms(sp.Symbol)])
    if Zs is None:
        Zs = [s for s in symbols if s != solve_for and s.startswith('Z')]
    H = rc_transfer_function(xfer_func, Zs)
    if solve_for is None:
        return H
    symbols = OrderedDict([(s.name, s) for s in H.atoms(sp.Symbol)])
    solve_for_symbol = symbols[solve_for]
    solved = sp.Eq(solve_for_symbol, sp.solve(H, solve_for_symbol)[0])
    return solved
예제 #9
0
 def to_explicit_odes(self, skip_output=False):
     amount_funcs = sympy.Matrix(
         [sympy.Function(amt.name)(self.t) for amt in self.amounts])
     derivatives = sympy.Matrix(
         [sympy.Derivative(fn, self.t) for fn in amount_funcs])
     inputs = self.zero_order_inputs
     a = self.compartmental_matrix @ amount_funcs + inputs
     eqs = [sympy.Eq(lhs, rhs) for lhs, rhs in zip(derivatives, a)]
     ics = {}
     output = self.find_output()
     for node in self._g.nodes:
         if skip_output and node == output:
             continue
         if node.dose is not None and isinstance(node.dose, Bolus):
             if node.lag_time:
                 time = node.lag_time
             else:
                 time = 0
             ics[sympy.Function(node.amount.name)(time)] = node.dose.amount
         else:
             ics[sympy.Function(node.amount.name)(0)] = sympy.Integer(0)
     if skip_output:
         eqs = eqs[:-1]
     return eqs, ics
예제 #10
0
    def diff_dynsys(self, k):
        """Compute derivatives of the dynamical system and substitute with ODEs.

		Parameters
		----------
		k : int
			Order of the derivative


		Returns
		-------
		two dimensional list(equations)

		"""
        dynsys = self.ode2dynsys()
        diff = []
        diff_out = [dynsys]
        substitutes = []
        l = len(dynsys)
        idx = 0
        for i in range(l):
            substitutes.append((dynsys[idx].lhs, dynsys[idx].rhs))
            idx += 1
        for i in range(1, k):
            idx = 0
            for j in range(l):
                diff.append(
                    sp.Eq(
                        sp.diff(dynsys[idx].lhs, self.t, i),
                        sp.diff(diff_out[i - 1][idx].rhs,
                                self.t).subs(substitutes),
                    ))
                idx += 1
            diff_out.append(diff)
            diff = []
        return diff_out
예제 #11
0
def getDeviceXY_old(antenna, d):
    x, y = sym.symbols('x,y', real=True)
    eq = sym.Eq((antenna.x - x)**2 + (antenna.y - y)**2, d**2)
    sol = sym.solve((eq), (x, y))
    ra = np.arange(4, 8)
    all_y = []
    for i in range(len(sol)):
        f = sym.lambdify(y, sol[i][0], "numpy")
        all_y = list(set(all_y) | set(f(ra)[~np.isnan(f(ra))]))

    #all_y = [round(num, 5) for num in all_y]
    df = pd.DataFrame(columns=['x', 'y'])
    for i in range(len(sol)):
        for elem in all_y:
            if 0 < elem < 16:
                res = sol[i][0].evalf(subs={y: elem})
                if isinstance(res, sym.Float):
                    if 0 < res < 5:
                        df = df.append({
                            "x": float(res),
                            "y": elem
                        },
                                       ignore_index=True)
    return df
예제 #12
0
    def all_equations(self) -> Set[sympy.Eq]:
        """
        Returns a set of equations for all rules currently found.
        """
        def get_function(comb_class) -> sympy.Function:
            return comb_class.get_function(self.classdb.get_label)

        eqs = set()
        for rule in self.all_rules():
            try:
                eq = rule.get_equation(get_function)
            except NotImplementedError:
                logger.info(
                    "can't find generating function for %s."
                    " The comb class is:\n%s",
                    get_function(rule.comb_class),
                    rule.comb_class,
                )
                eq = sympy.Eq(
                    get_function(rule.comb_class),
                    sympy.Function("NOTIMPLEMENTED")(sympy.var("x")),
                )
            eqs.add(eq)
        return eqs
예제 #13
0
    def construct_eqn(eqn, is_eq, rationalize):
        """ 
        Construct equation with sympy. Rationalize it if flag is set to True. is_eq is True for DAIs and Actions 
        
        NOTE: sympy.sympify(eqn) converts eqn into a type that can be used inside SymPy
        """

        try:
            if is_eq:
                eqn_split = eqn.split('=')
                lhs, rhs = eqn_split[0], eqn_split[1]
                #print (lhs, rhs)
                eqn = sympy.Eq(sympy.sympify(lhs), sympy.sympify(rhs))
            else:
                eqn = sympy.sympify(eqn)
                if type(eqn) is bool:
                    return eqn
        except:
            Session.write("ERROR: Invalid expression.\n")
            return None

        if rationalize:
            eqn = SymEq.rationalize(eqn)
        return eqn
def symbolicSol(fList):

	z = sympy.symbols('z', complex = True)

	string = ''

	for o in range(0, len(fList)):

		if fList[o] > 0:

			string = string + ' + ' + str(fList[o]) + '*z**' + str(o)

		elif fList[o] < 0:

			string = string + ' - ' + str(fList[o])[1:] + '*z**' + str(o)

		else:

			continue

	expr = parse_expr(string)
	sol = sympy.solve(sympy.Eq(expr, 0), domain = sympy.S.Complexes)

	return [s.evalf() for s in sol]
예제 #15
0
    def format(self, form='A y = b', invert=False):
        """Forms can be:
         A y = b
         b = A y
         Ainv b = y
         y = Ainv b

        If `invert` is True, the A matrix is inverted."""

        if form == 'A y = b':
            return expr(sym.Eq(sym.MatMul(self.A, self.y), self.b),
                        evaluate=False)

        elif form == 'b = A y':
            return expr(sym.Eq(self.b, sym.MatMul(self.A, self.y)),
                        evaluate=False)

        elif form in ('y = Ainv b', 'default'):
            if invert:
                return expr(
                    sym.Eq(self.y,
                           sym.MatMul(self.Ainv, self.b),
                           evaluate=False))

            return expr(
                sym.Eq(self.y,
                       sym.MatMul(sym.Pow(self.A, -1), self.b),
                       evaluate=False))

        elif form == 'Ainv b = y':
            if invert:
                return expr(
                    sym.Eq(sym.MatMul(self.Ainv, self.b),
                           self.y,
                           evaluate=False))

            return expr(
                sym.Eq(sym.MatMul(sym.Pow(self.A, -1), self.b),
                       self.y,
                       evaluate=False))
        else:
            raise ValueError('Unknown form %s' % form)
예제 #16
0
def test_F():
    "Hazony example 5.2.2"
    s = symbols('s')

    print("test_F")
    Z = (s**2 + s + 1) / (s**2 + 2 * s + 2)
    print(f"Z: {Z}")

    min_r = (3 - sympy.sqrt(2)) / 4

    Z1 = ratsimp(Z - min_r)
    print(f"Z1: {Z1}")

    #plot_real_part( sympy.lambdify(s, Z1, "numpy"))

    Y1 = ratsimp(1 / Z - 1)
    print(f"Y1: {Y1}")
    C = Cascade.Shunt(1)

    Z2 = ratsimp(1 / Y1 - s)
    print(f"Z2: {Z2}")
    C = C.hit(Cascade.Series(s))

    Y3 = ratsimp(1 / Z2 - s - 1)
    print(f"Y3: {Y3}")

    Ytotal = C.hit(Cascade.Shunt(1).hit(
        Cascade.Shunt(s))).terminate_with_admittance(0)

    assert sympy.Eq(0, ratsimp(1 / Ytotal - Z))
    assert sympy.Eq(1, ratsimp(Ytotal * Z))

    Ytotal = C.hit(Cascade.Shunt(s)).terminate_with_admittance(1)

    assert sympy.Eq(0, ratsimp(1 / Ytotal - Z))
    assert sympy.Eq(1, ratsimp(Ytotal * Z))

    Ytotal = C.terminate_with_admittance(1 + s)

    assert sympy.Eq(0, ratsimp(1 / Ytotal - Z))
    assert sympy.Eq(1, ratsimp(Ytotal * Z))
예제 #17
0
def FocalLossFormulas():
    x, y, gamma = sp.symbols('x y gamma')

    p = sp.exp(x) / (1 + sp.exp(x))
    display(sp.Eq(sp.S('p'), p))

    L_plus = (1 - p)**gamma * sp.log(p)
    L_minus = p**gamma * sp.log(1 - p)

    display(sp.Eq(sp.S('L_plus'), L_plus))
    display(sp.Eq(sp.S('L_minus'), L_minus))

    L = -y * L_plus - (1 - y) * L_minus
    display(sp.Eq(sp.S('L'), L))

    der1 = sp.diff(L, x)
    display(sp.Eq(sp.S('L__der1'), der1))

    der2 = sp.diff(der1, x)
    display(sp.Eq(sp.S('L__der2'), der2))
    return der1, der2
예제 #18
0
    def test_more_equations_than_symbols(self):
        system = EquationsSystem()
        system.add_figure_symbols('figure', ['x1', 'y1', 'x2', 'y2'])

        f_ = system.get_symbols('figure')
        f_x1, f_y1, f_x2, f_y2 = f_['x1'], f_['y1'], f_['x2'], f_['y2']

        values = {'figure': {'x1': 5.0, 'y1': 6.0, 'x2': 10.0, 'y2': 2.0}}

        # Fix start
        fixed_f_1 = [sympy.Eq(f_x1, 0.0), sympy.Eq(f_y1, 0.0)]
        system.add_restriction_equations('fixed_f_1', fixed_f_1)
        result = system.solve(values)
        values['figure'].update(result['figure'])

        # Fix end
        fixed_f_2 = [sympy.Eq(f_x2, 1.0), sympy.Eq(f_y2, 1.0)]
        system.add_restriction_equations('fixed_f_2', fixed_f_2)
        result = system.solve(values)
        values['figure'].update(result['figure'])

        # Try fix incorrect length
        fixed_length_incorrect = [
            sympy.Eq((f_x2 - f_x1)**2 + (f_y2 - f_y1)**2, 10**2)
        ]
        system.add_restriction_equations('fixed_length_incorrect',
                                         fixed_length_incorrect)
        with pytest.raises(MoreEquationsThanSymbolsError):
            system.solve(values)
        system.remove_restriction_equations('fixed_length_incorrect')

        # Try fix correct length
        fixed_length_correct = [
            sympy.Eq((f_x2 - f_x1)**2 + (f_y2 - f_y1)**2, 5**2)
        ]
        system.add_restriction_equations('fixed_length_correct',
                                         fixed_length_correct)
        with pytest.raises(MoreEquationsThanSymbolsError):
            system.solve(values)
        system.remove_restriction_equations('fixed_length_correct')
예제 #19
0
def test_equation_field():
    x, y = sympy.symbols("x y")

    with sympy.evaluate(False):
        test.equation = "3 * x + 5 = 4"
        assert test.equation == sympy.Eq(3 * x + 5, 4)

        test.equation = "3 * x + 5"
        assert test.equation == sympy.Eq(3 * x + 5, 0)

        test.equation = 3 * x + 5
        assert test.equation == sympy.Eq(3 * x + 5, 0)

        test.equation = "2 x + 3 y = y = x + y"
        assert test.equation == (sympy.Eq(2 * x + 3 * y, y), sympy.Eq(y, x + y))

        # If evaluate=True, Eq(1 / x) is False
        test.equation = "1 / x"
        assert test.equation == sympy.Eq(1 / x, 0)

    with pytest.raises(TypeError):
        test.equation = False
    with pytest.raises(ValueError):
        test.equation = "3 x = **"
예제 #20
0
import sympy

tempprom = 37
tempamb = 15
temphdesp = 33.9
tempinit = 34.5

t, k = sympy.symbols('t k')
y = sympy.Function('y')

f = k * (y(t) - tempamb)
sympy.Eq(y(t).diff(t), f)

edo_sol = sympy.dsolve(y(t).diff(t) - f)

ics = {y(0): tempinit}

C_eq = sympy.Eq(edo_sol.lhs.subs(t, 0).subs(ics), edo_sol.rhs.subs(t, 0))

C = sympy.solve(C_eq)[0]

eq = sympy.Eq(y(t), C * sympy.E**(k * t) + tempamb)

ics = {y(1): temphdesp}
k_eq = sympy.Eq(eq.lhs.subs(t, 1).subs(ics), eq.rhs.subs(t, 1))
kn = round(sympy.solve(k_eq)[0], 4)

hmuerte = sympy.Eq(tempprom, C * sympy.E**(kn * t) + tempamb)

t = round(sympy.solve(hmuerte)[0], 2)
예제 #21
0
#This labels all the "nodes" in the system.  Each node is a sympy variable that will be solved

#Variables to be used in the calculation.
x, y, f = sym.symbols('x y f')
x0, y0, y1, x1, phi0, phix, phiy = sym.symbols(
    'x_0 y_0 y_1 x_1 phi_0 phi_x phi_y')
phixx, phiyy = sym.symbols('phi_xx phi_yy')
x2, y2 = sym.symbols('x2 y2')

trial_function = (1 - x**2) * (1 - y**2)

#2. Set up The Element Parameters

ax, bx, ay, by, c = sym.symbols('a_x b_x a_y b_y c')
#This creates the template element by approximating it as a plane.
eq1 = sym.Eq(phi0, ax * x0**2 + bx * x0 + ay * y0**2 + by * y0 + c)
eq2 = sym.Eq(phix, ax * x1**2 + bx * x1 + ay * y0**2 + by * y0 + c)
eq3 = sym.Eq(phixx, ax * x2**2 + bx * x2 + ay * y0**2 + by * y0 + c)
eq4 = sym.Eq(phiy, ax * x0**2 + bx * x0 + ay * y1**2 + by * y1 + c)
eq5 = sym.Eq(phiyy, ax * x0**2 + bx * x0 + ay * y2**2 + by * y2 + c)
result = sym.nonlinsolve([eq1, eq2, eq3, eq4, eq5], [ax, ay, bx, by, c])

# print(sym.latex(result))
phi_final = result.args[0][0] * x**2 + result.args[0][1] * y**2 + result.args[
    0][2] * x + result.args[0][3] * y + result.args[0][4]

phi_solve_vars = [phi0, phix, phixx, phiy, phiyy]

phi_poly = sym.Poly(phi_final, phi_solve_vars)

# print(sym.latex(phi_poly.as_expr()))
예제 #22
0
#!/usr/bin/python3

import sympy as sym

a,b,c = sym.symbols("a b c")
x = sym.Symbol("x")
eq = sym.Eq(a * x**2 + b * x + c)

print(eq)

roots = sym.solve(eq, x)

print(roots)
예제 #23
0
# importando modulos necesarios
import matplotlib

import matplotlib.pyplot as plt
import numpy as np
import sympy
from scipy import integrate

# imprimir con notación matemática.
sympy.init_printing(use_latex='mathjax')

x = sympy.Symbol('x')
y = sympy.Function('y')

# definiendo la ecuación
eq = 1

# Condición inicial
ics = {y(2): 1}

# Resolviendo la ecuación
edo_sol = sympy.dsolve(y(x).diff(x) - eq)
edo_sol

# Sustituyendo condiciones iniciales
C_eq = sympy.Eq(edo_sol.lhs.subs(x, 0).subs(ics), edo_sol.rhs.subs(x, 0))
C_eq

sympy.solve(C_eq)
예제 #24
0
# %%

N_t

theta_t

# %%

#sp.series(theta_t, x=N, x0=1, n=3)

print(sp.latex(sp.series(N_t, x=theta, x0=0, n=5)))

# %%

x = sp.symbols('x')

sp.series(sp.sqrt(1-x), x=x, x0=0, n=4)

# %%

i = 1.336
g = 2.689e-5
print((i-1)/2/g/i)

# %%

%matplotlib qt
sp.plot_implicit(sp.Eq((index-1)/gamma/index/2, 5000), (index, 1, 2), (gamma, 2e-5, 4e-5))
w
예제 #25
0
c = complex(-0.7, 0.27015)


def f(z, c):
    try:
        num = 1
        den = 1 - npy.cos(0.1 * z)**2
        f = num / den + c
    except (OverflowError, ZeroDivisionError):
        f = 100 + c
    return f


# Converting to latex
exp = sym.Eq(FZ, (1) / (1 - sym.cos(Z)**2) + C)

# Write the latex expression to file
sym.preview(exp, viewer='file', filename='latex.png')

perdone = 0
# Draw the set
for x in range(w):
    # Progress
    if ((x / w) * 100) > perdone:
        print(perdone, '% completed')
        if (perdone % 10 == 0):
            print('Elapsed time: ', round(time.time() - start_time), 'seconds')
        bitmap.convert("RGB").save(
            'C:/Users/qntmn/OneDrive/Python/Fractals/Progress/CurrentProgress'
            + str(perdone) + '.png')
예제 #26
0
#plot_1.extend(plot_2)

#plot_1.show()

expression_1 = sp.sin(sp.sin(2 * x + y)) - 1.6 * x
expression_2 = x**2 + 2 * y**2 - 1

function_1 = sp.lambdify((x, y), expression_1, 'numpy')
function_2 = sp.lambdify((x, y), expression_2, 'numpy')

a_x = -1
b_x = 1
a_y = -1
b_y = 1

plot_1 = sp.plotting.plot_implicit(sp.Eq(expression_1, 0), (x, a_x, b_x),
                                   (y, a_y, b_y))
plot_2 = sp.plotting.plot_implicit(sp.Eq(expression_2, 0), (x, a_x, b_x),
                                   (y, a_y, b_y))
plot_1.extend(plot_2)

plot_1.show()

x_0 = -0.6
y_0 = -0.8


def jacobian(expression_1, expression_2, x_0, y_0):
    x, y = sp.symbols('x y')
    j = np.empty((2, 2), dtype=float)
    j[0][0] = sp.diff(expression_1, x).subs([(x, x_0), (y, y_0)]).evalf()
예제 #27
0
# %%

import sympy as sp

x3, y3, z3, x2, y2, z2 = sp.symbols('x3 y3 z3 x2 y2 z2', real=True)
E, Em = sp.symbols('E Em', real=True, positive=True)

# %%

eq = sp.Eq(
    Em,
    E + sp.sqrt(x3**2 + y3**2 + (-E - z2)**2) + sp.sqrt(x2**2 + y2**2 + z2**2))

# %%

from sympy import S
sols = sp.solve(eq, z2, domain=S.Reals)

# %%

vect = sp.Matrix([
    E, x2, y2,
    sp.simplify(sols[0].subs(x3, -x2).subs(y3, -y2)), -x2, -y2,
    -E - sp.simplify(sols[0].subs(x3, -x2).subs(y3, -y2))
])
coords = [E, x2, y2]


def numerical_vect(Enum, x2num, y2num, Emaxnum=1):
    z2num = sols[0].subs(x3, -x2).subs(y3,
                                       -y2).subs(E, Enum).subs(x2, x2num).subs(
예제 #28
0
h = h_0 + t

objective = (alpha.T * h - t.T * C * t)[0, 0]
constraint = sy.simplify(sy.expand((h.T * V * h)[0, 0]))
utility = sy.simplify(objective - lam * constraint)
print_expression("utility", utility)
diff_system = [
    sy.simplify(sy.diff(utility, t_0)),
    sy.simplify(sy.diff(utility, t_1))
]
print_expression("system", diff_system)
t_solutions = sy.linsolve(diff_system, [t_0, t_1])

# Prepare a 4 degree polynome solution
a_0, a_1, a_2, a_3, a_4 = sy.symbols("a_0 a_1 a_2 a_3 a_4")
eq = sy.Eq(
    a_4 * (lam**4) + a_3 * (lam**3) + a_2 * (lam**2) + a_1 * (lam**1) + a_0, 0)
# TODO: do only real numbers sy.Reals (raises an excception now when evaluating objective)
polynome_solutions = sy.solveset(eq, lam)
eq = eq.subs([(a_4, 1), (a_3, 0), (a_2, 0), (a_1, 0), (a_0, -1)])
print_expression("eq",
                 eq.subs([(a_4, 1), (a_3, 0), (a_2, 0), (a_1, 0), (a_0, -1)]))
print_expression("polynome_solutions", polynome_solutions)

candidates = []
max_objective_result = None

for sol in t_solutions:
    sol_vector = sy.Matrix([[sy.simplify(sol[0])], [sy.simplify(sol[1])]])
    print_expression("t solution", sol_vector)
    variance = sy.simplify((sol_vector.T * V * sol_vector)[0, 0])
    print_expression("variance", variance)
예제 #29
0
파일: sympy_tests.py 프로젝트: zea2/qupulse
 def assertEqual1(self, first, second, msg=None):
     if sympy.Eq(first, second):
         return
     raise self.failureException(msg=msg)
예제 #30
0
C1, C2, C3, C4 = sp.symbols('C1, C2, C3, C4')  # Constantes de integración

q = 0

# %%Se calcula la matrix de rigidez
K = sp.zeros(4)

V = sp.integrate(q, x) + C1  # se integran las ec. diferenciales
M = sp.integrate(V, x) + C2  # de la viga de Euler-Bernoulli
t = (sp.integrate(M, x) + C3) / EI
w = sp.integrate(t, x) + C4
for i in range(4):

    sol = sp.solve(
        [
            sp.Eq(w.subs(x, 0), int(i == 0)),  # Condiciones de frontera
            sp.Eq(t.subs(x, 0), int(i == 1)),
            sp.Eq(w.subs(x, L), int(i == 2)),
            sp.Eq(t.subs(x, L), int(i == 3))
        ],
        [C1, C2, C3, C4])

    constantes = [(C1, sol[C1]), (C2, sol[C2]), (C3, sol[C3]), (C4, sol[C4])]

    K[:, i] = [
        +V.subs(constantes).subs(x, 0),  # Y1  se evaluan las
        -M.subs(constantes).subs(x, 0),  # M1  reacciones verticales
        -V.subs(constantes).subs(x, L),  # Y2  y los momentos en los
        +M.subs(constantes).subs(x, L)
    ]  # M2  apoyos