Ejemplo n.º 1
0
def get_expressions():
    """
    Create symoblic expressions for the system.

    Returns:
        Expressions for theta_dd_1 and theta_dd_2.
    """

    s = 'l_1 theta_dd_1 m_1 m_2 l_2 theta_dd_2 theta_1 theta_2 theta_d_2 theta_d_1 g'
    l_1, theta_dd_1, m_1, m_2, l_2, theta_dd_2, theta_1, theta_2, theta_d_2, theta_d_1, g = sympy.symbols(s)
    expr1 = l_1 * theta_dd_1 * (m_1 + m_2) + m_2 * l_2 * (theta_dd_2 * sympy.cos(theta_1 - theta_2) + theta_d_2 ** 2 * sympy.sin(theta_1 - theta_2)) + (m_1 + m_2) * g * sympy.sin(theta_1)
    expr2 = m_2 * l_2 * theta_dd_2 + m_2 * l_1 * (theta_dd_1 * sympy.cos(theta_1 - theta_2) - theta_d_1 ** 2 * sympy.sin(theta_1 - theta_2)) + m_2 * g * sympy.sin(theta_2)
    theta_dd_1_expr = sympy.solveset(expr1, theta_dd_1).args[0]
    theta_dd_2_eval = sympy.solveset(expr2.subs(theta_dd_1, theta_dd_1_expr), theta_dd_2).args[0]
    theta_dd_2_expr = sympy.solveset(expr2, theta_dd_2).args[0]
    theta_dd_1_eval = sympy.solveset(expr1.subs(theta_dd_2, theta_dd_2_expr), theta_dd_1).args[0]

    res1 = sympy.simplify(theta_dd_1_eval)
    res2 = sympy.simplify(theta_dd_2_eval)

    sympy.init_printing()

    print(res1, res2, sep='\n\n')

    return res1, res2
Ejemplo n.º 2
0
    def eval(cls, *args):
        assert len(args) in cls.nargs

        depen = args[:]
        indep = None

        while len(depen) > 0:
            search = []

            for var in depen:
                if isinstance(var, Symbol):
                    indep = var
                    search = []
                    break
                elif isinstance(var, Real):
                    continue
                else:
                    search.extend(var.args)

            depen = search

        if indep is not None:
            res = solveset(cls._relation(*args), indep, domain=S.Reals)
        else:
            res = solveset(cls._relation(*args), domain=S.Reals)

        if isinstance(res, EmptySet):
            return S.Zero
        else:
            return S.One
Ejemplo n.º 3
0
def StrTabVarSimple(classe):
    u = rd.randint(0, 2)
    if classe == "Seconde":
        u = -1
        v = rd.randint(0, 2)
    if u == -1:
        if v == 0:
            A = IdRemarq()
            S1 = StrFexpr(A)
            expr = A
        if v == 1:
            A = racinepib() * AxPb()
            S1 = StrFexpr(A)
            expr = A
        if v == 2:
            A = IdRemarq()
            expr = sp.sqrt(A)
            S1 = StrFexpr(expr)
            deriv = sp.diff(expr, x)
            [a, b] = fraction(deriv)
            resultat = solveset(a >= 0, domain=S.Reals)
    if u == 0:
        expr = AxPbCarreDur() + sgnnbre() + AxPb()
        S1 = StrFexpr(expr)
    if u == 1:
        expr = AxPb() * AxPb()
        S1 = StrFexpr(expr)
    if u == 2:
        expr = AxPbCubeDur()
        S1 = StrFexpr(expr)
    if (u != -1 or v != 2):
        deriv = sp.diff(expr, x)
        resultat = solveset(deriv >= 0, domain=S.Reals)
    return [S1, sp.latex(resultat), sp.latex(deriv)]
