Esempio n. 1
0
def invariant3D_discriminant(T,coords,info=True):
    """
    Function assumes that the tensor is given in analytical form as a
    sympy matrix. Further it only considers 3D second rank symmetric
    tensors, i.e of the formd 
                
                T = [T00 T01 T02; 
                     T01 T11 T12;
                     T02 T12 T22] 
    
    The discriminant of the tensor is evaluated. If it equals zero, this implies
    that the tensor has at least two equal eigenvalues, i.e the tensor is 
    degenerate.

    This technique is based on the article by Zheng et. al. - see ZTP06
    """
    x0, y0, z0 = coords[0], coords[1], coords[2]
    x,y,z = sympy.symbols('x y z')
    
    P = T[0,0] + T[1,1] + T[2,2]
    Q = sympy.det(T[:2,:2]) + sympy.det(T[1:,1:]) + T[2,2]*T[0,0] - T[0,2]*T[0,2]
    R = sympy.det(T)
    
    D = Q**2*P**2 - 4*R*P**3 - 4*Q**3 - 4*Q**3 + 18*P*Q*R - 27*R**2

    D_value = D.evalf(subs={x:x0,y:y0,z:z0})
    eps = 1e-12
    if abs(D_value) <= eps :
        if info:
            msg(1,T,coords)
        return 1
    else:
        if info:
            msg(0,T,coords)
        return 0
Esempio n. 2
0
def solve(m):
    M = Matrix(m)
    M.col_del(N)

    M = M.applyfunc(lambda x: x % p)

    M_det = sympy.det(M) % p
    M_det_inv = Crypto.Util.number.inverse(M_det, p)

    X = list()

    for i in range(N):
        X.append(Matrix(m))

    for i in range(N):
        X[i].col_swap(i, N)
        X[i].col_del(N)
        X[i] = X[i].applyfunc(lambda x: x % p)

    X_det = list()

    print("Solving the matrix...")
    for i in pbar(range(N)):
        try:
            X_det.append(sympy.det(X[i]) % p)
        except KeyboardInterrupt:
            exit()

    key = list()

    for i in range(N):
        key.append((X_det[i] * M_det_inv) % p)
    return key
 def Inv_matrix(self, A, prime):
     M = list()
     determinate = sp.det(Matrix(A))  # определитель матрицы
     determinate = gcdex(determinate, prime)[1] % prime  # det(A)^(-1)
     for i in range(self.size):
         M.append(list())
         for j in range(self.size):
             m = np.delete(A, i, axis=0)
             m = sp.det(Matrix(np.delete(
                 m, j, axis=1)))  # алгебраическое дополнение
             M[i].append(pow(-1, i + j) * m * determinate % prime)
     M = list(map(list, zip(*M)))
     return M
Esempio n. 4
0
def question7_2e(reponse):
    e = sp.Matrix([[-1, 2, 3], [4, 6, -3], [0, -11, 4]])

    if np.abs(reponse - sp.det(e)) != 0:
        display(
            "Dans ce cas, deux fois la première rangée a été ajouté à la troisième rangée."
        )
        display("Aussi les premières deux rangées sont échangées.")
        display(
            Latex(
                "$ Soit: 2 \\times R_1 + R_3 \\rightarrow R_3, R_1 \\leftrightarrow R_2 $"
            ))
        display("Le déterminant est donc:")
        display(
            Latex("$ det|e| = (-1) \cdot det|A| = (-1) \cdot 155 = - 155 $"))

        button = widgets.Button(description='Solution', disabled=False)
        box = HBox(children=[button])
        out = widgets.Output()

        @out.capture()
        def solution(k):
            out.clear_output()
            Determinant_3x3(e, step_by_step=True)

        button.on_click(solution)

        display(box)
        display(out)
    else:
        display("Bravo! Vous avez trouvé la réponse.")
Esempio n. 5
0
def question7_2f(reponse):
    f = sp.Matrix([[4, -5, 8], [6, 10, 1], [-3, 15, -2]])

    if np.abs(reponse - sp.det(f)) != 0:
        display("Dans ce cas, la deuxième rangée a été multiplié par cinq.")
        display("Après ça, c''est la transposée de la matrice.")
        display(
            Latex(
                "$ Soit: 5 \\times R_2 \\rightarrow R_2, \: et \: transposée $"
            ))
        display("Le déterminant est donc:")
        display(
            Latex(
                "$ det|f| = 5 \cdot det|A|^T = 5 \cdot det|A| = 5 \cdot 155 = 755 $"
            ))

        button = widgets.Button(description='Solution', disabled=False)
        box = HBox(children=[button])
        out = widgets.Output()

        @out.capture()
        def solution(e):
            out.clear_output()
            Determinant_3x3(f, step_by_step=True)

        button.on_click(solution)

        display(box)
        display(out)
    else:
        display("Bravo! Vous avez trouvé la réponse.")
Esempio n. 6
0
File: sdp.py Progetto: jre21/SDP
    def print_bertini_script(self, directory, template="data/bertini_input"):
        """Create a bertini script suitable for execution from template.

        directory: working directory for bertini
        template: template file from which to generate script

        """
        x, y, z = sympy.symbols("x y z")
        det = sympy.det(
            x * sympy.Matrix(self.A) + y * sympy.Matrix(self.B) + z * sympy.Matrix(self.C) + sympy.Matrix(self.D)
        )
        difx = sympy.diff(det, x)
        dify = sympy.diff(det, y)
        difz = sympy.diff(det, z)

        with open(template) as inp:
            with open(directory + "/input", mode="w") as out:
                for line in inp.readlines():
                    print(
                        line.format(
                            F=str(det).replace("**", "^"),
                            G=str(difx).replace("**", "^"),
                            H=str(dify).replace("**", "^"),
                            I=str(difz).replace("**", "^"),
                        ),
                        file=out,
                        end="",
                    )
