Beispiel #1
0
    def inv(self):

        return self.__class__(sym.Matrix(self).inv())
    Cp[3, 3], Cp[4, 4], Cp[5, 5] = cp44, cp55, cp66

    Cpp = sp.zeros(6, 6)
    Cpp[0, 1], Cpp[0, 2] = -cpp12, -cpp13
    Cpp[1, 0], Cpp[1, 2] = -cpp21, -cpp23
    Cpp[2, 0], Cpp[2, 1] = -cpp31, -cpp32
    Cpp[3, 3], Cpp[4, 4], Cpp[5, 5] = cpp44, cpp55, cpp66

    T = sp.zeros(6, 6)
    T[0, 0], T[0, 1], T[0, 2] = 2, -1, -1
    T[1, 0], T[1, 1], T[1, 2] = -1, 2, -1
    T[2, 0], T[2, 1], T[2, 2] = -1, -1, 2
    T[3, 3], T[4, 4], T[5, 5] = 3, 3, 3
    T *= sp.Rational(1, 3)

    s = sp.Matrix([0, sq, sx, 0, 0, sqx])

    def vectomat(x):
        return sp.Matrix([[x[0], x[3], x[4]], [x[3], x[1], x[5]],
                          [x[4], x[5], x[2]]])

    Sp = vectomat(Cp * T * s)
    Spp = vectomat(Cpp * T * s)

    Sp = list(Sp.eigenvals())
    Spp = list(Spp.eigenvals())

    if name in ['h8', 'anis']:
        k = 8.0
    else:
        k = 2.0
import sympy as sym


def get_values(x, keys):
    x = x.tolist()
    x = [val for sublist in x for val in sublist]
    values = dict(zip(keys, x))
    return values


alpha = sym.Symbol('a')
expression = sym.sympify(
    '(x1+10*x2)**2 + 5*(x3-x4)**2 + (x2- 2*x3)**4 +10*(x1-x4)**4')
values = {'x1': 3, 'x2': -1, 'x3': 0, 'x4': 1}
var_list = list(expression.free_symbols)
grad = sym.Matrix([sym.diff(expression, i) for i in var_list])
hess = sym.hessian(expression, list(expression.free_symbols))
x = sym.Matrix(var_list)
eps = 1e-5
hess_inv = hess.inv()
iteration = 0
while (1):
    iteration = iteration + 1
    x_new = (x - sym.Matrix(hess_inv.dot(grad))).subs(values).evalf()
    diff = x_new - x.subs(values).evalf()
    error = diff.norm()
    values = get_values(x_new, values.keys())
    x = x_new
    if (error < eps):
        break
    if (iteration == 3):
def gradVec2(u_vec, x, y):
    return sp.Matrix([[sp.diff(u_vec[0], x),
                       sp.diff(u_vec[1], x)],
                      [sp.diff(u_vec[0], y),
                       sp.diff(u_vec[1], y)]])
def gradScalar2(u, x, y):
    return sp.Matrix([sp.diff(u, x), sp.diff(u, y)])
Beispiel #6
0
import numpy as np
import sympy
'''
Requirements:
    -> f : R^n -> R is continuously differentiable function
    -> grad(f) is a system of (continuous) non-linear eq's
    -> Hessian(f) is an invertible matrix, continuous at all x in Neighbourhood(x*)
'''
d = int(input("Dimension of domain(f) = "))
f = str(input("f:R^n -> R where f(x0,x1,...,xn) = "))
x_b = sympy.Matrix(
    np.array(
        [input("Start point of NM (in the form x0 x1 ... xn) = ").split()],
        float)).transpose()

variables = np.array(['x' + str(i) for i in range(0, d)])
fx = sympy.Matrix(np.array([f]))
df = np.array([sympy.diff(f, var) for var in variables])
df_M = sympy.Matrix(df)

d2f = np.array([[sympy.diff(grad, var) for var in variables] for grad in df])
d2f_M = sympy.Matrix(d2f)