Ejemplo n.º 4
0
def hello_world():
    x, y = symbols('x y')
    eq1, eq2 = getSimpleEq2(x, y)
    res: FiniteSet = solve(eq1, eq2, x, y)

    val_x = tuple(res)[0][0]
    val_y = tuple(res)[0][1]

    eq = mml('<mfenced open="{" close=""><mtable>' +
             mathml(eq1, printer="presentation") +
             mathml(eq2, printer="presentation") +
             "</mtable></mfenced>")

    sol1 = solveset(eq1, x)
    sol1f = tuple(sol1)[0] or 1
    int1 = 0

    sol2 = solveset(eq2, y)
    sol2f = tuple(sol2)[0] or 1
    int2 = 0

    return render_template('2eq.html', eq=eq,
    					   eq1=str(sol1f),
    					   eq2=str(sol2f),
    					   int1=int1,
    					   int2=int2,
                           val_x=show_val(val_x),
                           val_y=show_val(val_y))
Ejemplo n.º 5
0
 def solve_function(self):
     """
     O metodo determina a solucao da funcao
     """
     #http://docs.sympy.org/latest/modules/solvers/solvers.html
     #http://docs.sympy.org/latest/modules/solvers/solveset.html
     try:
         funcao = self.string_function % (self.dic_coefficients)
         self.solve = solveset(funcao, x)
         self.solve_real = solveset(funcao, x, domain=S.Reals)
     except Exception as error:
         print('Function Error: ', error)
Ejemplo n.º 6
0
 def FaireCorrection(self):
     if self.type == "D\\'eveloppement":
         self.corr = self.expr.expand()
     if self.type == "In\\'equation":
         self.corr = solveset(self.res >= 0, domain=S.Reals)
     if self.type == "Equation":
         self.corr = solveset(self.expr, domain=S.Reals)
     if self.type == "Tableaux de Variation":
         self.der = sp.together(
             sp.expand(sp.together(sp.diff(self.expr, x))))
         self.Df = solveset(self.CheckDomaine >= 0, domain=S.Reals)
         [a, b] = fraction(self.der)
         self.res = solveset(a >= 0, domain=self.Df)
Ejemplo n.º 7
0
def StrTabVarDur(classe):
    u = rd.randint(0, 2)
    if classe == "Seconde":
        u = 0
    if classe == "Terminale":
        u = rd.randint(3, 4)
        v = rd.randint(0, 2)
    if u == 0:
        expr = racine() * AxPbCubeDur()
        if classe == "Seconde":
            a = rd.randint(1, 9) * racinepib()
            b = rd.randint(1, 8) * racinepib()
            expr = (a * x + b)**3
        S1 = StrFexpr(expr)
    if u == 1:
        expr = AxPb() * racine() * AxPbCarreDur()
        S1 = StrFexpr(expr)
    if u == 2:
        expr = AxPbCarreDur() / AxPb()
        S1 = StrFexpr(expr)
    if u == 3:  # Exponentielle
        if v == 0:
            expr = sp.exp(AxPbCarre() / AxPb())
            [S1, deriv, resultat] = AnalyseExpo(expr)
        if v == 1:
            expr = sp.exp(AxPb() * racinepib() * AxPbCarreDur())
            [S1, deriv, resultat] = AnalyseExpo(expr)
        if v == 2:
            expr = AxPb() * sp.exp(AxPb())
            [S1, deriv, resultat] = AnalyseExpo(expr)
    if u == 4:  # Logarithme
        if v == 0:
            A = AxPbCarre() / AxPb()
            Df = sp.solveset(A > 0, domain=S.Reals)
            expr = sp.ln(A)
            [S1, deriv, resultat] = AnalyseLog(expr, Df)
        if v == 1:
            A = AxPb()
            expr = AxPbCube() + sp.ln(A)
            Df = sp.solveset(A > 0, domain=S.Reals)
            [S1, deriv, resultat] = AnalyseLog(expr, Df)
        if v == 2:
            A = AxPb()
            expr = sp.ln(A) / A
            Df = sp.solveset(A > 0, domain=S.Reals)
            [S1, deriv, resultat] = AnalyseLog(expr, Df)
    if classe != "Terminale":
        deriv = sp.diff(expr, x)
        resultat = solveset(deriv >= 0, domain=S.Reals)
    return [S1, sp.latex(resultat), sp.latex(deriv)]
