예제 #1
0
def weights_projection(net, equilibrium, rounding, z):
    """
    :param net:
    :param equilibrium:
    :return:
    """
    tol = 10 ** (-rounding)
    # constraints matrix
    c_mat = network_until_last_layer(net, equilibrium, rounding)[0]
    c_mat = sp.Matrix(sp.nsimplify(sp.Matrix(c_mat), rational=True).T)
    # compute projection matrix
    if c_mat == sp.zeros(c_mat.shape[0], c_mat.shape[1]):
        projection_mat = sp.eye(net.layers[-1].weight.shape[1])
    else:
        projection_mat = sp.eye(net.layers[-1].weight.shape[1]) \
                         - c_mat.T * (c_mat @ c_mat.T)**(-1) @ c_mat
    # make the projection w/o gradient operations with torch.no_grad
    if rounding > 0:
        last_layer = np.round(net.layers[-1].weight.data.numpy(), rounding)
    else:
        last_layer = net.layers[-1].weight.data.numpy()
    last_layer = sp.nsimplify(sp.Matrix(last_layer), rational=True, tolerance=tol)
    new_last_layer = sp.Matrix(last_layer @ projection_mat)

    return new_last_layer
예제 #2
0
def formula_to_string(formula):
    """
    Parameters
    ----------
    formula : dictionary or counter
        Chemical formula

    Returns
    -------
    formula_string : string
        A formula string, with element order as given in the list
        IUPAC_element_order.
        If one or more keys in the dictionary are not one of the elements
        in the periodic table, then they are added at the end of the string.
    """

    formula_string = ''
    for e in IUPAC_element_order:
        if e in formula and np.abs(formula[e]) > 1.e-12:
            if np.abs(formula[e] - 1.) < 1.e-12:
                formula_string += e
            else:
                formula_string += e + str(nsimplify(formula[e]))

    for e in formula:
        if e not in IUPAC_element_order:
            if e in formula and np.abs(formula[e]) > 1.e-12:
                if np.abs(formula[e] - 1.) < 1.e-12:
                    formula_string += e
                else:
                    formula_string += e + str(nsimplify(formula[e]))

    return formula_string
예제 #3
0
def network_until_last_layer(net, x, rounding):
    """
    :param net:
    :param x:
    :param equilibrium:
    :return:
    """
    z = x
    jacobian = np.eye(net.input_size, net.input_size)

    for idx, layer in enumerate(net.layers[:-1]):
        if rounding < 0:
            w = sp.Matrix(layer.weight.data.numpy())
            if layer.bias is not None:
                b = sp.Matrix(layer.bias.data.numpy()[:, None])
            else:
                b = sp.zeros(layer.out_features, 1)
        elif rounding > 0:
            w = sp.Matrix(np.round(layer.weight.data.numpy(), rounding))
            if layer.bias is not None:
                b = sp.Matrix(np.round(layer.bias.data.numpy(), rounding)[:, None])
            else:
                b = sp.zeros(layer.out_features, 1)
        #
        w = sp.Matrix(sp.nsimplify(w, rational=True))
        b = sp.Matrix(sp.nsimplify(b, rational=True))

        zhat = w @ z + b
        z = activation_z3(net.acts[idx], zhat)
        # Vdot
        jacobian = w @ jacobian
        jacobian = np.diagflat(activation_der_z3(net.acts[idx], zhat)) @ jacobian

    return z, jacobian
예제 #4
0
def lp_clique(graph, rational=True):
    V = list(graph.keys())
    v_encode = {}
    v_num = len(V)

    for i in range(v_num):
        temp = np.zeros(v_num)
        temp[i] = -1
        v_encode[V[i]] = temp

    arr_sets = []
    subsets(V, arr_sets=arr_sets)

    b_clique = np.negative(np.ones(v_num))
    A_clique = []
    cliques = []
    A_clique_set(graph, v_encode, arr_sets, A=A_clique, cliques=cliques)
    A_clique = np.transpose(np.array(A_clique))
    c_clique = np.ones(A_clique.shape[1])

    res = linprog(c_clique, A_ub=A_clique, b_ub=b_clique, bounds=(0, None))

    x_rational = list(map(lambda x: sy.nsimplify(x, tolerance=0.01), res.x))

    x_cliques = {}
    for i in range(len(x_rational)):
        x_cliques[cliques[i]] = x_rational[i]

    return sy.nsimplify(res.fun, tolerance=0.01), x_rational, x_cliques
예제 #5
0
파일: QCircuit.py 프로젝트: afuing/QCircuit
    def symbolic_hamiltonian(self):
        variable_phase_symbols = []
        variable_charge_symbols = []
        for variable_id, variable in enumerate(self.variables):
            variable.phase_symbol = sympy.Symbol(variable.name)
            if variable.variable_type == 'variable':
                variable.charge_symbol = sympy.Symbol('n' + variable.name)
            else:
                variable.charge_symbol = sympy.Symbol('U' + variable.name)
            variable_phase_symbols.append(variable.phase_symbol)
            variable_charge_symbols.append(variable.charge_symbol)
        variable_phase_symbols = sympy.Matrix(variable_phase_symbols)
        variable_charge_symbols = sympy.Matrix(variable_charge_symbols)

        node_phase_symbols = self.linear_coordinate_transform * variable_phase_symbols
        for node_id, node in enumerate(self.nodes):
            node.phase_symbol = node_phase_symbols[node_id]
        kinetic_energy = 0.5 * sympy.nsimplify(
            (variable_charge_symbols.T *
             self.capacitance_matrix_legendre_transform(symbolic=True) *
             variable_charge_symbols)[0, 0])
        potential_energy = 0
        for element in self.elements:
            if element.is_phase():
                element_node_phases = []
                element_node_voltages = []
                for wire in self.wires:
                    if wire[0] == element.name:
                        for node_id, node in enumerate(self.nodes):
                            if wire[1] == node.name:
                                element_node_phases.append(
                                    sympy.nsimplify(node.phase_symbol))
                potential_energy += element.symbolic_energy_term(
                    element_node_phases, 0)
        return kinetic_energy + potential_energy
예제 #6
0
    def symbolic_hamiltonian(self):
        variable_phase_symbols = []
        variable_charge_symbols = []
        for variable_id, variable in enumerate(self.variables):
            variable.phase_symbol = sympy.Symbol(variable.name)
            if variable.variable_type=='variable':
                variable.charge_symbol = sympy.Symbol('n'+variable.name)
            else:
                variable.charge_symbol = sympy.Symbol('U'+variable.name)
            variable_phase_symbols.append(variable.phase_symbol)
            variable_charge_symbols.append(variable.charge_symbol)
        variable_phase_symbols = sympy.Matrix(variable_phase_symbols)
        variable_charge_symbols = sympy.Matrix(variable_charge_symbols)

        node_phase_symbols = self.linear_coordinate_transform*variable_phase_symbols
        for node_id, node in enumerate(self.nodes):
            node.phase_symbol = node_phase_symbols[node_id]
        kinetic_energy = 0.5*sympy.nsimplify((variable_charge_symbols.T * self.capacitance_matrix_legendre_transform(symbolic=True) * variable_charge_symbols)[0,0])
        potential_energy = 0
        for element in self.elements:
            if element.is_phase():
                element_node_phases = []
                element_node_voltages = []
                for wire in self.wires:
                    if wire[0]==element.name:
                        for node_id, node in enumerate(self.nodes):
                            if wire[1]==node.name:
                                element_node_phases.append(sympy.nsimplify(node.phase_symbol))
                potential_energy += element.symbolic_energy_term(element_node_phases, 0)
        return kinetic_energy + potential_energy