d2f_inv_M = d2f_M.inv()

n_iter = 0
#df_b = df_M.subs([(variables[j], x_b[j]) for j in range(0, d)])
#d2f_inv_b = d2f_inv_M.subs([(variables[j], x_b[j]) for j in range(0, d)])

x = 0
alpha = 0.5
Beispiel #7
0
import sympy as sp

lst = sp.symbols("x,y,z,a,b,c,d,e,f,g,h,i,j,k,l")

x = lst[0:3]
A = lst[3:12]
d = lst[12:15]

A = sp.Matrix([A[0:3], A[3:6], A[6:9]])
x = sp.Matrix([[i] for i in x])
d = sp.Matrix([[i] for i in d])
Beispiel #8
0
 def calc_Dx_this_mul_exp_x_at_0(self, x):
     return sympy.Matrix(1, 2, lambda r, c:
                         sympy.diff((self * So2.exp(x))[c], x))\
         .limit(x, 0)
Beispiel #9
0
 def Dxi_x_matrix(x, i):
     if i == 0:
         return sympy.Matrix([[1, 0], [0, 1]])
     if i == 1:
         return sympy.Matrix([[0, -1], [1, 0]])
Beispiel #10
0
 def calc_Dx_exp_x(x):
     return sympy.Matrix(1, 2, lambda r, c: sympy.diff(So2.exp(x)[c], x))
Beispiel #11
0
 def Dx_exp_x_at_0():
     return sympy.Matrix([[0, 1]])
Beispiel #12
0
 def matrix(self):
     """ returns matrix representation """
     return sympy.Matrix([[self.z.real, -self.z.imag],
                          [self.z.imag, self.z.real]])
Beispiel #13
0
 def hat(theta):
     return sympy.Matrix([[0, -theta], [theta, 0]])
Beispiel #14
0
def define_matrices():
    e = sm.zeros(7, 1)
    e[0] = sm.sympify('u1')
    e[1] = sm.sympify('c * u3 + s * v3')
    e[2] = sm.sympify('u2 - u1')
    e[3] = sm.sympify('v4 + u2n')
    e[4] = sm.sympify('u4 - u3')
    e[5] = sm.sympify('v3 + u1n')
    e[6] = sm.sympify('c * u4 + s * v4 - c * u1 + s * u1n')
    k = sm.Matrix(7, 1, lambda i, j: sm.Symbol('k%d' % i))

    psi = (k.T * e.applyfunc(lambda x: x**2))[0]
    work = sm.sympify('u1 * g1 + u2 * g2')

    w = ['u1', 'u2', 'u3', 'u4', 'v3', 'v4']
    wbar = w[:2]
    g = ['g1', 'g2']

    mtx_a = sm.zeros(6, 6)
    for ir in range(mtx_a.shape[0]):
        for ic in range(mtx_a.shape[1]):
            mtx_a[ir, ic] = sm.diff(sm.diff(psi, w[ir]), w[ic])

    mtx_b_bar = sm.zeros(2, 6)
    for ir in range(mtx_b_bar.shape[0]):
        for ic in range(mtx_b_bar.shape[1]):
            mtx_b_bar[ir, ic] = sm.diff(sm.diff(work, g[ir]), w[ic])

    mtx_b = sm.zeros(2, 2)
    for ir in range(mtx_b.shape[0]):
        for ic in range(mtx_b.shape[1]):
            mtx_b[ir, ic] = sm.diff(sm.diff(work, wbar[ir]), g[ic])

    mtx_c = sm.eye(2)

    sn1 = sm.diff(psi, 'u1n').subs('u1n', 0)
    sn2 = sm.diff(psi, 'u2n').subs('u2n', 0)
    sn = sm.Matrix([sn1, sn2])

    mtx_d = sm.zeros(2, 6)
    for ir in range(mtx_d.shape[0]):
        for ic in range(mtx_d.shape[1]):
            mtx_d[ir, ic] = sm.diff(sn[ir], w[ic])

    subsd = {'c': ca, 's': sa}
    for ii, _k in enumerate(k):
        subsd['k%d' % ii] = ks[ii]

    m = {
        'A': eval_matrix(mtx_a, **subsd),
        'Bb': eval_matrix(mtx_b_bar),
        'B': eval_matrix(mtx_b),
        'C': eval_matrix(mtx_c),
    }

    ms = convert_to_csr(m)

    m['sn'] = sn.subs(subsd)
    m['D'] = mtx_d.subs(subsd)
    m['fs'] = fs

    return m, ms, w