Ejemplo n.º 8
0
    def plot_vecfield(
        self,
        sp=None,
        small_v=False,
        S=1.0,
        norm_mag=True,
        idx_x=0,
        idx_y=1,
    ):
        # assume that stimulation is stim_func evaluated at 0
        I_app = self.stim_func(0)

        # assert that the model has only two variables
        if self.sys_N != 2:
            raise Exception(
                'Invalid model! need two dimensions to plot vector field')

        if sp is None:
            sp = (np.arange(-100, 100, 10), np.arange(-100, 100, 10))

        # creating grid
        (X, Y) = np.meshgrid(*sp)

        # vector valued fctn
        u = self.model_funcs[idx_x](X, Y, I_app)
        v = self.model_funcs[idx_y](Y, Y, I_app)

        # magnitude
        r = np.sqrt(u**2.0 + v**2.0)
        # normalization of u,v
        u = u / r
        v = v / r
        # r = np.full(len(r), 1)
        if norm_mag:
            r = r / r

        # plot nullclines
        nlc_expr_X = sym.solveset(self.model_exprs[idx_x],
                                  self.lst_vars[idx_y])
        nlc_expr_Y = sym.solveset(self.model_exprs[idx_y],
                                  self.lst_vars[idx_y])

        nlc_func_X = sym.lambdify(nlc_expr_X)
        nlc_func_Y = sym.lambdify(nlc_expr_Y)

        plt.plot(sp[0], nlc_func_X(sp[0]), 'b-')
        plt.plot(sp[1], nlc_func_Y(sp[1]), 'b-')

        plt.quiver(X, Y, u, v, r, pivot="mid")
Ejemplo n.º 9
0
def solveset_it(expression, solve_for, equals_to=0):
    '''
    Syntax for solveset:
    sympy.solveset(sympy.Eq(expression,equals_to, solve_for, domain=S.Complexes)
    or
    if expr = expression - equals_to:
    sympy.solveset(expr,solve_for,domain=S.Reals)
    
    or simply:
    sympy.solveset(expr,solve_for)
    '''
    if equals_to == 0:
        return solveset(expression, solve_for)
    else:
        return solveset(Eq(expression, equals_to), solve_for)
Ejemplo n.º 10
0
def calcSumA1():
    while True:
        try:
            snIn = input("Sn = ")
            nIn = input("n = ")
            rIn = input("r = ")
            expr = (Sn * (1 - r)) / (1 - (r**n)) - A1
            expr = expr.subs(Sn, snIn)
            expr = expr.subs(n, nIn)
            expr = expr.subs(r, rIn)
            expr = solveset(expr, A1)
            print("\nResults:")
            print("A1 = ",
                  snIn,
                  " * (1 -",
                  rIn,
                  ") / (1 - (",
                  rIn,
                  "**",
                  nIn,
                  "))",
                  sep='')
            print("A1 =", str(expr))
            closer = str(
                input("\nEnter 1 to exit.\n"
                      "Press any key to continue.\n"))
            if (closer == '1'):
                return
        except:
            print("Invalid Character")
Ejemplo n.º 11
0
def solve(equation):
    x = symbols('X')
    solutions = solveset(equation, x, domain=S.Reals).evalf()
    if isinstance(solutions, Interval):
        return 0
    else:
        return list(solutions)[0]
    def __init__(self,start,end,gama,delta,formula=lineType[0]): 
        self.formula=formula
#       delta应力
        self.delta=delta
        #gama 比载
        self.gama=gama
        self.h=end.z-start.z
        self.theta_y=math.atan((start.y-end.y)/(end.x-start.x))
        #L悬链线在2D情况下的实际x轴长度
        self.L=(end.x-start.x)/math.cos(self.theta_y)
        #Lv悬链线在xoz平面投影的x轴长度
        self.Lv=(end.x-start.x)
        self.t=self.delta/self.gama
        #beta用于斜抛线方程
        self.beta=math.atan(self.h/self.L)
##        self.Loa2=self.L/2-delta/gama*math.sin(self.beta)
        #Loa真实长度
        if self.formula=="Catenary":
            #利用公式解Loa     
            x=Symbol('x')
            ans=solveset(sh(x)-self.h/2/self.t/sh(self.L/2/self.t),domain=S.Reals) 
            self.Loa=self.L/2-self.t*ans.args[0]         
            # self.Loa=(self.L/2-(self.t)*sh(self.h/2/self.t/sh(self.L/2/self.t)))
        if self.formula=="Parabola":
            self.Loa=self.L/2-self.delta/self.gama*math.sin(self.beta)
        print('Loa: ',self.Loa)