def newEq(theEquation, ans, theTerm, theVar):
    """
      Content under Creative Commons Attribution license CC-BY 4.0, 
      code under MIT license (c)2018 Sergio Rojas ([email protected]) 

      http://en.wikipedia.org/wiki/MIT_License
      http://creativecommons.org/licenses/by/4.0/

      Created on april, 2018
      Last Modified on: may 15, 2018

      This is a helper function to find step by step the solution
      of any linear equation via operations on both
      sides of the equation. In case of doubt, option 5 can be
      used to check the answer. This also can also be used
      to find solutions to any one variable non-linear equation.
    """
    from sympy import symbols, Eq, solveset, S, sympify
    from sympy import simplify, factor, expand, collect, nsimplify

    LHS, RHS = theEquation.split('=')
    LHS = sympify(LHS)
    RHS = sympify(RHS)
    if ans == 1:
        term = sympify(theTerm)
        RHS = nsimplify(RHS + term)
        LHS = nsimplify(LHS + term)
    elif ans == 2:
        term = sympify(theTerm)
        RHS = nsimplify(RHS - term)
        LHS = nsimplify(LHS - term)
    elif ans == 3:
        term = sympify(theTerm)
        #RHS = nsimplify( simplify(factor(RHS * term)) )
        #LHS = nsimplify( simplify(factor(LHS * term)) )
        RHS = nsimplify(simplify(RHS * term))
        LHS = nsimplify(simplify(LHS * term))
    elif ans == 4:
        term = sympify(theTerm)
        if term != 0:
            #RHS = nsimplify( simplify(expand(RHS / term)) )
            #LHS = nsimplify( simplify(expand(LHS / term)) )
            RHS = nsimplify(simplify(RHS / term))
            LHS = nsimplify(simplify(LHS / term))
    elif ans == 5:
        theVar = symbols(theVar)
        RHS = nsimplify(simplify(RHS))
        LHS = nsimplify(simplify(LHS))
        #RHS = solveset( Eq(LHS, RHS), theVar) ).args[0]
        RHS = list(solveset(Eq(LHS, RHS), theVar))
        if len(RHS) == 1:
            RHS = RHS[0]
        LHS = theVar
    else:
        RHS = RHS
        LHS = LHS

    theneweq = '{0} = {1}'.format(LHS, RHS)
    return theneweq
예제 #8
0
def sympy_equals(expr1, expr2):
    """
    Test that whether two string expressions are equal using sympy, allowing
    e.g. for ``sympy_equals("x * x", "x ** 2") == True``.
    """
    s_expr1 = sympy.nsimplify(sympy.sympify(expr1).expand())
    s_expr2 = sympy.nsimplify(sympy.sympify(expr2).expand())
    return s_expr1 == s_expr2
예제 #9
0
def bug_calc_other_root():
    var('GG', positive=True)
    u = (209*GG**6 - 2696*GG**5 + 13872*GG**4 - 35776*GG**3 + 47104*GG**2 - 27648*GG + 4096)
    h = (209*GG**3 + GG**2*(-1348 + 40*sqrt(5)) + GG*(-256*sqrt(5) + 2608) - 1312 + 416*sqrt(5))
    assert 0 == expand(gcd(u,h,extension=True)*209 - h)
    gg, = solve(h)
    assert 0 == nsimplify(u.subs(GG, gg))
    return all(0 != nsimplify(gg - _gg) for _gg in solve(u))
예제 #10
0
def inverse_symbolic(n, threshold=1e-5):
    rl = mpmath.identify(n.real, tol=1e-3, maxcoeff=30)
    im = mpmath.identify(n.imag, tol=1e-3, maxcoeff=30)
    if not rl or abs(n.real - (nsimplify(rl).evalf())) > threshold:
        rl = nsimplify(n.real).evalf(5)
    if not im or abs(n.imag - (nsimplify(im).evalf())) > threshold:
        im = nsimplify(n.imag).evalf(5)
    return (sympify(rl) + sympify(im) * 1j)
예제 #11
0
def linear_approx(eq, point, approx_point):
    subs = {x: point[0], y: point[1]}
    point = (point[0], point[1], nsimplify(eq.evalf(subs=subs), [pi]))
    plane = tangent_plane(eq, point)
    pprint(plane)

    approx_subs = {x: approx_point[0], y: approx_point[1]}

    return nsimplify(plane.evalf(subs=approx_subs), [pi])
예제 #12
0
def formula_to_string(formula):
    """
    Parameters
    ----------
    formula : dictionary or counter
        Chemical formula

    Returns
    -------
    formula_string : string
        A formula string, with element order based loosely
        on electronegativity, following the scheme suggested by IUPAC,
        except that H comes after the Group 16 elements, not before them.
        If one or more keys in the dictionary are not one of the elements
        in the periodic table, then they are added at the end of the string.
    """
    IUPAC_element_order=['v', 'Og', 'Rn', 'Xe', 'Kr', 'Ar', 'Ne', 'He', # Group 18
                         'Fr', 'Cs', 'Rb', 'K', 'Na', 'Li', # Group 1 (omitting H)
                         'Ra', 'Ba', 'Sr', 'Ca', 'Mg', 'Be', # Group 2
                         'Lr', 'No', 'Md', 'Fm', 'Es', 'Cf', 'Bk', 'Cm',
                         'Am', 'Pu', 'Np', 'U', 'Pa', 'Th', 'Ac', # Actinides
                         'Lu', 'Yb', 'Tm', 'Er', 'Ho', 'Dy', 'Tb', 'Gd',
                         'Eu', 'Sm', 'Pm', 'Nd', 'Pr', 'Ce', 'La', # Lanthanides
                         'Y', 'Sc', # Group 3
                         'Rf', 'Hf', 'Zr', 'Ti', # Group 4
                         'Db', 'Ta', 'Nb', 'V', # Group 5
                         'Sg', 'W', 'Mo', 'Cr', # Group 6
                         'Bh', 'Re', 'Tc', 'Mn', # Group 7
                         'Hs', 'Os', 'Ru', 'Fe', # Group 8
                         'Mt', 'Ir', 'Rh', 'Co', # Group 9
                         'Ds', 'Pt', 'Pd', 'Ni', # Group 10
                         'Rg', 'Au', 'Ag', 'Cu', # Group 11
                         'Cn', 'Hg', 'Cd', 'Zn', # Group 12
                         'Nh', 'Tl', 'In', 'Ga', 'Al', 'B', # Group 13
                         'Fl', 'Pb', 'Sn', 'Ge', 'Si', 'C', # Group 14
                         'Mc', 'Bi', 'Sb', 'As', 'P', 'N', # Group 15
                         'Lv', 'Po', 'Te', 'Se', 'S', 'O', # Group 16
                         'H', # hydrogen
                         'Ts', 'At', 'I', 'Br', 'Cl', 'F']# Group 17

    formula_string = ''
    for e in IUPAC_element_order:
        if e in formula and np.abs(formula[e])>1.e-12:
            if np.abs(formula[e] - 1.) < 1.e-12:
                formula_string += e
            else:
                formula_string += e + str(nsimplify(formula[e]))

    for e in formula:
        if e not in IUPAC_element_order:
            if e in formula and np.abs(formula[e])>1.e-12:
                if np.abs(formula[e] - 1.) < 1.e-12:
                    formula_string += e
                else:
                    formula_string += e + str(nsimplify(formula[e]))

    return formula_string
예제 #13
0
def __verify_C(A, B, angle_BAC, C):
    O = (0, 0, 0)
    OC, OB, OA = C, B, A = list(map(tuple, (C, B, A)))
    R = len_OA = len_OB = distance(O, A)
    L = len_AB = len_AC = distance(B, A)
    len_BC = opposite_tri_edge(len_AB, angle_BAC, len_AC)
    len_BC = my_sympify(len_BC)
    assert nsimplify(distance(B, C) - len_BC) == 0
    assert nsimplify(distance(A, C) - L) == 0
    assert dot_product(cross_product(OB, OA), OC) > 0
예제 #14
0
def random_complex_number(a=2, b=-1, c=3, d=1, rational=False):
    """
    Return a random complex number.

    To reduce chance of hitting branch cuts or anything, we guarantee
    b <= Im z <= d, a <= Re z <= c
    """
    A, B = uniform(a, c), uniform(b, d)
    if not rational:
        return A + I * B
    return nsimplify(A, rational=True) + I * nsimplify(B, rational=True)