def prob7():
    """Calculate the integral of f(x,y,z) = (x^2 + y^2 + z^2)^2 over the
    sphere of radius r. Lambdify the resulting expression and plot the integral
    value for r in [0,3]. Return the value of the integral when r = 2.

    Returns:
        (float): the integral of f over the sphere of radius 2.
    """
    #initialize the function
    x, y, z, j, k, l, r = sy.symbols('x y z j k l r')
    func = (x**2 + y**2 + z**2)**2
    #calculate the Jacobian matrix
    h = sy.Matrix([[j * sy.sin(l) * sy.cos(k)], [j * sy.sin(l) * sy.sin(k)],
                   [j * sy.cos(l)]])
    J = h.jacobian((j, k, l))
    f = sy.lambdify((x, y, z), func)
    det_ = -sy.det(J).simplify()
    #calculate the function in terms of r by intergrting the volume
    integ = sy.integrate(
        f(*h).simplify() * det_, (j, 0, r), (k, 0, 2 * sy.pi), (l, 0, sy.pi))

    g = sy.lambdify(r, integ)
    #graph the function in terms of r
    domain = np.linspace(0, 3, 100)
    plt.plot(domain, g(domain))
    plt.show()
Esempio n. 8
0
def getLimit():
    p1 = sym.Symbol('p1')
    p2 = sym.Symbol('p2')
    p3 = sym.Symbol('p3')
    p4 = sym.Symbol('p4')
    q1 = sym.Symbol('q1')
    q2 = sym.Symbol('q2')
    q3 = sym.Symbol('q3')
    q4 = sym.Symbol('q4')
    D_1 = sym.Matrix( \
       [ [p1*q1-1, p1-1, q1-1, 1],   \
        [p2*q3, p2-1, q3, 1], \
        [p3*q2, p3, q2-1, 1], \
        [p4*q4, p4, q4, 1] ])
    det_D_1 = str(sym.det(D_1))
    NumToSign = {1: '-', 0: '+'}
    for i1 in range(2):
        for i2 in range(2):
            #            for i3 in range(2):
            for i4 in range(2):
                sy = det_D_1
                sy = sym.limit(sy, q1, i1, NumToSign[i1])
                sy = sym.limit(sy, q2, i2, NumToSign[i2])
                #                    sy = sym.limit(sy,q3,i3,NumToSign[i3])
                sy = sym.limit(sy, q4, i4, NumToSign[i4])
                #print(i1,i2,i4,':',sy)
                checkDeterminant(str(sy))
Esempio n. 9
0
def question7_2c(reponse):
    c = sp.Matrix([[4, 6, -3], [-4, 8, 12], [-4, 5, -1]])

    if np.abs(reponse - sp.det(c)) != 0:
        display(
            "Dans ce cas, la deuxième rangée a été multiplié par 4 et la troisième par -1"
        )
        display(
            Latex(
                "$ Soit: 4 \\times R_2 \\rightarrow R_2, -1 \\times R_3 \\rightarrow R_3  $"
            ))
        display("Le déterminant est donc:")
        display(
            Latex(
                '$ det|c| = (-1) \cdot (4) \cdot det|A| = -4 \cdot 155 = - 620 $'
            ))

        button = widgets.Button(description='Solution', disabled=False)
        box = HBox(children=[button])
        out = widgets.Output()

        @out.capture()
        def solution(e):
            out.clear_output()
            Determinant_3x3(c, step_by_step=True)

        button.on_click(solution)

        display(box)
        display(out)
    else:
        display("Bravo! Vous avez trouvé la réponse")
Esempio n. 10
0
def getLimit():
    """
        Symbol declaration.
    """
    p1 = sym.Symbol('p1')
    p2 = sym.Symbol('p2')
    p3 = sym.Symbol('p3')
    p4 = sym.Symbol('p4')
    q1 = sym.Symbol('q1')
    q2 = sym.Symbol('q2')
    q3 = sym.Symbol('q3')
    q4 = sym.Symbol('q4')
    """
        Get all expressions of extrema.
        Let p1, p2, p4 be 0 or 1.
        Then check whether it can be 0 or not.
        
        In this example we assume 0<p3<1, 
        we can also assume p1, p2, p4 in the same way.
    """
    for p1 in range(2):
        for p2 in range(2):
            #   for i3 in range(2):
            for p4 in range(2):
                D_1 = sym.Matrix( \
                    [[p1*q1-1, p1-1, q1-1, 1],   \
                     [p2*q3, p2-1, q3, 1], \
                     [p3*q2, p3, q2-1, 1], \
                     [p4*q4, p4, q4, 1] ])
                det_D_1 = str(sym.det(D_1))
                """
                    Check whether a extreme value can be 0 with z3.
                """
                checkDeterminant(str(det_D_1))
Esempio n. 11
0
def calculateRouthTable(polynomial, epsilon, symbolic):
    dim = len(polynomial)
    coeff = dim
    columns = int(np.ceil(coeff / 2))
    RA = sym.zeros(coeff, columns)  # create the Routh table
    s = sym.Symbol('S')

    #assemble the first and second rows
    top = polynomial[0::2]
    down = polynomial[1::2]
    if len(top) != len(down):
        down.append(0)

    for i in range(len(top)):
        RA[0, i] += top[i]
        RA[1, i] += down[i]

    rows = coeff - 2  #number of rows that need determinants
    index = np.zeros(rows)

    for i in range(rows):
        index[rows - i - 1] = np.ceil((i + 1) / 2)

    for i in range(2, coeff):  #go from the 3rd row to the last
        if np.sum(np.abs(RA[i - 1, :])) == 0:  # while row is zero
            print(
                '\n Row of zeros detected in row %d. \n Finding Auxillary Polynomial by differentiating row %d'
                % (i, i - 1))
            order = coeff - i + 1
            order_arr = np.arange(order, -1, -2)
            poly = 0
            #get the polynomial for differentiation
            for k in range(len(order_arr)):
                poly += (s**(order_arr[k])) * RA[i - 2, k]
                diff = sp.diff(poly, s)
                a = sp.Poly(diff, s)
                c = a.coeffs()
            for l in range(columns - len(c)):
                c.append(0)
            for l in range(columns):
                RA[i - 1, l] = c[l]

        elif RA[i - 1:0] == 0:  # first element is zero
            print('\n First element is zero. Replacing with epsilon')
            RA[i - 1:0] = epsilon

        for j in range(int(index[i - 2])):
            if symbolic:
                RA[i, j] = -sym.det(
                    sym.Matrix([[RA[i - 2, 0], RA[i - 2, j + 1]],
                                [RA[i - 1, 0], RA[i - 1, j + 1]]])) / RA[i - 1,
                                                                         0]
            else:
                RA[i, j] = -my_det(
                    np.array([[RA[i - 2, 0], RA[i - 2, j + 1]],
                              [RA[i - 1, 0], RA[i - 1, j + 1]]
                              ]).astype(float)) / RA[i - 1, 0]

    return RA