##        print('Loa2:',self.Loa2)
        #Arch_y架构侧点的y坐标,用于calculat_yzs函数
        self.Arch_y=start.y
Ejemplo n.º 13
0
def evaluate(c, N, P):
    solutions, x = sp.symbols("solutions x")
    str_expr = get_equations_in_str(c, N, P)
    expr = sp.sympify(str_expr)
    solutions = sp.solveset(sp.Eq(expr), x)

    return solutions
Ejemplo n.º 14
0
def curve_normalize(old_curve: ParametricCurve, new_var=Symbol('s',
                                                               real=True)):
    from sympy import S, solveset, Eq
    from sympy import integrate
    from silkpy.sympy_utility import norm

    drdt = norm(old_curve.exprs.diff(old_curve.sym(0)))
    new_var_in_old = integrate(drdt, old_curve.sym(0)).simplify()
    solset = solveset(Eq(new_var, new_var_in_old),
                      old_curve.sym(0),
                      domain=S.Reals).simplify()
    try:
        if len(solset) != 1:
            raise RuntimeError(
                f"We have not yet succedded in inverse s(t) into t(s).\
            It found these solutions: {solset}.\
            Users need to choose from them or deduce manually, and then set it by obj.param_norm(s_symbol, t_expressed_by_s"
            )
    except:
        raise RuntimeError(
            f"We have not yet succedded in inverse s(t) into t(s). Try the curve_param_transform function instead and set the transform relation manually."
        )
    else:
        old_var_in_new = next(iter(solset))
    return ParametricCurve((new_var,
                            new_var_in_old.subs(old_curve.sym(0),
                                                old_curve.sym_limit(0)[0]),
                            new_var_in_old.subs(old_curve.sym(0),
                                                old_curve.sym_limit(0)[1])),
                           old_curve.exprs.subs(old_curve.sym(0),
                                                old_var_in_new))
Ejemplo n.º 15
0
def MENUMODE(questionType):
    expr = questionType
    print(sympy.latex(expr))
    ANS = sympy.solveset(expr)
    print(
        "1 is add, 2 is subtract, 3 is add multiples of X, and 4 is subtract multiples of X, 5 and 6 are divide and multiply, and 7 is to solve"
    )
    CHOICE = int(input())
    if CHOICE == 1:
        n = ADD(expr)
        MENUMODE(n)
    elif CHOICE == 2:
        n = SUBTRACT(expr)
        MENUMODE(n)
    elif CHOICE == 3:
        n = ADDX(expr)
        MENUMODE(n)
    elif CHOICE == 4:
        n = SUBTRACTX(expr)
        MENUMODE(n)
    elif CHOICE == 5:
        n = Divide(expr)
        MENUMODE(n)
    elif CHOICE == 6:
        n = Multiply(expr)
        MENUMODE(n)
    elif CHOICE == 7:
        ANSWER(expr)
Ejemplo n.º 16
0
def remove_nonzero_factors(eqn, reduce_monomials=False, atom_bounds=None):
    if eqn == 0:
        return eqn
    result = 1
    domains = {}
    for atom in [a for a in eqn.atoms() if a.is_symbol]:
        if atom_bounds and atom in atom_bounds:
            domains[atom] = sp.Interval(*atom_bounds[atom])
        else:
            domains[atom] = sp.Reals

    for factor in sp.factor(sp.cancel(eqn)).args:
        if isinstance(factor, sp.Pow) and factor.args[1] < 0:
            continue
        if reduce_monomials:
            atoms = [a for a in factor.atoms() if a.is_symbol]
            if len(atoms) == 1:
                a, = atoms
                solve_set = sp.solveset(factor, domain=domains[a])
                if not solve_set:
                    continue

        result *= factor

    return result