예제 #15
0
파일: randtest.py 프로젝트: ness01/sympy
def random_complex_number(a=2, b=-1, c=3, d=1, rational=False):
    """
    Return a random complex number.

    To reduce chance of hitting branch cuts or anything, we guarantee
    b <= Im z <= d, a <= Re z <= c
    """
    A, B = uniform(a, c), uniform(b, d)
    if not rational:
        return A + I * B
    return nsimplify(A, rational=True) + I * nsimplify(B, rational=True)
def simplify(func):
    """ Simplifies a scalar-valued or vector-valued function.

        Args:
            func: A symbolic functions.
    """
    if type(func) == list:
        for i in range(len(func)):
            func[i] = sympy.simplify(sympy.nsimplify(func[i]))
    else:
        func = sympy.simplify(sympy.nsimplify(func))
예제 #17
0
def eta_vect(tableu, m, n, p, p_row, p_col):
    etav = np.ndarray(m)
    etav = etav.astype('object')
    for row in range(m):
        if row == p_row:
            v = 1 / p
            etav[row] = nsimplify(v, rational=True)
        else:
            a = tableu[row][p_col]
            etav[row] = (a) / (-p)
            etav[row] = nsimplify(etav[row], rational=True)

    return etav
예제 #18
0
    def __init__(self):
        try:
            self.expr = (sp.nsimplify(input("Enter an Expression : ")))
            if self.expr.count(Equation.x) != 0:
                self.interval = []
                choice = input("Do you want to enter any interval ? \n " +
                               Fore.BLUE + " Enter ( y / n ) :  ")
                if choice == 'y':
                    self.interval.insert(
                        0,
                        sp.nsimplify(
                            input("Enter the lower bound of the Interval : ")))
                    self.interval.insert(
                        1,
                        sp.nsimplify(
                            input("Enter the upper bound of the Interval : ")))
                    if self.f_x(
                            self.expr,
                            self.interval[0]) == 'Math Error !!!' or self.f_x(
                                self.expr,
                                self.interval[1]) == 'Math Error !!!':
                        print("\nf(" + str(self.interval[0]) + ') = ', end='')
                        print(self.f_x(self.expr, self.interval[0]))
                        print("f(" + str(self.interval[1]) + ') = ', end='')
                        print(self.f_x(self.expr, self.interval[1]))
                        self.find_intervals()
                    if not self.root_exist():
                        self.find_intervals()
                else:
                    self.find_intervals()

                choice = input("Do you want to enter Tolerance ? \n" +
                               Fore.BLUE + " Enter ( y / n ) :  ")
                if choice == 'y':
                    self.Tolerance = float(
                        N(input("Enter the Tolerance (in decimals) : ")))
                else:
                    self.Tolerance = 0.0001  # 10^-4
                    print(Fore.GREEN + "\t\tDefault Value Is Assigned to " +
                          str(self.Tolerance) + " Tolerance .")

            choice = input("Do you want to enter no. of Decimal places ? \n " +
                           Fore.BLUE + " Enter ( y / n ) :  ")
            if choice == 'y':
                Equation.dp = input("Enter the no.of decimal places : ")
            else:
                print(Fore.GREEN + "\t\tDefault Value Is Assigned to " +
                      str(Equation.dp) + " Decimal Places .")
        except SympifyError:
            print(Fore.RED + "\n\t\tInvalid Expression !!! ")
            exit()
예제 #19
0
def get_v0v1(L, R):
    assert 0 < L < 2 * R
    v0 = (R, 0, 0)

    len_Ov0 = len_Ov1 = R
    len_v0v1 = L
    angle_v0Ov1 = opposite_tri_angle(len_Ov0, len_v0v1, len_Ov1)
    x = len_Ov1 * cos(angle_v0Ov1)
    y = len_Ov1 * sin(angle_v0Ov1)
    v1 = (x, y, 0)

    assert nsimplify(vec_len(v1) - R) == 0
    assert nsimplify(y) > 0
    return v0, v1
예제 #20
0
def test_mod_float():
    assert_equal("0.41\\mod 2", Mod(Rational('0.41'), 2))
    assert_equal("143E-13\\mod 21", Mod(Rational('143E-13'), 21))
    assert_equal("-9.80665\\mod 9.80665", Mod(-9.80665, 9.80665))
    assert_equal("0.0000923423\\mod -8341.234802909",
                 nsimplify(Mod(0.0000923423, -8341.234802909)))
    assert_equal("\\sqrt{5}\\mod \\sqrt{2}", Mod(sqrt(5), sqrt(2)))
    assert_equal("987\\mod \\pi", Mod(987, pi))
    assert_equal("\\pi\\mod ((1+\\sqrt{5})/2)",
                 Mod(pi, nsimplify(GoldenRatio)),
                 symbolically=True)
    assert_equal("1234\\mod 1E-29", Mod(1234,
                                        Rational('1E-29'),
                                        evaluate=False))
def calc_g33334():
    # solid2sorted_C_Ks:
    ## (3, 3, 3, 3, 4): ((1/2, sqrt(2)), (2, 1)),
    solid = (3, 3, 3, 3, 4)
    f = solid2zero_poly_GG(solid)
    f = factor(f)
    gg, = solve(f)
    g33334 = sqrt(gg)
    g33334 = nsimplify(g33334)
    _g33334 = sqrt(-2*(42*sqrt(33) + 566)**(one/3)
                   - 128/(42*sqrt(33) + 566)**(one/3) + 44) / sqrt(21)
    assert 0 == nsimplify(g33334 - _g33334)

    assert verify_G(solid, g33334)
    return g33334
예제 #22
0
파일: helpers.py 프로젝트: razetime/Vyxal
def vyxalify(value: Any) -> Any:
    """Takes a value and returns it as one of the four types we use here."""
    if isinstance(value, sympy.core.numbers.Integer):
        return int(value)
    elif is_sympy(value):
        return sympy.nsimplify(value, rational=True)
    elif isinstance(value, (float, complex, numpy.number)):
        return sympy.nsimplify(value, rational=True)
    elif isinstance(value,
                    (int, sympy.Rational, str, LazyList, types.FunctionType)):
        return value
    elif isinstance(value, list):
        return list(map(vyxalify, value))
    else:
        return LazyList(map(vyxalify, value))
예제 #23
0
def _angle_simplify(ang):
    if isinstance(ang, float):
        nsimp = sympy.nsimplify(ang / np.pi)
        numer, denom = nsimp.as_numer_denom()
        if denom < 1e12:
            return pi * numer / denom
    return ang
예제 #24
0
def test_C22():
    test = nsimplify(
        ((6 - 4 * sqrt(2)) * log(3 - 2 * sqrt(2)) +
         (3 - 2 * sqrt(2)) * log(17 - 12 * sqrt(2)) + 32 - 24 * sqrt(2)) /
        (48 * sqrt(2) - 72))
    good = sqrt(2) / 3 - log(sqrt(2) - 1) / 3
    assert test == good
예제 #25
0
def nsimplify_matrix(A_expr,constants=[],tolerance=None,full=False,rational=False):

    A_nsimplified_expr = sympy.Matrix.zeros(A_expr.rows,A_expr.cols)
    for r in range(A_expr.rows):
        for c in range(A_expr.cols):
            A_nsimplified_expr[r,c] = sympy.nsimplify(A_expr[r,c],constants,tolerance,full,rational)
    return A_nsimplified_expr
예제 #26
0
def asin_pi2coeffs(f, x):
    '''f = sum Ci asin(Ki/sqrt(4-x*x)) {i} + C*pi
f/-2/C + pi/2 = sum Ci/-2/C asin(Ki/(4-x*x)) {i}
return {Ki:Ci/-2/C for i}

'''
    w = symbols('__W', positive=True)
    f = f.subs((4-x*x), 1/w/w) # W=1/X=1/sqrt(4-gg); WW=1/(4-gg)
    f = expand(sympify(f))
    f0 = f

    C_pi = get_coeff_of(f, pi)
    
    f /= -2*C_pi
    f += pi/2
    f = expand(f)
    #print(f)
    A, B_ls = f.as_coeff_add()
    assert A == 0
    K = Wild('K')
    C = Wild('C')
    p = C*asin(K*w)
    ls = []
    for b in B_ls:
        m = p.matches(b)
        assert len(m) == 2
        ls.append((m[K], m[C]))
    _f = sum(c*asin(k*w) for k,c in ls)
    assert f == _f
    d = dict((nsimplify(k),c) for k,c in ls)
    assert len(d) == len(ls)
    return d