Esempio n. 12
0
def area(p1, p2, p3):
	if not p1.is_normalized():
		p1 = Npoint(*p1)
	if not p2.is_normalized():
		p2 = Npoint(*p2)
	if not p3.is_normalized():
		p3 = Npoint(*p3)
	return S / 2 * sympy.det(sympy.Matrix([list(p1), list(p2), list(p3)]))
Esempio n. 13
0
	def print_slater(self, this_state):
		result = 0
		occupations, amplitudes = self.get_occupations (this_state)
		for i, occ in enumerate(occupations):
			this_phi = bitwise_filter(self.phis, occ)
			this_mat = M([this_phi]*len(this_phi))
			result += amplitudes[i]/sp.sqrt(len(this_phi))*sp.det (this_mat)
		return result
Esempio n. 14
0
def question7_2(reponse):
    A = sp.Matrix([[4, 6, -3], [-1, 2, 3], [4, -5, 1]])

    if np.abs(reponse - sp.det(A)) != 0:
        Determinant_3x3(A, step_by_step=True)
    else:
        display(
            "Bravo! Vous avez trouvé la réponse. Utilisez cette réponse pour les prochaines questions."
        )
Esempio n. 15
0
def question7_2a(reponse):
    a = sp.Matrix([[4, -1, 4], [6, 2, -5], [-3, 3, 1]])

    if np.abs(reponse - sp.det(a)) != 0:
        display(
            "Dans ce cas, cette matrice est la transposée de A. Les déterminants sont égaux."
        )
        Determinant_3x3(a, step_by_step=True)
    else:
        display("Bravo! Vous avez trouvé la réponse")
Esempio n. 16
0
def question7_2d(reponse):
    d = sp.Matrix([[4, 6, -3], [-1, 2, 3], [-8, 10, -2]])

    if np.abs(reponse - sp.det(d)) != 0:
        display("Dans ce cas, la troisième rangée est multipliée par -2 ")
        display(Latex("$ Soit: -2 \\times R_3 \\rightarrow R_3 $"))
        display("Le déterminant est donc:")
        display(Latex("$ det|d| = (-2) \cdot det|A| = -2 \cdot 155 = - 310 $"))
        Determinant_3x3(d, step_by_step=True)
    else:
        display("Bravo! Vous avez trouvé la réponse.")
Esempio n. 17
0
def question7_4b_solution(detC, somme):
    A = sp.Matrix([[1, 3, -6], [5, 2, 2], [-2, -4, 9]])
    B = sp.Matrix([[5, 0, -2], [10, -3, 7], [-1, 4, 1]])
    C = sp.Matrix([[6, 3, -8], [15, -1, 9], [-3, 0, 10]])
    flag1 = False
    flag2 = False

    if detC != sp.det(C):
        display(Markdown('Votre solution pour $\det(A+B) $ est fausse'))
        flag1 = True
    if somme != (sp.det(A) + sp.det(B)):
        display(Markdown('Votre solution pour $\det A + \det B$ est fausse'))
        flag1 = True
    else:
        display(
            Markdown(
                "Correct! $\det(A+B)$ n'est pas égale à $\det A + \det B $"))

    if flag1:
        question7_4b(A, B, C)
Esempio n. 18
0
    def callback(e):
        out.clear_output()

        with out:
            if len(select.value) <= 0:
                pass
            elif len(select.value) > 1:
                display(Markdown('Seulement une réponse est requise'))
            elif sp.det(A) == 0:
                if "La matrice n'est pas inversible" not in select.value:
                    display(Markdown("Faux"))
                    question3c(A)
                else:
                    display(Markdown("Correct!"))
            elif sp.det(A) != 0:
                if 'La matrice est inversible' not in select.value:
                    display(Markdown("Faux"))
                    question3c(A)
                else:
                    display(Markdown("Correct!"))
Esempio n. 19
0
def test_StateSpaceModel_create():
    a, b = symbols('a, b')

    A = Matrix([[2 * a, a], [3 * b, b]])

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

    C = Matrix([[2, 4 * b]])

    cs = StateSpaceModel(A, B, C)
    assert cs.A == A

    print(cs)
    print(repr(cs))

    cm = cs.controllability_matrix()
    print(cm)
    assert cm == Matrix([[0, a], [1, b]])
    print(det(cm))
    assert det(cm) == -a
Esempio n. 20
0
def question7_2b(reponse):
    b = sp.Matrix([[4, 6, -3], [7, 14, -3], [4, -5, 1]])

    if np.abs(reponse - sp.det(b)) != 0:
        display(
            "Dans ce cas, la première rangée a été multiplié par deux et elle a été ajouté à la deuxième rangée"
        )
        display(Latex("$ Soit: 2 \\times R_1 + R_2 \\rightarrow R_2 $"))
        display("Le déterminant est le même")
        Determinant_3x3(b, step_by_step=True)
    else:
        display("Bravo! Vous avez trouvé la réponse")