Ejemplo n.º 17
0
def calcDefr2():
    while True:
        try:
            anIn = input("An = ")
            a1In = input("A1 = ")
            nIn = int(input("n = "))
            expr = (An / A1)**(1 / (n - 1)) - r
            expr = expr.subs(An, anIn)
            expr = expr.subs(A1, a1In)
            expr = expr.subs(n, nIn)
            expr = solveset(expr, r)
            print("\nResults:")
            print("r = (",
                  anIn,
                  " / ",
                  a1In,
                  ")**(1 / (",
                  nIn,
                  " - 1))",
                  sep='')
            print("r =", str(expr))
            closer = str(
                input("\nEnter 1 to exit.\n"
                      "Press any key to continue.\n"))
            if (closer == '1'):
                return
        except:
            print("Invalid Character")
Ejemplo n.º 18
0
def integral_func(expre1, expre2):

    expre = '{}-({})'.format(expre1, expre2)
    a_b = solveset(Eq(expre, 0), x)
    result = integrate(expre1, (x, *a_b)) - integrate(expre2, (x, *a_b))

    return result
Ejemplo n.º 19
0
 def twin_function_expr(self, value):
     if not value:
         self.twin_function = None
         self.twin_inverse_function = None
         self._twin_function_expr = ""
         self._twin_inverse_sympy = None
         return
     expr = sympy.sympify(value)
     if len(expr.free_symbols) > 1:
         raise ValueError("The expression must contain only one variable.")
     elif len(expr.free_symbols) == 0:
         raise ValueError("The expression must contain one variable, "
                          "it contains none.")
     x = tuple(expr.free_symbols)[0]
     self.twin_function = lambdify(x, expr.evalf())
     self._twin_function_expr = value
     if not self.twin_inverse_function:
         y = sympy.Symbol(x.name + "2")
         try:
             inv = sympy.solveset(sympy.Eq(y, expr), x)
             self._twin_inverse_sympy = lambdify(y, inv)
             self._twin_inverse_function = None
         except BaseException:
             # Not all may have a suitable solution.
             self._twin_inverse_function = None
             self._twin_inverse_sympy = None
             _logger.warning(
                 "The function {} is not invertible. Setting the value of "
                 "{} will raise an AttributeError unless you set manually "
                 "``twin_inverse_function_expr``. Otherwise, set the "
                 "value of its twin parameter instead.".format(value, self))
Ejemplo n.º 20
0
def symbol_calc_fz_jac_square_taylor(n):

    fx1sq, v = symbol_calc_2d_taylor(n, x_taylor="x1sq", order=3, x1_neg=True, slope="slope", Iext1="Iext1")[1:]
    fx1sq = fx1sq.tolist()

    fz, vz = symbol_eqtn_fz(n, zmode=array("lin"), z_pos=True, model="2d")[1:]
    fz = fz.tolist()
    v.update(vz)
    del vz

    x1 = []
    #dfx1z = []
    for iv in range(n):
        x1.append(list(solveset(fx1sq[iv], v["x1"][iv]))[0])
        #dfx1z.append(x1[iv].diff(v["z"][iv]))

    for iv in range(n):
        for jv in range(n):
            fz[iv] = fz[iv].subs(v["x1"][jv], x1[jv])

    fz_jac = Matrix(fz).jacobian(Matrix([v["z"]]))

    # for iv in range(n):
    #     for jv in range(n):
    #         fz_jac[iv, jv].simplify().collect(dfx1z[jv])

    fz_jac = Array(fz_jac)

    fz_jac_lambda = lambdify([v["z"], v["y1"], v["Iext1"], v["K"], v["w"], v["a"], v["b"], v["tau1"], v["tau0"],
                              v["x_taylor"]], fz_jac, 'numpy')

    return fz_jac_lambda, fz_jac, v
Ejemplo n.º 21
0
def gm2_strategy(kurtosis, b=2):
    '''Use sympy to solve for "a" in Proposition 2 numerically.
    >>> round( gm2_strategy(7, 2), 4 )
    0.7454
    '''
    #  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 :-)
        system.die("Extreme kurtosis: argument b should be increased.")
        #     ^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