Beispiel #15
0
    def inv(self, method='ADJ'):

        return self.__class__(sym.Matrix(self).inv(method=method))
Beispiel #16
0
 def calc_Dxi_x_matrix(x, i):
     return sympy.Matrix(2, 2,
                         lambda r, c: sympy.diff(x.matrix()[r, c], x[i]))
Beispiel #17
0
def verify_5a(answer):

    import sympy

    M = sympy.Matrix([[-1, 1, 0], [1, -2, 1], [0, 1, -1]])
    return answer == M.eigenvects()
Beispiel #18
0
 def calc_Dx_exp_x_matrix_at_0(x):
     return sympy.Matrix(
         2, 2,
         lambda r, c: sympy.diff(So2.exp(x).matrix()[r, c], x)).limit(x, 0)
F = f(ts)
G = g(ts)
dF = sym.diff(F, ts)
ddF = sym.diff(dF, ts)
dG = sym.diff(G, ts)
ddG = sym.diff(dG, ts)
"""
print("F = ", F)
print("G = ", G)
print("dF = ", dF)
print("dG = ", dG)
print("ddG = ", ddG)
print("ddF = ", ddF)
"""

A_sym_triplet = sym.Matrix([[dG / G, -dF, 0], [+dF, 0, 1],
                            [+(dF * dG) / G, ddG / G, 0]])
#A_sym_triplet = sym.Matrix([[0, -dF, 1], [dF, dG/G, 0], [ddG/G, -dF*dG/G, 0]])

A_num_triplet = sym.lambdify((ts), A_sym_triplet, modules=array2mat)

triplet2 = {}
triplet2["name"] = "triplet2"
triplet2["title"] = "3D equation, with $x = e^{-t/4}\\cos((2 + \\cos(t))t)$"
triplet2["n"] = 10
triplet2["sigma"] = 4
triplet2["f"] = f
triplet2["g"] = g
triplet2["A_sym"] = A_sym_triplet
triplet2["A_num"] = A_num_triplet

Beispiel #20
0
 def _clean_dependence(A, b):
     _, indep_rows_numbers = sympy.Matrix(A).T.rref()
     indep_rows_numbers = list(indep_rows_numbers)
     A_indep = A[indep_rows_numbers]
     b_indep = b[indep_rows_numbers]
     return A_indep, b_indep
def zeroVec2():
    return sp.Matrix([sp.Integer(0), sp.Integer(0)])