예제 #27
0
def calc_truncated_g(org_solid):
    #org = mid_truncated_solid2org_solid[solid]
    org_g = Platonic_solid2g[org_solid]

    n = org_solid[0]  # n-gon face of org_solid
    angle = angle_of_regular_polygon(n)

    # assume org_L = 2; 1 = org_L/2
    org_L = 2 * one
    org_L, X = symbols('org_L X', positive=True)
    new_L = opposite_tri_edge(org_L, angle, org_L) * X
    new_L_ = org_L * (1 - 2 * X)
    x, = solve(new_L - new_L_, X)
    x = my_sympify(x)
    new_L = my_sympify(new_L.subs(X, x))

    org_R = org_L / org_g
    org_Rc = outer_radius_of_regular_polygon(n, org_L)
    org_rc = inner_radius_of_regular_polygon(n, org_L)
    org_HH = org_R**2 - org_Rc**2

    new_rc_rc = org_rc**2 + (new_L / 2)**2
    new_RR = org_HH + new_rc_rc
    new_R = sqrt(new_RR)

    new_g = new_L / new_R
    g = my_sympify(new_g)
    g = nsimplify(g)

    if not g.is_number:
        print(locals())
    assert g.is_number
    return g
예제 #28
0
 def C(self, value):
     self.validation.Csetter(self, value)
     if value is None:
         self._C = 0
     else:
         self._C = sp.nsimplify(value, tolerance=1e-6, rational=True)
         self._C = sp.sympify(self._C)
예제 #29
0
    def calcJacobian(self, oJv, pJv, pJw):
        """oJv: terna a la cual se calcula la velocidad de movimiento
        pJv: terna en que se proyectan las velocidades lineales
        pJw: terna en que se proyectan las velocidades rotacionales"""
        J = sym.Matrix(sym.MatrixSymbol('J', 6, self.nAxis))
        A = self.A

        for qi in range(self.nAxis):  #qi = eje de la terna i
            Aojv = self.propagarTerna(qi, oJv)  #del eje hasta la terna final
            Apjv = self.propagarTerna(
                qi, pJv)  #del eje hasta la terna proyectada de velocidad
            Apjw = self.propagarTerna(
                qi, pJw)  #del eje hasta la terna proyectada de rotacion w

            p = Aojv[0:3, 3]
            for i in range(3):  #Itero por eje x, y, z
                if self.jointType[qi] == 'r':
                    rv = Apjv[0:3, i]
                    J[i, qi] = p.cross(rv)[2]
                    rw = Apjw[0:3, i]
                    J[i + 3, qi] = rw[2]
                else:
                    J[i, qi] = Apjw[2, i]
                    J[i + 3, qi] = 0
        J = sym.nsimplify(J, tolerance=1E-10)
        J = sym.trigsimp(J)
        return J
    def adjust(self, solutions, dim):

        sols = []

        x = sp.symbols('x1, x2,x3')

        for tup in solutions:

            # enleve la val de "v"
            tup = tup[:len(tup) - 1]
            l = []

            for i in range(0, dim):

                # les valeurs inconnues sont mises a 0 les autres sont recopiées

                if (tup[i] != x[1] and tup[i] != x[0] and tup[i] != x[2]):

                    l.append(sp.nsimplify(tup[i]))

                else:
                    l.append(0)

            sols.append(tuple(l))

        return sols
def Modified_M1():
    # modified Magnus expansion from Iserles 2002a
    # "ON THE GLOBAL ERROR OF DISCRETIZATION METHODS ... "

    Use_symbolic = True

    A = A_sym.subs(ts, ts0)
    h = sym.Symbol("h", nonzero=True)
    t_half = sym.Symbol("t_half")
    A_half = A.subs(ts0, t_half)
    """
	def B(t):
		A_t = A.subs(ts0, t)
		B = sym.exp((ts0 - t)*A_half)*(A_t - A_half)*sym.exp((t - ts0)*A_half)
		return B
	"""
    B_ = sym.exp(-h * A_half) * (A.subs(ts0, ts1) - A_half) * sym.exp(
        h * A_half)
    B_ = sym.nsimplify(B_)
    B_ = B_.rewrite(sym.cos)
    B_ = sym.simplify(B_)
    print("B = ", B_)
    print()
    if Use_symbolic:
        Om = sym.integrate(B_, (ts1, ts0, ts))
        Om_ = Om.subs({h: ts - ts0, t_half: (1 / 2) * (ts + ts0)})
        print("Om = ", Om_)
        print()
        M_sym = sym.exp(h * A_half) * sym.exp(Om)
        M_sym_ = M_sym.subs({h: ts - ts0, t_half: (1 / 2) * (ts + ts0)})
        print("Modified Magnus 1 matrix = ", M_sym_)
        print()
        Mf = sym.lambdify((ts0, ts), M_sym_, modules=array2mat_c)
    elif not Use_symbolic:
        A_half_num = sym.lambdify((ts0, ts), A_half, modules=array2mat)

        def B_num(t1, t0, t):
            A_t = Eq["A_num"](t1)
            A_h = A_half_num(t0, t)
            B = linalg.expm((t0 - t) * A_h) @ (A_t - A_h) @ linalg.expm(
                (t - t0) * A_h)
            return B

        """
		B_ = B(ts1)
		B_num = sym.lambdify((ts1, ts0, ts), B_, modules=array2mat_c)
		"""
        MM1["name"] = MM1["name"] + " (numeric GL quad, maxiter=" + str(
            quad_maxiter) + ")"

        def Omega_num(t0, t):
            Om = M_quad(B_num, t0, t, ARGS=(t0, t), MAXITER=quad_maxiter)
            return Om

        def Mf(t0, t):
            M_ = linalg.expm(
                (t - t0) * A_half_num(t0, t)) @ linalg.expm(Omega_num(t0, t))
            return M_

    return Mf
def calc_g3444_g3454(solid):
    f = solid2zero_poly_GG(solid)
    gg, = solve(f)
    g = nsimplify(sqrt(gg))

    assert verify_G(solid, g)
    return g
예제 #33
0
def gradient(eq, point=None, verbose=True):
    f_x = eq.diff(x)
    f_y = eq.diff(y)
    f_z = eq.diff(z)

    if verbose:
        pprint(eq)
        pprint((f_x, f_y, f_z))

    if point:
        subs = {x: point[0], y: point[1], z: point[2]}
        f_x = f_x.subs(subs)
        f_y = f_y.subs(subs)
        f_z = f_z.subs(subs)

    return (nsimplify(f_x, [pi]), nsimplify(f_y, [pi]), nsimplify(f_z, [pi]))
예제 #34
0
파일: test_subs.py 프로젝트: KsenijaM/sympy
def test_issue_2877():
    f = Float(2.0)
    assert (x + f).subs({f: 2}) == x + 2

    def r(a,b,c):
        return factor(a*x**2 + b*x + c)
    e = r(5/6, 10, 5)
    assert nsimplify(e) == 5*x**2/6 + 10*x + 5
예제 #35
0
 def simplify_matrix(matrix):
     """
     Replaces floats with ints and puts elements with fractions
     on a single demoninator.
     """
     m = matrix[:, :]
     for i, e in enumerate(m):
         m[i] = nsimplify(e, rational=True).cancel()
     return m