Ejemplo n.º 22
0
def solver_rate_from_compounded_df(dis_factor, daycount_factors):
    rate = sy.Symbol('rate')
    fv = sy.Symbol('fv')
    #df = sy.Symbol('df')
    dcfs = daycount_factors
    #df = dis_factor

    for d in range(len(dcfs)):
        if d == 0:

            fv = (1 + (rate * 0.01 * dcfs[d]))
        else:
            fv = fv * (1 + (rate * 0.01 * dcfs[d]))

    fv = dis_factor * fv - 1
    #solved_rates = sy.solve(fv,rate)
    solved_rates = sy.solveset(fv, rate, domain=sy.S.Reals)
    new_rates = []
    #print('solved_rates==> ',solved_rates, type(solved_rates),list(solved_rates))
    solved_rates = list(solved_rates)
    for i in range(len(solved_rates)):
        try:
            float(solved_rates[i])
        except:
            continue
        new_rates.append(solved_rates[i])

    new_rates = list(filter(lambda x: x > 0, new_rates))
    return new_rates
Ejemplo n.º 23
0
def sympy_solver(expr):
    # Sympy is buggy and slow.  Use Transforms.
    symbols = get_symbols(expr)
    if len(symbols) != 1:
        raise ValueError('Expression "%s" needs exactly one symbol.' %
                         (expr, ))

    if isinstance(expr, Relational):
        result = sympy.solveset(expr, domain=sympy.Reals)
    elif isinstance(expr, sympy.Or):
        subexprs = expr.args
        intervals = [sympy_solver(e) for e in subexprs]
        result = sympy.Union(*intervals)
    elif isinstance(expr, sympy.And):
        subexprs = expr.args
        intervals = [sympy_solver(e) for e in subexprs]
        result = sympy.Intersection(*intervals)
    elif isinstance(expr, sympy.Not):
        (notexpr, ) = expr.args
        interval = sympy_solver(notexpr)
        result = interval.complement(sympy.Reals)
    else:
        raise ValueError('Expression "%s" has unknown type.' % (expr, ))

    if isinstance(result, sympy.ConditionSet):
        raise ValueError('Expression "%s" is not invertible.' % (expr, ))

    return result
Ejemplo n.º 24
0
def calcDefr():
    while True:
        try:
            an1In = input("An1 = ")
            an2In = input("An2 = ")
            n1In = int(input("n1 = "))
            n2In = int(input("n2 = "))
            nIn = n1In - n2In
            expr = (An1 / An2)**(1 / n) - (r**n)**(1 / n)
            expr = expr.subs(An1, an1In)
            expr = expr.subs(An2, an2In)
            expr = expr.subs(n, nIn)
            print("\nResults: Restart or press Ctrl+C if taking too long")
            expr = solveset(expr, r)
            print("r^(1/",
                  nIn,
                  ") = (",
                  an1In,
                  " / ",
                  an2In,
                  ")^(1/",
                  nIn,
                  ")",
                  sep='')
            print("r =", str(expr))
            closer = str(
                input("\nEnter 1 to exit.\n"
                      "Press any key to continue.\n"))
            if (closer == '1'):
                return
        except:
            print("Invalid Character")
Ejemplo n.º 25
0
def sympy_can_colide(a, b):
    ap, av, aa = a
    bp, bv, ba = b

    t = sympy.symbols('t', integer=True)

    a_exs = [
        p + v * t + (a * t * (t + 1)) / 2 for (p, v, a) in zip(ap, av, aa)
    ]
    b_exs = [
        p + v * t + (a * t * (t + 1)) / 2 for (p, v, a) in zip(bp, bv, ba)
    ]
    # exs = [sympy.Eq(ax, bx) for ax, bx in zip(a_exs, b_exs)]
    # print(sympy.solveset(exs, t, domain=sympy.S.Integers))

    doms = []
    dom = sympy.Integers
    for ax, bx in zip(a_exs, b_exs):
        w = sympy.Eq(ax, bx)
        sl = sympy.solveset(w, t, domain=sympy.S.Integers)
        dom = dom.intersect(sl)

        if dom == sympy.EmptySet:
            return None

    if dom != sympy.EmptySet:
        # print(a)
        # print(b)
        # print(dom)
        return dom

    return None