Beispiel #22
0
    def no_constraints_projection(A, b, y):
        '''
        The function returns the projection of 
        y point to the linear subspace, which is 
        defined as follow:
        A x = b (*)
        where the projection is the point y^', such that 
        y^' = argmin(|y - y^'| where y^' satisfies (*))
        '''

        # check for the linear system A x = b is compatible
        assert (A.shape[0] == b.shape[0])

        A_rank = np.linalg.matrix_rank(A)
        A_augmented = np.append(A, b.reshape(b.shape[0], 1), axis=1)
        A_augmented_rank = np.linalg.matrix_rank(A_augmented)

        # Kronecker–Capelli theorem conditions:
        if A_rank == A_augmented_rank:
            # the system has solutions
            pass
        else:
            # the system has no solutions
            return (None)

        # Below we select numbers of the rows in the A matrix,
        # which are independent
        _, indep_rows_numbers = sympy.Matrix(A).T.rref()
        indep_rows_numbers = list(indep_rows_numbers)
        A_indep = A[indep_rows_numbers]
        b_indep = b[indep_rows_numbers]

        # Below we define and solve the final system
        '''
        1. Let's assume, that x_0 is the solution of the system:
        A x_0 = b

        2. So we can suppose, that we find projection of (y - x_0) vector
        on the linear subspace L defined as follow:
        A x = 0
        
        3. Let's define y_0 := (y - x_0) 

        4. Let's suppose, that y* is the solution of our task
        This means, that p = (y_0 - y*) vector orthogonal to L

        5. So, we can notice, that in view of rows a_1, ..., a_k 
        of A matrix are orthogonal to L and 
        <a_1, a_2 ... a_k> is the orthogonal component of L, so
        p \in <a_1, a_2 ... a_k>
        
        6. Let's suppose  {a_i_1, a_i_2, ... , a_i_m}, where m <= k ,is the 
        basis of <a_1, a_2 ... a_k>. 
        Define {a'_1, ... , a'_m } := {a_i_1, a_i_2, ... , a_i_m}

        7. Let's define A' := (a'_1, ... , a'_m) , where A' is the matrix
        and a'_i are rows of this matrix (In the code below A' = A_indep)
        Also let's define b' := (b_i_1, ... b_i_m) (In the code b' = b_indep)

        8. So p = alpha_1 * a'_1  + ... + alpha_m * a'_m
        In matrix symbols, p = A'.T * alpha

        9. Let.s notice, that y_0 - p = y*, 
        y* belongs to L, so 0 = A' y* = A' (y_0 - p) = 
        = A' y_0 - A' A'.T alpha = A' (y - x_0) - A' A'.T alpha =
        = A' y - b' - A' A'.T alpha

        10. So, we have got the formula:
        A' A'.T alpha = A' y - b'
        in the code it is equivalent to solving the 
        linear system:
          alpha = np.linalg.solve(Mat, vec)
        '''

        Mat = A_indep @ A_indep.T
        vec = A_indep @ y - b_indep
        alpha = np.linalg.solve(Mat, vec)

        res_vector = A_indep.T @ alpha
        res_point = y - res_vector
        return (res_point)
def divTen2(tensor, x, y):
    return sp.Matrix([
        sp.diff(tensor[0, 0], x) + sp.diff(tensor[1, 0], y),
        sp.diff(tensor[0, 1], x) + sp.diff(tensor[1, 1], y)
    ])
Beispiel #24
0
import sympy as sp
import numpy as np

x1, x2, x3 = sp.symbols('x1 x2 x3')
f1 = x1 + (x2**2) - (x3**2) - 13
f2 = sp.log(x2 / 4) + sp.exp(0.5 * x3 - 1) - 1
f3 = ((x2 - 3)**2) - (x3**3) + 1
f = sp.Matrix([f1, f2, f3])
X = sp.Matrix([x1, x2, x3])
Df = f.jacobian(X)

jac = sp.lambdify([(x1, x2, x3)], Df, "numpy")
v = np.array([1.5, 3, 2.5])

print(jac(v))
def eye2():
    return sp.Matrix([[sp.Integer(1), sp.Integer(0)],
                      [sp.Integer(0), sp.Integer(1)]])