예제 #36
0
    def mark(self):
        """Splits up input into point location and MinMax Value"""
        gradient = 0
        attempt = self.parser.parse()
        attemptPoints = attempt[0]
        attemptMinMax = attempt[1]
        function = equationMaker(self.qvariables)
    
        diff = sympy.diff(function, x)

        # Sympy can only solve for 0, so must take gradient from function
        diff -=  gradient

        results = sympy.solve(diff, x)

        # Simplify results and answer to avoid issue with fractions
        for i in range(len(results)):
            results[i] = sympy.nsimplify(results[i])

        for i in range(len(attemptPoints)):
            attemptPoints[i] = sympy.nsimplify(attemptPoints[i])
        
        """Differentiates a second time, works out if the point is positive, negative
        or 0 and then sets the list accordingly. Minimum point is -1, Max is 1."""
        diff2 = sympy.diff(diff, x)
        minOrMax = []
        for i in range(len(results)):
            j = diff2.subs(x, results[i])
            if j > 0:
                minOrMax.append(-1)
            elif j < 0:
                minOrMax.append(1)
            else:
                minOrMax.append(0)

        """Redundant code for if we split marks up, if so it gives value for each part
        correctly answered:

        half = 1 if (set(minOrMax) == set(attemptMinMax)) else 0
        half += 1 if (set(attemptPoints) == set(results)) else 0
        """
        
        return True if (set(minOrMax) == set(attemptMinMax)) and (set(attemptPoints) == set(results)) else False
예제 #37
0
 def _decimal(self, nbr, prec=None, fractions=None):
     if prec is None:
         prec = self.precision_calcul
     if fractions is None:
         fractions = self.convertir_decimaux_en_fractions
     if fractions:
         # On indique qu'il faudra reconvertir les résultats en décimaux.
         self.reconvertir_en_decimaux = True
         return nsimplify(nbr, rational=True)
     return Float(nbr, prec)
예제 #38
0
 def capacitance_matrix_variables(self, symbolic=False):
     """
     Calculates the capacitance matrix for the energy term of the qubit Lagrangian in the variable respresentation.
     """                        
     
     if symbolic:
         C = self.linear_coordinate_transform.T*self.capacitance_matrix(symbolic)*self.linear_coordinate_transform
         C = sympy.Matrix([sympy.nsimplify(sympy.ratsimp(x)) for x in C]).reshape(*(C.shape))
     else:
         C = np.einsum('ji,jk,kl->il', self.linear_coordinate_transform,self.capacitance_matrix(symbolic),self.linear_coordinate_transform)
     return C
예제 #39
0
def isEquivalentExpressions(response, rubric, allowChangeOfVariable = False, allowSimplify = True, trigIdentities = False, logIdentities = False, forceAssumptions = False):
    if not allowChangeOfVariable:
        if isinstance(response, bool):
            return (type(response) == type(rubric) and response == rubric)
        elif trigIdentities:
            return simplify(expand(nsimplify(response - rubric, rational=True), trig=True)) == 0 
        elif logIdentities and forceAssumptions:
            return simplify(expand(nsimplify(response - rubric, rational=True), log=True, force=True)) == 0 
        elif logIdentities:
            return simplify(expand(nsimplify(response - rubric, rational=True), log=True)) == 0 
        elif allowSimplify:
            return simplify(nsimplify(response - rubric, rational=True)) == 0
        else:
            return response == rubric
    if len(response.free_symbols) == 0:
        return isEquivalent(response, rubric)
    if len(response.free_symbols) > 1:
        raise Exception("Don't know how to test change of variable equivalence of 2 expressions if they have more than 1 variable. Yet")
    if len(response.free_symbols) != len(rubric.free_symbols):
        return False
    return isEquivalent(response.subs(response.free_symbols.pop(),rubric.free_symbols.pop()), rubric)
예제 #40
0
	def as_expr(self):
		expr = 0
		for i in range(len(self.coefs)):
			fact = 1
			for j in range(len(self.vars)):
				fact = fact*self.vars[j]**self.exps[i][j]
			if self.rs is None:
				expr += self.coefs[i]*fact
			else:
				coef = 0
				for j in range(len(self.rs)):
					coef += self.rs[j]*self.coefs[i][j]
				expr += coef*fact
		return spy.nsimplify(expr)
예제 #41
0
파일: test_expr.py 프로젝트: goodok/sympy
def test_action_verbs():
    assert nsimplify((1/(exp(3*pi*x/5)+1))) == (1/(exp(3*pi*x/5)+1)).nsimplify()
    assert ratsimp(1/x + 1/y) == (1/x + 1/y).ratsimp()
    assert trigsimp(log(x), deep=True) == (log(x)).trigsimp(deep = True)
    assert radsimp(1/(2+sqrt(2))) == (1/(2+sqrt(2))).radsimp()
    assert powsimp(x**y*x**z*y**z, combine='all') == (x**y*x**z*y**z).powsimp(combine='all')
    assert simplify(x**y*x**z*y**z) == (x**y*x**z*y**z).simplify()
    assert together(1/x + 1/y) == (1/x + 1/y).together()
    assert separate((x*(y*z)**3)**2) == ((x*(y*z)**3)**2).separate()
    assert collect(a*x**2 + b*x**2 + a*x - b*x + c, x) == (a*x**2 + b*x**2 + a*x - b*x + c).collect(x)
    assert apart(y/(y+2)/(y+1), y) == (y/(y+2)/(y+1)).apart(y)
    assert combsimp(y/(x+2)/(x+1)) == (y/(x+2)/(x+1)).combsimp()
    assert factor(x**2+5*x+6) == (x**2+5*x+6).factor()
    assert refine(sqrt(x**2)) == sqrt(x**2).refine()
    assert cancel((x**2+5*x+6)/(x+2)) == ((x**2+5*x+6)/(x+2)).cancel()
예제 #42
0
파일: functions.py 프로젝트: cran/dMod
def printTransformations(infisAll, allVariables):
	n = len(infisAll[0])

	length1 = 8
	length2 = 13
	length3 = 14
	transformations = [0]*len(infisAll)
	types = [0]*len(infisAll)
	outputs = []
	for l in range(len(infisAll)):
		for i in range(n):
			infisAll[l][i] = spy.nsimplify(infisAll[l][i])
		transformations[l], types[l] = buildTransformation(infisAll[l], allVariables)
		
		outputs.append([])
		for i in range(n):
			if infisAll[l][i] != 0:
				# get stuff for output line
				outputs[-1].append(\
							[str(allVariables[i]), str(infisAll[l][i]), str(transformations[l][i])])
				
				# remove string extension
				for v in ['Q', 'C', 'O', 'S', 'I', 'N', 'E']:
					outputs[-1][-1][0] = outputs[-1][-1][0].replace(v + extension_str, v)
					outputs[-1][-1][1] = outputs[-1][-1][1].replace(v + extension_str, v)
					outputs[-1][-1][2] = outputs[-1][-1][2].replace(v + extension_str, v)
				
				# search for longest string
				if len(outputs[-1][-1][0]) > length1:
					length1 = len(outputs[-1][-1][0])					
				if len(outputs[-1][-1][1]) > length2:
					length2 = len(outputs[-1][-1][1])					
				if len(outputs[-1][-1][2]) > length3:
					length3 = len(outputs[-1][-1][2])

	# print all stuff
	print ('{0:'+str(length1)+'s} : ').format('variable') \
		+ ('{0:'+str(length2)+'s} : ').format('infinitesimal')\
		+ str('transformation')

	for l in range(len(infisAll)):
		print '-'*(length1+length2+length3+6)
		print '#' + str(l+1) + ': ' + types[l]
		
		for lst in outputs[l]:
			print ('{0:'+str(length1)+'s} : ').format(lst[0]) \
					+ ('{0:'+str(length2)+'s} : ').format(str(lst[1]))\
					+ str(lst[2])
예제 #43
0
def floats2rationals(expr):
    u"""Convertit tous les flottants d'une expression sympy en rationnels.

    Si l'expression est de type `list` ou `tuple`, la fonction est appelée
    récursivement.
    Sinon, si elle n'est pas de type sympy, l'expression est renvoyée telle
    qu'elle.
    """
    if isinstance(expr, (list, tuple)):
        return expr.__class__(floats2rationals(item) for item in expr)
    elif not isinstance(expr, Basic):
        return expr
    dico = {}
    for a in expr.atoms():
        if a.is_Float:
            dico[a] = nsimplify(a, rational=True)
    return expr.subs(dico)