Esempio n. 21
0
def test_System1():
    # Define symbols for parameters
    a, b = symbols('a, b')

    # Define vector for states
    x1, x2 = symbols('x1, x2')

    # Define state vector field: f(x)
    f = Matrix([-x1 + a * x2 + sin(x1), -x2 * cos(x1)])

    # Define control vector field: g(x)
    g = Matrix([0, cos(x1) + b])

    x = Matrix([x1, x2])

    cs = from_control_affine_form(f, g, x)
    assert cs.f == f

    cm = cs.controllability_matrix()
    print(cm)
    assert cm == Matrix([[0, -a * (b + cos(x1))],
                         [
                             b + cos(x1), (b + cos(x1)) * cos(x1) -
                             (a * x2 - x1 + sin(x1)) * sin(x1)
                         ]])
    print(det(cm))
    assert det(cm) == a * (b + cos(x1))**2

    print(cs)
    assert cs.find_dependency() == x1
    tr = cs.transformation()
    print(tr)
    assert tr == Matrix([x1, a * x2 - x1 + sin(x1)])

    assert cs.beta() == 1 / (a * (b + cos(x1)))

    assert cs.alpha() == 1 / (a * (b + cos(x1))) * (-a * x2 * cos(x1) +
                                                    (cos(x1) - 1) *
                                                    (a * x2 - x1 + sin(x1)))
Esempio n. 22
0
    def __init__(self, defining_quantities):
        """

        :param defining_quantities: tuples of length 3: (quantity_name unit_name,PhysicalQuantity)
        All quantities must share the same system
        TODO option to build the quantity name from the underlying system quantity_string
        """
        #TODO The naming must be better handled ! A system similar to the physicalsystem must be taken to have names
        #TODO for the quantities that are expressed within the system
        #TODO Best would be to align the structure of defining_quantities better with the parent class

        # TODO Check input structure
        # system = None
        # for Quq in defining_quantities:
        #     if system is None:
        #         system = Quq[2].system
        #     else:
        #         assert Quq[2].system == system
        #         Quq[2].name = Quq[1]

        # No zero value can be used
        assert all([Quq[2].value != 0 for Quq in defining_quantities])

        # Load data
        self.quantity_definitions = []
        self.quantities = []
        for Q, u, q in defining_quantities:
            self.quantity_definitions.append((Q, u))
            if isinstance(q, MeasurementQuantity):
                self.quantities.append(q.underlying_quantity())
            elif isinstance(q, PhysicalQuantity):
                self.quantities.append(q)
            else:
                raise TypeError("Need quantities")
        self.physical_system = self.quantities[0].system
        for q in self.quantities:
            assert self.physical_system == q.system, "All quantities must have the same underlying system"

        # Build the transfer matrix, check that it is invertible
        first_row = Matrix([1] + [0] * len(defining_quantities))
        log_qs = Matrix([log(q.value) for Q, u, q in defining_quantities])
        Y = Matrix([list(q.dimension) for Q, u, q in defining_quantities])
        self.matrix = Y.col_insert(0,
                                   log_qs).row_insert(0, first_row.transpose())
        Yinv = Y.inv()
        assert det(self.matrix) != 0
        # Build the inverse transfer matrix
        # We exploit the block structure to avoid mixing floats of the logs with potential int/rationals
        # that are in the exponent matrix Y/Yinv
        self.inverse_matrix = Yinv.col_insert(0, -Yinv * log_qs).row_insert(
            0, first_row.transpose())
Esempio n. 23
0
def _integrate_exact(k, pyra):
    def f(x):
        return x[0] ** int(k[0]) * x[1] ** int(k[1]) * x[2] ** int(k[2])

    # map the reference hexahedron [-1,1]^3 to the pyramid
    xi = sympy.DeferredVector("xi")
    pxi = (
        +pyra[0] * (1 - xi[0]) * (1 - xi[1]) * (1 - xi[2]) / 8
        + pyra[1] * (1 + xi[0]) * (1 - xi[1]) * (1 - xi[2]) / 8
        + pyra[2] * (1 + xi[0]) * (1 + xi[1]) * (1 - xi[2]) / 8
        + pyra[3] * (1 - xi[0]) * (1 + xi[1]) * (1 - xi[2]) / 8
        + pyra[4] * (1 + xi[2]) / 2
    )

    pxi = [sympy.expand(pxi[0]), sympy.expand(pxi[1]), sympy.expand(pxi[2])]
    # determinant of the transformation matrix
    J = sympy.Matrix(
        [
            [
                sympy.diff(pxi[0], xi[0]),
                sympy.diff(pxi[0], xi[1]),
                sympy.diff(pxi[0], xi[2]),
            ],
            [
                sympy.diff(pxi[1], xi[0]),
                sympy.diff(pxi[1], xi[1]),
                sympy.diff(pxi[1], xi[2]),
            ],
            [
                sympy.diff(pxi[2], xi[0]),
                sympy.diff(pxi[2], xi[1]),
                sympy.diff(pxi[2], xi[2]),
            ],
        ]
    )
    det_J = sympy.det(J)
    # we cannot use abs(), see <https://github.com/sympy/sympy/issues/4212>.
    # abs_det_J = sympy.Piecewise((det_J, det_J >= 0), (-det_J, det_J < 0))
    # This is quite the leap of faith, but sympy will cowardly bail out
    # otherwise.
    abs_det_J = det_J

    exact = sympy.integrate(
        sympy.integrate(
            sympy.integrate(abs_det_J * f(pxi), (xi[2], -1, 1)), (xi[1], -1, +1)
        ),
        (xi[0], -1, +1),
    )

    return float(exact)