Beispiel #26
0
    def balance(self):
        """Balances the Chemical Reaction
        :return: None
        :rtype: void
        """
        if not self.is_balanced:
            reference_vector = []
            seen_formulas = []
            for j in [self.reactants, self.products]:
                for compound in j:
                    for i in compound.elements:
                        if i.Symbol not in seen_formulas:
                            seen_formulas.append(i.Symbol)
                            reference_vector.append(i)

            compound_formulas = []
            compounds = []
            for j in [i for i in self.compounds]:
                if j.formula not in compound_formulas:
                    compound_formulas.append(j.formula)
                    compounds.append(j)

            matrix = []
            for compound in compounds:
                col = []
                for m in seen_formulas:
                    try:
                        if compound.formula in self.product_formulas:
                            col.append(-compound.occurences[m])
                        else:
                            col.append(compound.occurences[m])
                    except:
                        col.append(0)
                matrix.append(col)

            matrix = sympy.Matrix(
                np.array(matrix).transpose()).rref()  #Row - echelon form
            solutions = matrix[0][:, -1]
            lcm = sympy.lcm([i.q for i in solutions])
            solutions = lcm * solutions
            solutions = list(solutions)
            solutions = [abs(i) for i in solutions]

            while 0 in solutions:
                solutions.remove(0)

            if (len(compounds) > len(solutions)):
                solutions.append(lcm)

            final_reactants = []
            final_products = []

            for sol in range(len(compounds)):
                if compounds[sol].formula in self.reactant_formulas:
                    final_reactants.append([compounds[sol]] * solutions[sol])

                if compounds[sol].formula in self.product_formulas:
                    final_products.append([compounds[sol]] * solutions[sol])

            final_reactants = sum(final_reactants, [])
            final_products = sum(final_products, [])

            self.reinit(final_reactants, final_products)

        else:
            return True
 def vectomat(x):
     return sp.Matrix([[x[0], x[3], x[4]], [x[3], x[1], x[5]],
                       [x[4], x[5], x[2]]])
Beispiel #28
0
import sympy as sp
from sympy.utilities.lambdify import lambdify
from matplotlib import pyplot as plt
from visuals import plot_vector_field, plot_trajectory

TAU = 2 * PI
PI2 = PI / 2

print('Initializing system...')
# initialize matrix symbols
a, b, u = sp.symbols('a b u', real=True)
w = sp.sqrt(a**2 + b**2 + u**2)
ww = sp.symbols('w', positive=True)

# system matrices
A = sp.Matrix([[0, a, b], [-a, 0, 0], [-b, 0, 0]])
B = sp.Matrix([[0, 0, 0], [0, 0, -1], [0, 1, 0]])
M = A + u * B
print('M')
sp.pprint(M)

# inverse of (sI - M) step by step
print("*" * 180)
print('Calculating inverse matrix...')
s = sp.symbols('s')
Ms = s * sp.eye(3) - M  # sI - M
Ms_det = sp.factor(Ms.det()).subs({w**2: ww**2})
Ms_com = Ms.cofactor_matrix()
Ms_inv = Ms_com.transpose() / Ms_det
print('(sI-M)^-1 =')
Beispiel #29
0
    script_path = os.path.realpath(__file__)
    sys.path.append(os.path.dirname(script_path) + '/../')
    import pyfme

"""
This example derives automatically the calculation of the single-contact wrench
cone reported in <https://scaron.info/research/icra-2015.html>.
"""

X = sympy.Symbol('X', real=True, positive=True)
Y = sympy.Symbol('Y', real=True, positive=True)
mu = sympy.Symbol('mu', real=True, positive=True)

F = sympy.Matrix([
    # fx  fy   fz
    [-1,  0, -mu],
    [+1,  0, -mu],
    [0,  +1, -mu],
    [0,  -1, -mu]])

T = sympy.diag(F, F, F, F)

M = sympy.Matrix([
    # f1x f1y f1z f2x f2y f2z f3x f3y f3z f4x f4y f4z
    [1,    0,  0,  1,  0,  0,  1,  0,  0,  1,  0,  0],
    [0,    1,  0,  0,  1,  0,  0,  1,  0,  0,  1,  0],
    [0,    0,  1,  0,  0,  1,  0,  0,  1,  0,  0,  1],
    [0,    0, +Y,  0,  0, -Y,  0,  0, -Y,  0,  0, +Y],
    [0,    0, -X,  0,  0, -X,  0,  0, +X,  0,  0, +X],
    [-Y,  +X,  0, +Y, +X,  0, +Y, -X,  0, -Y, -X, +0]])

if __name__ == "__main__":
Beispiel #30
0
    def det(self):

        return sym.Matrix(self).det()