예제 #44
0
파일: libm.py 프로젝트: bayao/qml
 def emit(name, iname, cdf, args, no_small=False):
     V = []
     for arg in sorted(args):
         y = cdf(*arg)
         if isinstance(y, mpf):
             e = sp.nsimplify(y, rational=True)
             if e.is_Rational and e.q <= 1000 and mp.almosteq(e, y, 1e-25):
                 y = e
         else:
             y = N(y)
         V.append(arg + (y,))
     for v in V:
         if name:
             test(name, *v)
     for v in V:
         if iname and (not no_small or 1/1000 <= v[-1] <= 999/1000):
             test(iname, *(v[:-2] + v[:-3:-1]))
예제 #45
0
def test_power():
    """
    Take units to some power.

    """
    from sympy import nsimplify

    pc_cgs = cm_per_pc
    mK_cgs = 1e-3
    u1_dims = mass * length**2 * time**-3 * temperature**4
    u1 = Unit("g * pc**2 * s**-3 * mK**4")

    u2 = u1**2

    yield assert_true, u2.dimensions == u1_dims**2
    yield assert_allclose_units, u2.base_value, (pc_cgs**2 * mK_cgs**4)**2, 1e-12

    u3 = u1**(-1.0/3)

    yield assert_true, u3.dimensions == nsimplify(u1_dims**(-1.0/3))
    yield assert_allclose_units, u3.base_value, (pc_cgs**2 * mK_cgs**4)**(-1.0/3), 1e-12
예제 #46
0
def test_power():
    """
    Take units to some power.

    """
    from dimensionful.dimensions import mass, length, time, temperature
    from sympy import nsimplify

    pc_cgs = 3.08568e18
    mK_cgs = 1e-3
    u1_dims = mass * length ** 2 * time ** -3 * temperature ** 4
    u1 = Unit("g * pc**2 * s**-3 * mK**4")

    u2 = u1 ** 2

    assert u2.dimensions == u1_dims ** 2
    assert u2.cgs_value == (pc_cgs ** 2 * mK_cgs ** 4) ** 2

    u3 = u1 ** (-1.0 / 3)

    assert u3.dimensions == nsimplify(u1_dims ** (-1.0 / 3))
    assert u3.cgs_value == (pc_cgs ** 2 * mK_cgs ** 4) ** (-1.0 / 3)
예제 #47
0
def euler_rotmat(order='xyz', frame='local', angles=None, unit='deg',
                 str_symbols=None, showA=True, showN=True):
    """Euler rotation matrix given sequence, frame, and angles.
    
    This function calculates the algebraic rotation matrix (3x3) for a given
    sequence ('order' argument) of up to three elemental rotations of a given
    coordinate system ('frame' argument) around another coordinate system, the
    Euler (or Eulerian) angles [1]_.

    This function also calculates the numerical values of the rotation matrix
    when numerical values for the angles are inputed for each rotation axis.
    Use None as value if the rotation angle for the particular axis is unknown.

    The symbols for the angles are: alpha, beta, and gamma for the first,
    second, and third rotations, respectively.
    The matrix product is calulated from right to left and in the specified
    sequence for the Euler angles. The first letter will be the first rotation.
    
    The function will print and return the algebraic rotation matrix and the
    numerical rotation matrix if angles were inputed.

    Parameters
    ----------
    order  : string, optional (default = 'xyz')
             Sequence for the Euler angles, any combination of the letters
             x, y, and z with 1 to 3 letters is accepted to denote the
             elemental rotations. The first letter will be the first rotation.

    frame  : string, optional (default = 'local')
             Coordinate system for which the rotations are calculated.
             Valid values are 'local' or 'global'.

    angles : list, array, or bool, optional (default = None)
             Numeric values of the rotation angles ordered as the 'order'
             parameter. Enter None for a rotation whith unknown value.

    unit   : str, optional (default = 'deg')
             Unit of the input angles.
    
    str_symbols : list of strings, optional (default = None)
             New symbols for the angles, for instance, ['theta', 'phi', 'psi']
             
    showA  : bool, optional (default = True)
             True (1) displays the Algebraic rotation matrix in rich format.
             False (0) to not display.

    showN  : bool, optional (default = True)
             True (1) displays the Numeric rotation matrix in rich format.
             False (0) to not display.
             
    Returns
    -------
    R     :  Matrix Sympy object
             Rotation matrix (3x3) in algebraic format.

    Rn    :  Numpy array or Matrix Sympy object (only if angles are inputed)
             Numeric rotation matrix (if values for all angles were inputed) or
             a algebraic matrix with some of the algebraic angles substituted
             by the corresponding inputed numeric values.

    Notes
    -----
    This code uses Sympy, the Python library for symbolic mathematics, to
    calculate the algebraic rotation matrix and shows this matrix in latex form
    possibly for using with the IPython Notebook, see [1]_.

    References
    ----------
    .. [1] http://nbviewer.ipython.org/github/duartexyz/BMC/blob/master/Transformation3D.ipynb

    Examples
    --------
    >>> # import function
    >>> from euler_rotmat import euler_rotmat
    >>> # Default options: xyz sequence, local frame and show matrix
    >>> R = euler_rotmat()
    >>> # XYZ sequence (around global (fixed) coordinate system)
    >>> R = euler_rotmat(frame='global')
    >>> # Enter numeric values for all angles and show both matrices
    >>> R, Rn = euler_rotmat(angles=[90, 90, 90])
    >>> # show what is returned
    >>> euler_rotmat(angles=[90, 90, 90])
    >>> # show only the rotation matrix for the elemental rotation at x axis
    >>> R = euler_rotmat(order='x')
    >>> # zxz sequence and numeric value for only one angle
    >>> R, Rn = euler_rotmat(order='zxz', angles=[None, 0, None])
    >>> # input values in radians:
    >>> import numpy as np
    >>> R, Rn = euler_rotmat(order='zxz', angles=[None, np.pi, None], unit='rad')
    >>> # shows only the numeric matrix
    >>> R, Rn = euler_rotmat(order='zxz', angles=[90, 0, None], showA='False')
    >>> # Change the angles' symbols
    >>> R = euler_rotmat(order='zxz', str_symbols=['theta', 'phi', 'psi'])
    >>> # Negativate the angles' symbols
    >>> R = euler_rotmat(order='zxz', str_symbols=['-theta', '-phi', '-psi'])
    >>> # all algebraic matrices for all possible sequences for the local frame
    >>> s=['xyz','xzy','yzx','yxz','zxy','zyx','xyx','xzx','yzy','yxy','zxz','zyz']
    >>> for seq in s: R = euler_rotmat(order=seq)
    >>> # all algebraic matrices for all possible sequences for the global frame
    >>> for seq in s: R = euler_rotmat(order=seq, frame='global')
    """

    import numpy as np
    import sympy as sym
    try:
        from IPython.core.display import Math, display
        ipython = True
    except:
        ipython = False

    angles = np.asarray(np.atleast_1d(angles), dtype=np.float64)
    if ~np.isnan(angles).all():        
        if len(order) != angles.size:
            raise ValueError("Parameters 'order' and 'angles' (when " + 
                             "different from None) must have the same size.")

    x, y, z = sym.symbols('x, y, z')
    sig = [1, 1, 1]
    if str_symbols is None:
        a, b, g = sym.symbols('alpha, beta, gamma')
    else:
        s = str_symbols
        if s[0][0] == '-': s[0] = s[0][1:]; sig[0] = -1
        if s[1][0] == '-': s[1] = s[1][1:]; sig[1] = -1
        if s[2][0] == '-': s[2] = s[2][1:]; sig[2] = -1        
        a, b, g = sym.symbols(s)

    var = {'x': x, 'y': y, 'z': z, 0: a, 1: b, 2: g}
    # Elemental rotation matrices for xyz (local)
    cos, sin = sym.cos, sym.sin
    Rx = sym.Matrix([[1, 0, 0], [0, cos(x), sin(x)], [0, -sin(x), cos(x)]])
    Ry = sym.Matrix([[cos(y), 0, -sin(y)], [0, 1, 0], [sin(y), 0, cos(y)]])
    Rz = sym.Matrix([[cos(z), sin(z), 0], [-sin(z), cos(z), 0], [0, 0, 1]])

    if frame.lower() == 'global':
        Rs = {'x': Rx.T, 'y': Ry.T, 'z': Rz.T}
        order = order.upper()
    else:
        Rs = {'x': Rx, 'y': Ry, 'z': Rz}
        order = order.lower()

    R = Rn = sym.Matrix(sym.Identity(3))
    str1 = r'\mathbf{R}_{%s}( ' %frame  # last space needed for order=''
    #str2 = [r'\%s'%var[0], r'\%s'%var[1], r'\%s'%var[2]]
    str2 = [1, 1, 1]        
    for i in range(len(order)):
        Ri = Rs[order[i].lower()].subs(var[order[i].lower()], sig[i] * var[i]) 
        R = Ri * R
        if sig[i] > 0:
            str2[i] = '%s:%s' %(order[i], sym.latex(var[i]))
        else:
            str2[i] = '%s:-%s' %(order[i], sym.latex(var[i]))
        str1 = str1 + str2[i] + ','
        if ~np.isnan(angles).all() and ~np.isnan(angles[i]):
            if unit[:3].lower() == 'deg':
                angles[i] = np.deg2rad(angles[i])
            Rn = Ri.subs(var[i], angles[i]) * Rn
            #Rn = sym.lambdify(var[i], Ri, 'numpy')(angles[i]) * Rn
            str2[i] = str2[i] + '=%.0f^o' %np.around(np.rad2deg(angles[i]), 0)
        else:
            Rn = Ri * Rn

    Rn = sym.simplify(Rn)  # for trigonometric relations

    try:
        # nsimplify only works if there are symbols
        Rn2 = sym.latex(sym.nsimplify(Rn, tolerance=1e-8).n(chop=True, prec=4))
    except:
        Rn2 = sym.latex(Rn.n(chop=True, prec=4))
        # there are no symbols, pass it as Numpy array
        Rn = np.asarray(Rn)
    
    if showA and ipython:
        display(Math(str1[:-1] + ') =' + sym.latex(R, mat_str='matrix')))

    if showN and ~np.isnan(angles).all() and ipython:
            str2 = ',\;'.join(str2[:angles.size])
            display(Math(r'\mathbf{R}_{%s}(%s)=%s' %(frame, str2, Rn2)))

    if np.isnan(angles).all():
        return R
    else:
        return R, Rn