Esempio n. 24
0
def self_intersection():
    # starting from the required conditions in the case of a cubic:
    # a3(t² + st + s²) + a2(t + s) + a1 = 0
    # b3(t² + st + s²) + b2(t + s) + b1 = 0

    x, y, t, s = map(Symbol, ['x', 'y', 't', 's'])

    q1, q2, q3 = map(Symbol, ['q1', 'q2', 'q3'])
    a3, a2, a1, a0 = map(Symbol, ['a3', 'a2', 'a1', 'a0'])
    b3, b2, b1, b0 = map(Symbol, ['b3', 'b2', 'b1', 'b0'])
    a2_, a1_, a0_ = map(Symbol, ['a2_', 'a1_', 'a0_'])
    b2_, b1_, b0_ = map(Symbol, ['b2_', 'b1_', 'b0_'])
    A3, A2, A1, A0 = map(Symbol, ['A3', 'A2', 'A1', 'A0'])
    B3, B2, B1, B0 = map(Symbol, ['B3', 'B2', 'B1', 'B0'])
    x3, x2, x1, x0 = map(Symbol, ['x3', 'x2', 'x1', 'x0'])
    y3, y2, y1, y0 = map(Symbol, ['y3', 'y2', 'y1', 'y0'])

    Q1 = a2_ * b1_ - a1_ * b2_
    Q2 = a2_ * b0_ - a0_ * b2_
    Q3 = a1_ * b0_ - a0_ * b1_

    M = Matrix([[q1, q2], [q2, q3]])

    m = det(M)

    m = m.subs(q1, Q1).subs(q2, Q2).subs(q3, Q3)

    m = m.subs(a2_, a3).subs(b2_, b3)
    m = m.subs(a1_, a3 * s + a2).subs(b1_, b3 * s + b2)
    m = m.subs(a0_, a3 * s**2 + a2 * s + a1).subs(b0_, b3 * s**2 + b2 * s + b1)

    m = expand(-1 * m)

    m = collect(m, s)

    A3 = x3 - 3 * x2 + 3 * x1 - x0
    A2 = 3 * x2 - 6 * x1 + 3 * x0
    A1 = 3 * x1 - 3 * x0
    B3 = y3 - 3 * y2 + 3 * y1 - y0
    B2 = 3 * y2 - 6 * y1 + 3 * y0
    B1 = 3 * y1 - 3 * y0

    m = m.subs(a3, A3).subs(a2, A2).subs(a1, A1)
    m = m.subs(b3, B3).subs(b2, B2).subs(b1, B1)

    m = expand(m)

    m = collect(m, s)

    print(m)
 def generate_alpha(self,
                    epsilon=[0, 0, 0, 0, 0, 0],
                    preserve_volume=False):
     '''Computes the (symmetric) deformation matrix in Cartesian coordinates that would lead to infinitesimal strain epsilon,i.e.
     alpha=1+epsilon, where epsilon is first converted to Cartesian notation. If preserve_volume is set to True, alpha will subsequently be rescaled by its determinant.'''
     alpha = UnVoigt(np.asarray(epsilon) + np.array([1, 1, 1, 0, 0, 0]))
     if preserve_volume:
         determinant = sp.det(sp.Matrix(alpha))
         if isinstance(determinant, sp.Float):
             alpha = alpha / (float(determinant)**(1 / 3))
         else:
             alpha = alpha / sp.cbrt(sp.factor(determinant))
     self.alpha = alpha
     return alpha
Esempio n. 26
0
    def apply(self, polys, xlist, alist, evaluation):
        'ClassicalDixonResultant[polys_, xlist_,alist_]'
        ####this is not written in a wrapper function as it is not used anywhere else

        res = DixonMatrix_apply(polys, xlist, alist)
        if isinstance(res, String):
            return res
        if res.to_sympy() == sympy.sympify(0):
            return res
        rsym = res.leaves
        dixon_list = [j.leaves for j in rsym]

        dixon_sym = [[j.to_sympy() for j in i] for i in dixon_list]
        dix_mat = sympy.Matrix(dixon_sym)
        return from_sympy(sympy.det(dix_mat))
Esempio n. 27
0
def _integrate_exact(f, hexa):
    xi = sympy.DeferredVector('xi')
    pxi = \
        + hexa[0] * 0.125*(1.0 - xi[0])*(1.0 - xi[1])*(1.0 - xi[2]) \
        + hexa[1] * 0.125*(1.0 + xi[0])*(1.0 - xi[1])*(1.0 - xi[2]) \
        + hexa[2] * 0.125*(1.0 + xi[0])*(1.0 + xi[1])*(1.0 - xi[2]) \
        + hexa[3] * 0.125*(1.0 - xi[0])*(1.0 + xi[1])*(1.0 - xi[2]) \
        + hexa[4] * 0.125*(1.0 - xi[0])*(1.0 - xi[1])*(1.0 + xi[2]) \
        + hexa[5] * 0.125*(1.0 + xi[0])*(1.0 - xi[1])*(1.0 + xi[2]) \
        + hexa[6] * 0.125*(1.0 + xi[0])*(1.0 + xi[1])*(1.0 + xi[2]) \
        + hexa[7] * 0.125*(1.0 - xi[0])*(1.0 + xi[1])*(1.0 + xi[2])
    pxi = [
        sympy.expand(pxi[0]),
        sympy.expand(pxi[1]),
        sympy.expand(pxi[2]),
    ]
    # determinant of the transformation matrix
    J = sympy.Matrix([
        [
            sympy.diff(pxi[0], xi[0]),
            sympy.diff(pxi[0], xi[1]),
            sympy.diff(pxi[0], xi[2])
        ],
        [
            sympy.diff(pxi[1], xi[0]),
            sympy.diff(pxi[1], xi[1]),
            sympy.diff(pxi[1], xi[2])
        ],
        [
            sympy.diff(pxi[2], xi[0]),
            sympy.diff(pxi[2], xi[1]),
            sympy.diff(pxi[2], xi[2])
        ],
    ])
    det_J = sympy.det(J)
    # we cannot use abs(), see <https://github.com/sympy/sympy/issues/4212>.
    # pylint: disable=invalid-unary-operand-type
    abs_det_J = sympy.Piecewise((det_J, det_J >= 0), (-det_J, det_J < 0))
    g_xi = f(pxi)
    exact = \
        sympy.integrate(
            sympy.integrate(
                sympy.integrate(abs_det_J * g_xi, (xi[2], -1, 1)),
                (xi[1], -1, 1)
            ),
            (xi[0], -1, 1)
        )
    return float(exact)