Ejemplo n.º 26
0
 def twin_function_expr(self, value):
     if not value:
         self.twin_function = None
         self.twin_inverse_function = None
         self._twin_function_expr = ""
         self._twin_inverse_sympy = None
         return
     expr = sympy.sympify(value)
     if len(expr.free_symbols) > 1:
         raise ValueError("The expression must contain only one variable.")
     elif len(expr.free_symbols) == 0:
         raise ValueError("The expression must contain one variable, "
                          "it contains none.")
     x = tuple(expr.free_symbols)[0]
     self.twin_function = lambdify(x, expr.evalf())
     self._twin_function_expr = value
     if not self.twin_inverse_function:
         y = sympy.Symbol(x.name + "2")
         try:
             inv = sympy.solveset(sympy.Eq(y, expr), x)
             self._twin_inverse_sympy = lambdify(y, inv)
             self._twin_inverse_function = None
         except BaseException:
             # Not all may have a suitable solution.
             self._twin_inverse_function = None
             self._twin_inverse_sympy = None
             _logger.warning(
                 "The function {} is not invertible. Setting the value of "
                 "{} will raise an AttributeError unless you set manually "
                 "``twin_inverse_function_expr``. Otherwise, set the "
                 "value of its twin parameter instead.".format(value, self))
Ejemplo n.º 27
0
def find_solve_with_hybrid_method(func, a, b, x0, eps):
    x_k = x0
    count = 0
    # exact_solution = 0
    i = 0
    solutions = solveset(func)
    # while i < len(solutions):
    #     if a < solutions.args[i] < b:
    #        exact_solution = solutions.args[i]
    #    i += 1
    while True:
        x_k1 = x_k - (func.subs(x, x_k)) / ((diff(func, x)).subs(x, x_k))
        while True:
            count += 1
            if abs(func.subs(x, x_k1)) < abs(func.subs(x, x_k)):
                break
            else:
                x_k_temp = x_k
                x_k = x_k1
                x_k1 = (x_k1 + x_k_temp) / 2
        if abs(x_k - x_k1) <= eps:
            break
        x_k = x_k1
    print("ГИБРИДНЫЙ МЕТОД")
    print("Найденный корень x* = " + str(x_k1))
    print("Невязка f(x*) = " + str(func.subs(x, x_k1)))
    print("Кол-во итераций = " + str(count))
Ejemplo n.º 28
0
def eq_solver():
    #Generate solutions here.
    eq_str = request.args.get('eq', 0)
    if not eq_str:
        return render_template('/projects/eq_solver.html')

    #Simplify expression (if necessary)
    sympy_eq_str = eq_str.replace('^', '**')
    try:
        simplified_expr = str(simplify(sympy_eq_str)).replace('**', '^')
    except:
        simplified_expr = eq_str
    #Calculate zeros + complex solutions
    expr = parse_expr(
        sympy_eq_str,
        transformations=(standard_transformations +
                         (implicit_multiplication_application, )))
    try:
        simplified_expr = str(simplify(expr)).replace('**',
                                                      '^').replace('*', '')
    except:
        simplified_expr = eq_str
    sols = list(solveset(expr, Symbol('x')))
    complex_sols = [complex(sol) for sol in sols if not sol.is_real]
    sols = [float(sol) for sol in sols if sol.is_real]
    return render_template('/projects/eq_solver.html',
                           zeros=sols,
                           complex_sols=complex_sols,
                           eq=simplified_expr,
                           submit="Yes")
Ejemplo n.º 29
0
def test_solveset():
    x = Symbol('x')
    A = Matrix([[x, 2, x * x], [4, 5, x], [x, 8, 9]])

    solns = solve(det(A), x)
    solns_set = list(solveset(det(A), x))

    print(solns)
    print('\n')
    print(solns_set)

    print('\n\n\n')
    print((solns[0]))
    print('\n')
    print((solns_set[0]))

    soln_sub = solns[0].subs(x, 1)
    solnset_sub = solns_set[0].subs(x, 1)

    s1 = soln_sub.evalf()
    s1set = solnset_sub.evalf()

    s2set = solns_set[1].subs(x, 1).evalf()

    print(s1)
    print(s1set)
    print(s2set)
Ejemplo n.º 30
0
def gm2_strategy(kurtosis, b=2):
    '''Use sympy to solve for "a" in Proposition 2 numerically.
    >>> round( gm2_strategy(7, 2), 4 )
    0.7454
    '''
    #  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 :-)
        system.die("Extreme kurtosis: argument b should be increased.")
        #     ^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