예제 #48
0
def test_issue_9448():
    tmp = sympify("1/(1 - (-1)**(2/3) - (-1)**(1/3)) + 1/(1 + (-1)**(2/3) + (-1)**(1/3))")
    assert nsimplify(tmp) == S(1)/2
예제 #49
0
def test_nsimplify():
    x = Symbol("x")
    assert nsimplify(0) == 0
    assert nsimplify(-1) == -1
    assert nsimplify(1) == 1
    assert nsimplify(1 + x) == 1 + x
    assert nsimplify(2.7) == Rational(27, 10)
    assert nsimplify(1 - GoldenRatio) == (1 - sqrt(5))/2
    assert nsimplify((1 + sqrt(5))/4, [GoldenRatio]) == GoldenRatio/2
    assert nsimplify(2/GoldenRatio, [GoldenRatio]) == 2*GoldenRatio - 2
    assert nsimplify(exp(5*pi*I/3, evaluate=False)) == \
        sympify('1/2 - sqrt(3)*I/2')
    assert nsimplify(sin(3*pi/5, evaluate=False)) == \
        sympify('sqrt(sqrt(5)/8 + 5/8)')
    assert nsimplify(sqrt(atan('1', evaluate=False))*(2 + I), [pi]) == \
        sqrt(pi) + sqrt(pi)/2*I
    assert nsimplify(2 + exp(2*atan('1/4')*I)) == sympify('49/17 + 8*I/17')
    assert nsimplify(pi, tolerance=0.01) == Rational(22, 7)
    assert nsimplify(pi, tolerance=0.001) == Rational(355, 113)
    assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3)
    assert nsimplify(2.0**(1/3.), tolerance=0.001) == Rational(635, 504)
    assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == \
        2**Rational(1, 3)
    assert nsimplify(x + .5, rational=True) == Rational(1, 2) + x
    assert nsimplify(1/.3 + x, rational=True) == Rational(10, 3) + x
    assert nsimplify(log(3).n(), rational=True) == \
        sympify('109861228866811/100000000000000')
    assert nsimplify(Float(0.272198261287950), [pi, log(2)]) == pi*log(2)/8
    assert nsimplify(Float(0.272198261287950).n(3), [pi, log(2)]) == \
        -pi/4 - log(2) + S(7)/4
    assert nsimplify(x/7.0) == x/7
    assert nsimplify(pi/1e2) == pi/100
    assert nsimplify(pi/1e2, rational=False) == pi/100.0
    assert nsimplify(pi/1e-7) == 10000000*pi
    assert not nsimplify(
        factor(-3.0*z**2*(z**2)**(-2.5) + 3*(z**2)**(-1.5))).atoms(Float)
    e = x**0.0
    assert e.is_Pow and nsimplify(x**0.0) == 1
    assert nsimplify(3.333333, tolerance=0.1, rational=True) == Rational(10, 3)
    assert nsimplify(3.333333, tolerance=0.01, rational=True) == Rational(10, 3)
    assert nsimplify(3.666666, tolerance=0.1, rational=True) == Rational(11, 3)
    assert nsimplify(3.666666, tolerance=0.01, rational=True) == Rational(11, 3)
    assert nsimplify(33, tolerance=10, rational=True) == Rational(33)
    assert nsimplify(33.33, tolerance=10, rational=True) == Rational(30)
    assert nsimplify(37.76, tolerance=10, rational=True) == Rational(40)
    assert nsimplify(-203.1) == -S(2031)/10
    assert nsimplify(.2, tolerance=0) == S.One/5
    assert nsimplify(-.2, tolerance=0) == -S.One/5
    assert nsimplify(.2222, tolerance=0) == S(1111)/5000
    assert nsimplify(-.2222, tolerance=0) == -S(1111)/5000
    # issue 7211, PR 4112
    assert nsimplify(S(2e-8)) == S(1)/50000000
    # issue 7322 direct test
    assert nsimplify(1e-42, rational=True) != 0
    # issue 10336
    inf = Float('inf')
    infs = (-oo, oo, inf, -inf)
    for i in infs:
        ans = sign(i)*oo
        assert nsimplify(i) == ans
        assert nsimplify(i + x) == x + ans

    assert nsimplify(0.33333333, rational=True, rational_conversion='exact') == Rational(0.33333333)

    # Make sure nsimplify on expressions uses full precision
    assert nsimplify(pi.evalf(100)*x, rational_conversion='exact').evalf(100) == pi.evalf(100)*x
예제 #50
0
def test_C17():
    test = nsimplify((sqrt(3) + sqrt(2)) / (sqrt(3) - sqrt(2)))
    good = 5 + 2*sqrt(6)
    assert test == good
예제 #51
0
def test_C18():
    assert nsimplify(sqrt(-2 + sqrt(-5)) * sqrt(-2 - sqrt(-5))) == 3
예제 #52
0
def test_C19():
    assert radsimp(nsimplify((90 + 35*sqrt(7)) ** R(1, 3))) == 3 + sqrt(7)