Esempio n. 28
0
def Sarrus_3x3(A):
    if A.shape != (3, 3):
        raise ValueError(
            'Dimension of matrix A should be 3x3. The input A must be a sp.Matrix of shape (3,3).'
        )

    # Construct string for determinant of matrix A
    detA_s = sp.latex(A).replace('[', '|').replace(']', '|')

    A11 = sp.latex(A[0, 0])
    A12 = sp.latex(A[0, 1])
    A13 = sp.latex(A[0, 2])
    A21 = sp.latex(A[1, 0])
    A22 = sp.latex(A[1, 1])
    A23 = sp.latex(A[1, 2])
    A31 = sp.latex(A[2, 0])
    A32 = sp.latex(A[2, 1])
    A33 = sp.latex(A[2, 2])

    x1 = '(' + A11 + '\cdot ' + A22 + '\cdot ' + A33 + ')'
    x2 = '(' + A12 + '\cdot ' + A23 + '\cdot ' + A31 + ')'
    x3 = '(' + A13 + '\cdot ' + A21 + '\cdot ' + A32 + ')'

    y1 = '(' + A13 + '\cdot ' + A22 + '\cdot ' + A31 + ')'
    y2 = '(' + A11 + '\cdot ' + A23 + '\cdot ' + A32 + ')'
    y3 = '(' + A12 + '\cdot ' + A21 + '\cdot ' + A33 + ')'

    prod1 = A[0, 0] * A[1, 1] * A[2, 2]
    prod2 = A[0, 1] * A[1, 2] * A[2, 0]
    prod3 = A[0, 2] * A[1, 0] * A[2, 1]

    prod4 = A[0, 2] * A[1, 1] * A[2, 0]
    prod5 = A[0, 0] * A[1, 2] * A[2, 1]
    prod6 = A[0, 1] * A[1, 0] * A[2, 2]

    display(
        Latex('$' + detA_s + ' = ' + x1 + "+" + x2 + "+" + x3 + "-" + y1 +
              "-" + y2 + "-" + y3 + '$'))
    display(Latex('$' + detA_s + ' = ' + sp.latex(sp.simplify(prod1)) + " + " + sp.latex(sp.simplify(prod2)) + " + " \
                  + sp.latex(sp.simplify(prod3)) + " - [(" + sp.latex(sp.simplify(prod4)) + ") + ("\
                  + sp.latex(sp.simplify(prod5)) + ") + (" + sp.latex(sp.simplify(prod6)) + ')] $'))
    display(
        Latex('$' + detA_s + ' = ' +
              sp.latex(sp.simplify(prod1 + prod2 + prod3)) + ' - ' +
              sp.latex(sp.simplify(prod4 + prod5 + prod6)) + '$'))

    display(
        Latex('$' + detA_s + ' = ' + sp.latex(sp.simplify(sp.det(A))) + '$'))
Esempio n. 29
0
def impl_quad():
    x, y, t = map(Symbol, ['x', 'y', 't'])

    q1, q2, q3 = map(Symbol, ['q1', 'q2', 'q3'])
    r1, r2 = map(Symbol, ['r1', 'r2'])
    R1R1, R1R2, Q1R1 = map(Symbol, ['R1R1', 'R1R2', 'Q1R1'])

    a2, a1, a0 = map(Symbol, ['a2', 'a1', 'a0'])
    b2, b1, b0 = map(Symbol, ['b2', 'b1', 'b0'])
    #c2, c1, c0 = map(Symbol, ['c2','c1','c0'])
    #d2, d1, d0 = map(Symbol, ['d2','d1','d0'])

    Q1 = a2 * b1 - a1 * b2
    Q2 = a2 * b0 - a0 * b2
    Q3 = a1 * b0 - a0 * b1

    R1 = b1 * x - a1 * y
    R2 = b2 * x - a2 * y

    M = Matrix([[q1, q2 + r2], [q2 + r2, q3 + r1]])

    m = det(M)
    #m = expand(m)

    R1R1 = R1 * R1
    #print(R1R1)
    R1R1 = expand(R1R1)
    #print(R1R1)

    print(m)
    print()
    m = expand(m)

    print(m)
    print()
    m = m.subs(r1, R1).subs(r2, R2)
    #m = m.subs(q1,Q1).subs(q2,Q2).subs(q3,Q3)

    m = expand(m)
    print(m)

    #X = c3*t**3 + c2*t**2 + c1*t + c0
    #Y = d3*t**3 + d2*t**2 + d1*t + d0
    #m = m.subs(x,X).subs(y,Y)

    #print(m)
    return M
Esempio n. 30
0
def hurwitz(Dcoeffs):
    """
    compute determinants for hurwitz stability criteria (see Section 4.5)

    Inputs:
        Dcoeffs - coefficients of denominator polynomial ordered from highest order to lowest

    Returns:
        the determinants to be used for evaluating stability via the Hurwitz criterion
    """
    assert (isinstance(Dcoeffs, list))
    # rescale D's coefficients so that coefficient on s^k is 1, where k is the order of the denominator
    rescaledCoeffs = [d / Dcoeffs[0] for d in Dcoeffs]
    # zero pad
    order = len(rescaledCoeffs) - 1
    coeffsPadded = sp.zeros(2 * order, 1)
    for i in range(order + 1):
        coeffsPadded[i] = rescaledCoeffs[i]
    hurwitzDeterminants = []
    for i in range(order):
        # construct subminor matrix
        Co = sp.zeros(i + 1, i + 1)
        skip = 0
        for j in range(i + 1):
            if j > 0 and j % 2 == 0:
                skip += 1
            if j % 2 == 0:
                # put odd coefficients (a1, a3, a5...)
                k = skip
                ii = 0
                while k <= i:
                    Co[j, k] = coeffsPadded[2 * ii + 1]
                    ii += 1
                    k += 1
            else:
                # put even coefficients (a0=1, a2, a4...)
                k = skip
                ii = 0
                while k <= i:
                    Co[j, k] = coeffsPadded[2 * ii]
                    ii += 1
                    k += 1
        Do = sp.simplify(sp.det(Co))
        hurwitzDeterminants.append(Do)
    return hurwitzDeterminants