Ejemplo n.º 31
0
 def solve_for(self, sym, expr):
     ss = sy.solveset(expr, sym, domain=sy.S.Reals)
     try:
         ss = list(ss)
     except:
         pass
     return ss
Ejemplo n.º 32
0
 def solve_d_geometric_eqn(self):
     cottheta = sy.symbols('c_theta', real=True, positive=True )
     eq1 = self.raw_d_geometric_eqn(d, u,w,Q,theta).subs(sy.cot(theta),cottheta)
     d_geometric_solns = sy.solveset( eq1, d )
     d_geometric_soln = sy.simplify(d_geometric_solns.args[1].subs(
                                                 cottheta,1/sy.tan(theta)))
     return Eq(d,d_geometric_soln)
Ejemplo n.º 33
0
 def _calc_optimal_C0(self, solution, start, end):
     ret_val = C0
     anal_sol = -1 / x
     if C0 in solution.free_symbols:
         integrand = self._subs_solution(solution)
         # integrand = solution - anal_sol
         integrand *= integrand
         # integrand = integrand.subs({C0: -0.11077})
         squared_residual = integrate(integrand, (x, start, end))
         # print("total error is ", squared_residual)
         # assert False
         det_eq = squared_residual.diff(C0)
         print('squared res is ')
         print(det_eq)
         ans = solveset(det_eq, C0, domain=S.Reals)
         print("C0 opt vals are: ", ans)
         ISR_l = lambdify(C0, squared_residual)
         # print('min error is ', ISR_l(-0.0633790771568749))
         # print('min error is ', ISR_l(-0.313647060539033))
         # print('min error is ', ISR_l(-0.177974008726031))
         assert False
         pass
     else:
         ham_error('HAM_ERROR_CRITICAL', 'CRITICAL__ASSERT_NOT_REACHED')
     return ret_val
Ejemplo n.º 34
0
    def solve(self) -> Tuple[Rational, Rational, Rational]:
        x_expression = list(
            solveset(Eq(self.kernel.dH_dx, 0), self.kernel.x)
        )[0]
        y_expression = list(
            solveset(Eq(self.kernel.dH_dy, 0), self.kernel.y)
        )[0]

        y_expression_without_x = y_expression.subs(
            self.kernel.x, x_expression)
        y_solution = list(
            solveset(
                Eq(y_expression_without_x, self.kernel.y),
                self.kernel.y
            )
        )[0]

        x_solution = x_expression.subs(self.kernel.y, y_solution)

        return x_solution, y_solution, self.kernel.get_value_at_point(
            x_solution,
            y_solution
        )
Ejemplo n.º 35
0
import sympy as sp


if __name__ == "__main__":
    
    x, y, z = sp.symbols("x y z")
    
    """
    [CLS]: 1 element polynomial of 2 degree, 1 equations
    """
    
    roots = sp.solveset(x**2-x,x)
    print type(roots), roots #{0, 1}  ==> <class 'sympy.sets.sets.FiniteSet'>
    
    roots = sp.solveset(x**2 > x**3,x, domain=sp.S.Reals)
    print type(roots), roots #(-oo, 0) U (0, 1) ==> <class 'sympy.sets.sets.Union'>


    """
    [CLS]:3 elements polynomial of 1 degree, 2 equations
    """
    roots = sp.linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))
    print type(roots), roots #{(-y - 1, y, 2)}  ==> <class 'sympy.sets.sets.FiniteSet'>
    
    
    """
    A*x = b Form
    """
    """
    [CLS]: the last column is equation constant 
            x + y +   z  = 1
import sympy as sy


def mean(arr):
    return sum(arr) / len(arr)


def std(arr):
    m = mean(arr)
    return sy.sqrt(sum((x - m)**sy.S(2) for x in arr) / len(arr))


if __name__ == '__main__':
    a = [1, 2, 3]
    n = sy.symbols('n')
    b = [1, 2, 3, n]
    target = std(a)
    curr = std(b)
    print max(sy.solveset(curr - target, n)).evalf()