예제 #53
0
def test_nsimplify():
    x = Symbol("x")
    assert nsimplify(0) == 0
    assert nsimplify(-1) == -1
    assert nsimplify(1) == 1
    assert nsimplify(1+x) == 1+x
    assert nsimplify(2.7) == Rational(27, 10)
    assert nsimplify(1-GoldenRatio) == (1-sqrt(5))/2
    assert nsimplify((1+sqrt(5))/4, [GoldenRatio]) == GoldenRatio/2
    assert nsimplify(2/GoldenRatio, [GoldenRatio]) == 2*GoldenRatio - 2
    assert nsimplify(exp(5*pi*I/3, evaluate=False)) == sympify('1/2 - sqrt(3)*I/2')
    assert nsimplify(sin(3*pi/5, evaluate=False)) == sympify('sqrt(sqrt(5)/8 + 5/8)')
    assert nsimplify(sqrt(atan('1', evaluate=False))*(2+I), [pi]) == sqrt(pi) + sqrt(pi)/2*I
    assert nsimplify(2 + exp(2*atan('1/4')*I)) == sympify('49/17 + 8*I/17')
    assert nsimplify(pi, tolerance=0.01) == Rational(22, 7)
    assert nsimplify(pi, tolerance=0.001) == Rational(355, 113)
    assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3)
    assert nsimplify(2.0**(1/3.), tolerance=0.001) == Rational(635, 504)
    assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == 2**Rational(1, 3)
    assert nsimplify(x + .5, rational=True) == Rational(1, 2) + x
    assert nsimplify(1/.3 + x, rational=True) == Rational(10, 3) + x
    assert nsimplify(log(3).n(), rational=True) == \
           sympify('109861228866811/100000000000000')
    assert nsimplify(Float(0.272198261287950), [pi,log(2)]) == pi*log(2)/8
    assert nsimplify(Float(0.272198261287950).n(3), [pi,log(2)]) == \
        -pi/4 - log(2) + S(7)/4
    assert nsimplify(x/7.0) == x/7
    assert nsimplify(pi/1e2) == pi/100
    assert nsimplify(pi/1e2, rational=False) == pi/100.0
    assert nsimplify(pi/1e-7) == 10000000*pi
예제 #54
0
def test_nsimplify():
    x = Symbol("x")
    assert nsimplify(0) == 0
    assert nsimplify(-1) == -1
    assert nsimplify(1) == 1
    assert nsimplify(1+x) == 1+x
    assert nsimplify(2.7) == Rational(27, 10)
    assert nsimplify(1-GoldenRatio) == (1-sqrt(5))/2
    assert nsimplify((1+sqrt(5))/4, [GoldenRatio]) == GoldenRatio/2
    assert nsimplify(2/GoldenRatio, [GoldenRatio]) == 2*GoldenRatio - 2
    assert nsimplify(exp(5*pi*I/3, evaluate=False)) == sympify('1/2 - I*3**(1/2)/2')
    assert nsimplify(sin(3*pi/5, evaluate=False)) == sympify('(5/8 + 1/8*5**(1/2))**(1/2)')
    assert nsimplify(sqrt(atan('1', evaluate=False))*(2+I), [pi]) == sqrt(pi) + sqrt(pi)/2*I
    assert nsimplify(2 + exp(2*atan('1/4')*I)) == sympify('49/17 + 8*I/17')
    assert nsimplify(pi, tolerance=0.01) == Rational(22, 7)
    assert nsimplify(pi, tolerance=0.001) == Rational(355, 113)
    assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3)
    assert nsimplify(2.0**(1/3.), tolerance=0.001) == Rational(635, 504)
    assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == 2**Rational(1, 3)
    assert nsimplify(x + .5, rational=True) == Rational(1, 2) + x
    assert nsimplify(1/.3 + x, rational=True) == Rational(10, 3) + x
    assert nsimplify(log(3).n(), rational=True) == \
           sympify('109861228866811/100000000000000')
예제 #55
0
def test_C15():
    test = nsimplify(sqrt(14 + 3*sqrt(3 + 2*sqrt(5 - 12*sqrt(3 - 2*sqrt(2))))))
    good = sqrt(2) + 3
    assert test == good
예제 #56
0
def print_latex():

        #plt.clf()
        #edo_main()
        for i in range(1,7):Respostas[i] = nsimplify(Respostas[i], rational = True,tolerance = 0.05).evalf(prec)

        # 0- Raizes; 1- Forma Natural da respsota; 2- Resposta Natural;
        # 3- Resposta Particular; 4- Resposta Transitoria; 5- Respsota Forcada
        # 6- Resposta Completa; 7-Sinal de entrada x(t); 8 - eq
        ###
        eqDiferencialEntradaLatex = latex(Respostas[8])




        ##Perfumaria
        dif = 0.9 -0.77
        xdif = -0.15
        font = {'family' : 'Sans',
                'weight' : 'normal',
                'size'   : 18}


        plt.rc('font', **font)

        ##Obtendo as respostas em Latex
        RespostasEmLatex = [0]*(len(Respostas))
        raizEmLatex = [0]*(len(Respostas[0]))
        str_raizLatex =""
        for i in range(len(Respostas[0])):
                raizEmLatex[i] = '$'+str(latex(Respostas[0][i])) +'$'
        for i in range(len(raizEmLatex)):
                rn = "r"+str(i+1)+" = "
                rn = '$'+str(latex(rn)) +'$'
                str_raizLatex = str_raizLatex+"\t"+rn+raizEmLatex[i]
        ##print len(RespostasEmLatex)
        for i in range(len(Respostas)):
                RespostasEmLatex[i] = '$'+str(latex(Respostas[i])) +'$'
        #print RespostasEmLatex
        #xTLatex = '$' + latex(xT) +'$'
        ###Preparando para imprimir
        log_figure = plt.figure("Representacao",facecolor='white')
        ax1 = plt.axes(frameon = False)
        ax1.get_xaxis().tick_bottom()
        ax1.get_xaxis().set_visible(False)
        ax1.axes.get_yaxis().set_visible(False)
        for i in range(0,8,1):
                plt.axhline(0.86-dif*i,xmin = -5,xmax = 5, color = 'black',lw =0.2, linestyle = ':')
        #log_figure.figure("Forma_Representativa:")
        plt.title('')
        plt.text(xdif,0.89,"Eq dif: 0="+ur'$'+eqDiferencialEntradaLatex+'$'+"\tConds Iniciais: y(0)= "+str(cond_ini[0])+"\ty'(0)= "+str(cond_ini[1]))
        plt.text(xdif,0.89-dif,'Forma Natural:'+ur''+RespostasEmLatex[1])
        plt.text(xdif,0.9-2*dif,'yn(t) = '+ur''+RespostasEmLatex[2])
        plt.text(xdif,0.9-3*dif,'ypar(t) = '+ur''+RespostasEmLatex[3])
        plt.text(xdif,0.9-4*dif,'ytran(t) = '+ur''+RespostasEmLatex[4])
        plt.text(xdif,0.9-5*dif,'yfor(t) = '+ur''+RespostasEmLatex[5])
        plt.text(xdif,0.9-6*dif,'yc(t) = '+ur''+RespostasEmLatex[6])
        plt.text(xdif,0.9-7*dif,'x(t) = '+ur''+RespostasEmLatex[7])
        plt.text(xdif,0.9-8*dif,'Raiz(es): '+ur''+str_raizLatex)

        plt.subplots_adjust(left=0.11, bottom=0.08, right=0.50, top=0.88,
                                                wspace=0.22, hspace=0.21)





        ##log_figure.set_size_inches(19.2,10.8)
        #log_figure.show()
        #plt.show()

        return log_figure
예제 #57
0
def test_C22():
    test = nsimplify(((6 - 4*sqrt(2))*log(3 - 2*sqrt(2)) + (3 - 2*sqrt(2))*log(17
        - 12*sqrt(2)) + 32 - 24*sqrt(2)) / (48*sqrt(2) - 72))
    good = sqrt(2)/3 - log(sqrt(2) - 1)/3
    assert test == good
예제 #58
0
def test_C21():
    assert nsimplify((41 + 29*sqrt(2)) ** R(1, 5)) == 1 + sqrt(2)
예제 #59
0
def test_C20():
    inside = (135 + 78*sqrt(3))
    test = nsimplify((inside**R(2, 3) + 3) * sqrt(3) / inside**R(1, 3))
    assert test == 12