Esempio n. 31
0
def test_System2():
    I, b, k, m, L, grav = symbols('I, b, k, m, L, g')

    q = Matrix(symbols(r'theta_1, theta_2'))
    dq = Matrix(symbols(r'\dot{\theta}_1, \dot{\theta}_2'))
    x = Matrix([q, dq])

    f = Matrix([
        x[2], x[3], 1 / I * (-b * x[2] - k * (x[0] - x[1])),
        1 / (m * L**2) * (k * (x[0] - x[1]) - m * grav * L * sin(x[1]))
    ])

    g = Matrix([0, 0, 1 / I, 0])

    cs = from_control_affine_form(f, g, x)
    assert det(cs.controllability_matrix()) == -k**2 / (I**4 * L**4 * m**2)

    assert cs.beta() == I * m * L**2 / k
Esempio n. 32
0
def question7_2e(reponse):
    e = sp.Matrix([[-1, 2, 3], [4, 6, -3], [0, -11, 4]])

    if np.abs(reponse - sp.det(e)) != 0:
        display(
            "Dans ce cas, deux fois la première rangée a été ajouté à la troisième rangée."
        )
        display("Aussi les premières deux rangées sont échangées.")
        display(
            Latex(
                "$ Soit: 2 \\times R_1 + R_3 \\rightarrow R_3, R_1 \\leftrightarrow R_2 $"
            ))
        display("Le déterminant est donc:")
        display(
            Latex("$ det|e| = (-1) \cdot det|A| = (-1) \cdot 155 = - 155 $"))
        Determinant_3x3(e, step_by_step=True)
    else:
        display("Bravo! Vous avez trouvé la réponse.")
Esempio n. 33
0
def question7_2f(reponse):
    f = sp.Matrix([[4, -5, 8], [6, 10, 1], [-3, 15, -2]])

    if np.abs(reponse - sp.det(f)) != 0:
        display("Dans ce cas, la deuxième rangée a été multiplié par cinq.")
        display("Après ça, c''est la transposée de la matrice.")
        display(
            Latex(
                "$ Soit: 5 \\times R_2 \\rightarrow R_2, \: et \: transposée $"
            ))
        display("Le déterminant est donc:")
        display(
            Latex(
                "$ det|f| = 5 \cdot det|A|^T = 5 \cdot det|A| = 5 \cdot 155 = 755 $"
            ))
        Determinant_3x3(f, step_by_step=True)
    else:
        display("Bravo! Vous avez trouvé la réponse.")
# -*- coding: utf-8 -*-
from sympy import Matrix, solve, det, latex
from sympy.abc import x,y,z
from sympy.plotting import plot3d

P1 = (1,2,3)
P2 = (0,-1,1)
P3 = (-2,1,-2)

M = Matrix([[x-P1[0]     , y-P1[1]     , z-P1[2]]    ,
		    [P2[0]-P1[0] , P2[1]-P1[1] , P2[2]-P1[2]],
		    [P3[0]-P1[0] , P3[1]-P1[1] , P3[2]-P1[2]]])

sol = solve(det(M), z)
print(u"Ecuación implícita: %s = 0"%det(M))
print(u"Ecuación explícita: z=%s"%(sol[0]))
h = plot3d(sol[0], (x,0,5), (y,0,5), title="$z = %s$"%(latex(sol[0])))
h.save("img_01.png")
h.show()
Esempio n. 35
0
def line_through_two_points(p1, p2):
	l1, l2 = list(p1), list(p2)
	return Curve(sympy.det(sympy.Matrix([l1, l2, [x, y, z]])))
Esempio n. 36
0
def A_vector_to_axis(vector,axis=[1.,0.,0.]):
    """
    http://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d
        http://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d/180436#180436
    
    """
    vector = sp.Matrix(vector)
    leng = vector.norm()
    axis   = sp.Matrix(axis).reshape(3,1)
    vector = sp.Matrix(vector).reshape(3,1)*1./leng
    

    if vector[1] == 0 and vector[2] == 0 or axis[1] == 0 and axis[2] == 0:
        Gx = sp.eye(3)
#        Gx[1,1] = sp.sign(vector[1])*Gx[1,1]
#        Gx[2,2] = sp.sign(vector[2])*Gx[2,2]
    else:
        axis_yz, vector_yz = axis[[1,2],[0]].normalized(),vector[[1,2],[0]].normalized()
        Gx = sp.Matrix([[1, 0,                                       0],
                        [0, vector_yz.dot(axis_yz),                  -sp.det(vector_yz.col_insert(1,axis_yz))],
                        [0, sp.det(vector_yz.col_insert(1,axis_yz)), vector_yz.dot(axis_yz)]])
        
        ang_rel_x = np.angle(np.complex(vector_yz[0],vector_yz[1])) - np.angle(np.complex(axis_yz[0],axis_yz[1]))
        Gx = [Gx,-Gx][ang_rel_x >= np.pi/2]
        Gx = [Gx,-Gx][ang_rel_x < -np.pi/2]
        check_x = ['ERROR ON KEY: %s at Gx' %key,'OK'][ round((Gx[[1,2],[1,2]]*vector_yz)[0],3) == round(axis_yz[0],3) and round((Gx[[1,2],[1,2]]*vector_yz)[1],3) == round(axis_yz[1],3) ]
        print check_x
        
#        Gx = [Gx,Gx][np.angle(np.complex(vector_yz[0],vector_yz[1])) < 0]
#        Gx = [Gx,-Gx.T][np.angle(np.complex(vector_yz[0],vector_yz[1])) >= np.pi/2 or np.angle(np.complex(vector_yz[0],vector_yz[1])) < np.pi/2]
      
      
    if vector[2] == 0 and vector[0] == 0 or axis[2] == 0 and axis[0] == 0:
        Gy = sp.eye(3)
    else:
        axis_zx, vector_zx = axis[[2,0],[0]].normalized(),vector[[2,0],[0]].normalized()
        ang_rel_y = np.angle(np.complex(vector_zx[0],vector_zx[1])) - np.angle(np.complex(axis_zx[0],axis_zx[1]))
        
        Gy = sp.Matrix([[vector_zx.dot(axis_zx),                    0, sp.det(vector_zx.col_insert(1,axis_zx))],
                        [0,                                         1, 0],
                        [-sp.det(vector_zx.col_insert(1,axis_zx)),  0, vector_zx.dot(axis_zx)]])


        Gy2 =sp.Matrix([[sp.cos(-ang_rel_y),                    0, sp.sin(-ang_rel_y)],
                        [0,                                         1, 0],
                        [-sp.sin(-ang_rel_y),  0, sp.cos(-ang_rel_y)]])
        
        
        
        Gy = [Gy,Gy.T][ang_rel_y >= np.pi/2 and len(key) != 4]
        Gy = [Gy,Gy][ang_rel_y < -np.pi/2]
        check_y = ['ERROR ON KEY: %s at Gy, angle = %f' %(key,np.angle(np.complex(vector_zx[0]+axis_zx[0],vector_zx[1]+axis_zx[1]))),
                   'OK ON KEY: %s at Gy, angle = %f' %(key,np.angle(np.complex(vector_zx[0]+axis_zx[0],vector_zx[1]+axis_zx[1])))][ round((Gy[[2,0],[2,0]]*vector_zx)[0],3) == round(axis_zx[0],3) and round((Gy[[2,0],[2,0]]*vector_zx)[1],3) == round(axis_zx[1],3) ]
        print check_y
#        Gy = [Gy,Gy][np.angle(np.complex(vector_zx[0],vector_zx[1])) < 0]
#        Gy = [Gy,-Gy.T][np.angle(np.complex(vector_zx[0],vector_zx[1])) >= np.pi/2 or np.angle(np.complex(vector_zx[0],vector_zx[1])) < np.pi/2]
        
                
    if vector[0] == 0 and vector[1] == 0 or axis[0] == 0 and axis[1] == 0:
        Gz = sp.eye(3)
    else:
        axis_xy, vector_xy = axis[[0,1],[0]].normalized(),vector[[0,1],[0]].normalized()
        ang_rel_z = np.angle(np.complex(vector_xy[0],vector_xy[1])) - np.angle(np.complex(axis_xy[0],axis_xy[1]))
        
        Gz = sp.Matrix([[vector_xy.dot(axis_xy),                  -sp.det(vector_xy.col_insert(1,axis_xy)), 0],
                        [sp.det(vector_xy.col_insert(1,axis_xy)), vector_xy.dot(axis_xy),                   0],
                        [0,                                       0,                                        1]])
        
        Gz2 =sp.Matrix([[sp.cos(-ang_rel_z),                  -sp.sin(-ang_rel_z), 0],
                        [sp.sin(-ang_rel_z), sp.cos(-ang_rel_z),                   0],
                        [0,                                       0,                                        1]])

        
        Gz = [Gz,Gz.T][ang_rel_z >= np.pi/2 and len(key) != 4]
        Gz = [Gz,Gz.T][ang_rel_z < -np.pi/2]
        check_z = ['ERROR ON KEY: %s at Gz' %key,'OK'][ round((Gz[[0,1],[0,1]]*vector_xy)[0],3) == round(axis_xy[0],3) and round((Gz[[0,1],[0,1]]*vector_xy)[1],3) == round(axis_xy[1],3) ]
        print check_z
#        Gz = [Gz,-Gz][np.angle(np.complex(vector_xy[0],vector_xy[1])) >= np.pi/2 or np.angle(np.complex(vector_xy[0],vector_xy[1])) < np.pi/2]
###        Gz = [Gz,-Gz][np.angle(np.complex(vector_xy[0],vector_xy[1])) < 0]#sum(np.sign(vector_xy)) == -2]
###        Gz = [Gz,Gz.T][np.angle(np.complex(vector_xy[0],vector_xy[1])) >= np.pi/2 or np.angle(np.complex(vector_xy[0],vector_xy[1])) < np.pi/2]
    G = Gz*Gy*Gx

    check = ['ERROR ON KEY: %s at G' %key,'OK!'][ G*vector == sp.Matrix(axis) ]
    print check


    U = G
    return U
Esempio n. 37
0
def collinear(p1, p2, p3):
	l1, l2, l3 = list(p1), list(p2), list(p3)
	return sympy.simplify(sympy.Eq(sympy.det(sympy.Matrix([l1, l2, l3])), 0))
Esempio n. 38
0
# INVOLUTIVITY EXAMPLE 1
# (see Applied Nonlinear Control by Slotine&Li (Chapter 6.2, Example 6.9))

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

# involutive distribution defined by the vector fields
f1 = sp.Matrix([4*x3, -1, 0])
f2 = sp.Matrix([-x1, x3**2-3*x2, 2*x3])

# checking involutivity (simple)
# lie bracket [f1,f2]
ff12 = lt.lie_bracket(f1,f2,[x1,x2,x3])

M12 = sp.Matrix(np.hstack([f1,f2,ff12]))
assert sp.det(M12) == 0

# checking involutivity (with function)
assert involutive([f1,f2], x1,x2,x3) == True

## INVOLUTIVITY EXAMPLE 2

# non-involutive distribution defined by the vector fields
f3 = sp.Matrix([4*x3, -1, 0])
f4 = sp.Matrix([-x2, x3**2-3*x2, 2*x1])

assert involutive([f3,f4], x1,x2,x3) == False

# INVOLUTIVITY EXAMPLE 3
# see http://www.roebenack.de/content/example-involutiveintegrable-distribution
   [1, 1],
   [1, 1],
   [1, 1],
   [1, 1]])

W = BlockMatrix([[X, X]])
g = theano_function([X], [W])
g([[1, 1],
   [1, 1],
   [1, 1]])
g(X)

h = theano_function([x, y], [z])

U = MatrixSymbol('U', 3, 3)
h = theano_function([U], [det(U)])
timeit(h([[1, 1, 1], [1, 1, 1], [1, 1, 1]]))


g_a = g.at(dict(w=Matrix(w_value)))
g_a.pprint()

g_max = g.max()
g_max.pprint()

g_a_max = g_a.max()
g_a_max.pprint()

g_m_wz = g.marginalize(('w', 'z'))
g_m_wz.pprint()