Exemple #1
0
    def apply(self, m, b, evaluation):
        'LinearSolve[m_, b_]'

        matrix = matrix_data(m)
        if matrix is None:
            return evaluation.message('LinearSolve', 'matrix', m, 1)
        if not b.has_form('List', None):
            return
        if len(b.leaves) != len(matrix):
            return evaluation.message('LinearSolve', 'lslc')
        system = [mm + [v] for mm, v in zip(matrix, b.leaves)]
        system = to_sympy_matrix(system)
        if system is None:
            return evaluation.message('LinearSolve', 'matrix', b, 2)
        syms = [
            sympy.Dummy('LinearSolve_var%d' % k)
            for k in range(system.cols - 1)
        ]
        sol = sympy.solve_linear_system(system, *syms)
        if sol:
            # substitute 0 for variables that are not in result dictionary
            free_vars = dict(
                (sym, sympy.Integer(0)) for sym in syms if sym not in sol)
            sol.update(free_vars)
            sol = [(sol[sym] if sym in free_vars else sol[sym].subs(free_vars))
                   for sym in syms]
            return from_sympy(sol)
        else:
            return evaluation.message('LinearSolve', 'nosol')
Exemple #2
0
    def apply(self, m, b, evaluation):
        'LinearSolve[m_, b_]'

        matrix = matrix_data(m)
        if matrix is None:
            return
        if not b.has_form('List', None):
            return
        if len(b.leaves) != len(matrix):
            return evaluation.message('LinearSolve', 'lslc')
        system = [mm + [v] for mm, v in zip(matrix, b.leaves)]
        system = to_sympy_matrix(system)
        if system is None:
            return
        syms = [sympy.Dummy('LinearSolve_var%d' % k)
                for k in range(system.cols - 1)]
        sol = sympy.solve_linear_system(system, *syms)
        if sol:
            # substitute 0 for variables that are not in result dictionary
            free_vars = dict((sym, sympy.Integer(
                0)) for sym in syms if sym not in sol)
            sol.update(free_vars)
            sol = [(sol[sym] if sym in free_vars else sol[sym].subs(free_vars))
                   for sym in syms]
            return from_sympy(sol)
        else:
            return evaluation.message('LinearSolve', 'nosol')
Exemple #3
0
    def __call__(self, equations, variables=None):
        
        if variables is None:
            variables = {}
        
        # Get a representation of the ODE system in the form of
        # dX/dt = M*X + B
        varnames, matrix, constants = get_linear_system(equations)

        # Make sure that the matrix M is constant, i.e. it only contains
        # external variables or constant variables
        t = Symbol('t', real=True, positive=True)
        symbols = set.union(*(el.atoms() for el in matrix))
        non_constant = _non_constant_symbols(symbols, variables, t)
        if len(non_constant):
            raise ValueError(('The coefficient matrix for the equations '
                              'contains the symbols %s, which are not '
                              'constant.') % str(non_constant))

        # Check for time dependence
        dt_var = variables.get('dt', None)
        if dt_var is not None:
            # This will raise an error if we meet the symbol "t" anywhere
            # except as an argument of a locally constant function
            for entry in itertools.chain(matrix, constants):
                _check_for_locally_constant(entry, variables, dt_var.get_value(), t)
        symbols = [Symbol(variable, real=True) for variable in varnames]
        solution = sp.solve_linear_system(matrix.row_join(constants), *symbols)
        b = sp.ImmutableMatrix([solution[symbol] for symbol in symbols]).transpose()
        
        # Solve the system
        dt = Symbol('dt', real=True, positive=True)
        A = (matrix * dt).exp()                
        C = sp.ImmutableMatrix([A.dot(b)]) - b
        _S = sp.MatrixSymbol('_S', len(varnames), 1)
        updates = A * _S + C.transpose()
        try:
            # In sympy 0.7.3, we have to explicitly convert it to a single matrix
            # In sympy 0.7.2, it is already a matrix (which doesn't have an
            # is_explicit method)
            updates = updates.as_explicit()
        except AttributeError:
            pass
        
        # The solution contains _S[0, 0], _S[1, 0] etc. for the state variables,
        # replace them with the state variable names 
        abstract_code = []
        for idx, (variable, update) in enumerate(zip(varnames, updates)):
            rhs = update
            for row_idx, varname in enumerate(varnames):
                rhs = rhs.subs(_S[row_idx, 0], varname)

            # Do not overwrite the real state variables yet, the update step
            # of other state variables might still need the original values
            abstract_code.append('_' + variable + ' = ' + sympy_to_str(rhs))
        
        # Update the state variables
        for variable in varnames:
            abstract_code.append('{variable} = _{variable}'.format(variable=variable))
        return '\n'.join(abstract_code)
Exemple #4
0
def find_balancing_weights(coalitions: list, var_name: str = ''):
    '''
    Parameter coalitions is a list of lists, each inner list representing a coalition of players.
    Number of players is inferred depending on who participates in the coalitions
    '''
    coefficients = []
    players = {}
    matrices = []
    for i, coalition in enumerate(coalitions):
        coalition_name = '{0}{{{1}}}'.format(
            var_name, ','.join([str(x) for x in coalition]))
        coefficients.append(Symbol(coalition_name))
        for player in coalition:
            if player not in players:
                players[player] = []
            players[player].append(i)

    for player, participating in players.items():
        tmp = [0] * len(coalitions)
        for coalition in participating:
            tmp[coalition] = 1

        tmp.append(1)
        matrices.append(tmp)

    system = Matrix(matrices)
    return solve_linear_system(system, *coefficients)
Exemple #5
0
def matrix_z(M_self, X, x_zero, matriz_um):
    f_xis = M_self
    n = 0
    for x in range(0, X.shape[0]):
        f_xis = f_xis.subs(X[n], x_zero[n])
        n = n + 1
    f_xis = -1 * f_xis
    f_final = matriz_um.col_insert(X.shape[0], f_xis)
    return solve_linear_system(f_final, *X)
def linear_solve(sparse_mat_rep, sub_cvector, length, fvars, iofvars, fvargen,
                 newfvars, vardict):
    augmatrix = sympy.zeros(len(sub_cvector), length + 1)
    for index, value in sparse_mat_rep.items():
        augmatrix[index[0], index[1]] = value
    for i, c in enumerate(sub_cvector):
        augmatrix[i, -1] = c
    if augmatrix.cols == 2 and augmatrix.rows == 1:
        return {fvars[0]: augmatrix[0, 1] / augmatrix[0, 0]}
    return sympy.solve_linear_system(augmatrix, *fvars)
Exemple #7
0
def sytem_of_equations():
    strVariables = str(request.args.get('variables'))
    strVariables = strVariables.replace("[", "")
    strVariables = strVariables.replace("\"", "")
    strVariables = strVariables.replace("\'", "")

    variables = strVariables.split(",")

    strMatrix = str(request.args.get('matrix'))

    strMatrix = strMatrix.replace("[", "")
    strMatrix = strMatrix.replace("\"", "")
    strMatrix = strMatrix.replace("\'", "")

    matrix = strMatrix.split("]")
    matrix.pop(len(matrix) - 1)

    equations = [[]]

    i = 0
    for row in matrix:
        for item in row.split(","):
            equations[i].append(float(item))
        i += 1
        equations.append([])
    equations.pop(len(equations) - 1)

    print(equations)

    if len(variables) == 2:
        x, y = sp.symbols(variables)
        system = Matrix((equations[0], equations[1]))
        print(str(solve_linear_system(system, x, y)))

        return (str(solve_linear_system(system, x, y)))
    if len(variables) == 3:
        x, y, z = sp.symbols(variables)
        system = Matrix((equations[0], equations[1], equations[2]))
        print(str(solve_linear_system(system, x, y, z)))

        return (str(solve_linear_system(system, x, y, z)))

    return "HUIH"
    def calcAlignTrans(self, shape1, shape2):
        """
        start = time.time()
        coeffs = np.array( [
            [ self.Xgen( shape2 ), - self.Ygen( shape2 ), self.Wgen(), 0],
            [ self.Ygen( shape2 ), self.Xgen( shape2 ), 0, self.Wgen()],
            [ self.Zgen( shape2 ), 0, self.Xgen( shape2 ), self.Ygen( shape2 )],
            [ 0, self.Zgen( shape2 ), - self.Ygen( shape2 ), self.Xgen( shape2 )]
            ])
        eqs = np.array([ self.Xgen(shape1) ,  self.Ygen(shape1), self.C1gen(shape1, shape2), self.C2gen(shape1, shape2) ] )
        sol = np.linalg.solve( coeffs, eqs )
            # d = ax = s cos 0
            # e = ay = s sin 0
            # f = tx
            # g = ty

        rot = [[ sol[0], - sol[1]],
               [ sol[1], sol[0]] ]
        t = [[ sol[2]],[sol[3]]]
        
        """
        toSolve = Matrix([[
            self.Xgen(shape2), -self.Ygen(shape2),
            self.Wgen(), 0,
            self.Xgen(shape1)
        ],
                          [
                              self.Ygen(shape2),
                              self.Xgen(shape2), 0,
                              self.Wgen(),
                              self.Ygen(shape1)
                          ],
                          [
                              self.Zgen(shape2), 0,
                              self.Xgen(shape2),
                              self.Ygen(shape2),
                              self.C1gen(shape1, shape2)
                          ],
                          [
                              0,
                              self.Zgen(shape2), -self.Ygen(shape2),
                              self.Xgen(shape2),
                              self.C2gen(shape1, shape2)
                          ]])

        sol = solve_linear_system(toSolve, d, e, f, g)
        # d = ax = s cos 0
        # e = ay = s sin 0
        # f = tx
        # g = ty

        rot = [[sol[d], -sol[e]], [sol[e], sol[d]]]
        t = [[sol[f]], [sol[g]]]

        return {'rot': rot, 't': t}
Exemple #9
0
    def linear_solve(A, b):
        '''solve linear equation Ax=b

        return (tuple of number): a tuple of column element of x
        A (list of list of number): A matrix
        b (list of number): b vector
        '''
        vnames = sp.symbols(["a" + str(i) for i in range(len(b))])
        result = sp.solve_linear_system(
            sp.Matrix(A).row_join(sp.Matrix(b)), *vnames)
        return tuple([result[item] for item in vnames])
Exemple #10
0
def kusochno_linear():
    n = len(x0)
    systems = []
    x, y = sympy.symbols("x, y")

    for i in range(1, n):
        system = sympy.Matrix(((x0[i - 1], 1, y0[i - 1]), (x0[i], 1, y0[i])))
        solved = sympy.solve_linear_system(system, x, y)
        systems.append(solved[x] * x + solved[y])

    return systems
Exemple #11
0
def build_formula(degree):
    xs = [symbols('x' + str(i)) for i in range(degree+1)]
    x = symbols('x')

    m = Matrix([[letter**power for letter in xs + [x]] for power in range(degree + 1)])

    factors = [symbols('f' + str(i)) for i in range(degree+1)]
    solutions = solve_linear_system(m, *factors)

    ys = [symbols('y' + str(i)) for i in range(degree+1)]
    final = sum(solutions[factors[i]] * ys[i] for i in range(degree + 1))
    return final
Exemple #12
0
def Main():
    #Read("spec.in")
    #Read("spec_warp_simpler.in")
    #Read("spec_warpPerspective.in")
    Read("spec_rotate.in")

    if False:
        [(c_name, c_code), (h_name, c_header)] = codegen([("xdst", eqList[0]),
                                                          ("ydst", eqList[1])],
                                                         "C",
                                                         "test",
                                                         header=False,
                                                         empty=False)

        print("c_code = %s" % c_code)

    print("eqList = %s" % str(eqList))
    resEqSysMat = eqs2matrix(eqs=eqList,
                             unknownSymbols=(xdst, ydst),
                             augment=True)
    print("resEqSysMat = %s" % str(resEqSysMat))

    from sympy import Matrix, solve_linear_system
    res = solve_linear_system(resEqSysMat, xdst, ydst)
    print("The result is (xdst, ydst) = %s" % str(res))
    print("res[xdst] = %s" % str(res[xdst]))
    print("res[ydst] = %s" % str(res[ydst]))

    #sympy.simplify.cse_main.cse(res[xdst], res[ydst])
    expListWithBoundedVars = cse([res[xdst], res[ydst]])
    print("After performing CSE, we have: %s" % str(expListWithBoundedVars))

    print("expListWithBoundedVars[0] (the bounded vars) = %s" %
          str(expListWithBoundedVars[0]))
    print("expListWithBoundedVars[1][0] = %s" %
          str(expListWithBoundedVars[1][0]))
    eFinal = []
    for e in expListWithBoundedVars[0]:
        eFinal.append((str(e[0]), e[1]))

    #expListWithBoundedVars[0] + \
    expListWithBoundedVars = eFinal + \
                            [("xdst", expListWithBoundedVars[1][0])] + \
                            [("ydst", expListWithBoundedVars[1][1])]
    print("expListWithBoundedVars = %s" % str(expListWithBoundedVars))
    [(c_name, c_code), (h_name, c_header)] = codegen(expListWithBoundedVars,
                                                     "C",
                                                     "final_test",
                                                     header=False,
                                                     empty=False)

    print("c_code = %s" % c_code)
def quadratic(x1, y1, x2, y2, dist):
    ''''y = ax + b so will solve it using the sympy module
    example >>> system = Matrix(( (1, 4, 2), (-2, 1, 14)))
    >>> solve_linear_system(system, x, y)
    {x: -6, y: 2}
    now solve distance: d**2 = (x3-x1)**2 + (y3-y1)**2 =>
    x3**2 - 2*x1x3 + (x1**2 - d**2 / (a**2 +1)) :a from y = ax + b'''
    if x1 != x2:
        system = Matrix(((x1, 1, y1), (x2, 1, y2)))
        d = solve_linear_system(system, x, y)
        z = float(d[x])
        w = float(d[y])
        a = 1
        b = -2 * x1
        c = x1**2 - (dist**2 / (z**2 + 1))
        diak = b**2 - (4 * a * c)
        if x1 < x2:
            if (x1 <= ((-b + math.sqrt(diak)) / (2 * a)) <= x2):
                x3 = ((-b + math.sqrt(diak)) / (2 * a))
            else:
                x3 = ((-b - math.sqrt(diak)) / (2 * a))
            y3 = z * x3 + w
            if (distance(x3, y3, x2, y2) <= dist):
                return (x2, y2)
            else:
                return (x3, y3)
        elif x2 < x1:
            if (x2 <= ((-b + math.sqrt(diak)) / (2 * a)) <= x1):
                x3 = ((-b + math.sqrt(diak)) / (2 * a))
            else:
                x3 = ((-b - math.sqrt(diak)) / (2 * a))
            y3 = z * x3 + w
            if (distance(x3, y3, x2, y2) <= dist):
                return (x2, y2)
            else:
                return (x3, y3)
    elif x1 == x2:
        if y1 < y2:
            y3 = y1 + dist
            if (distance(x2, y3, x2, y2) <= dist):
                return (x2, y2)
            else:
                return (x2, y3)
        else:
            y3 = y1 - dist
            if (distance(x2, y3, x2, y2) <= dist):
                return (x2, y2)
            else:
                return (x2, y3)
Exemple #14
0
    def algebraSolver(self):
        #x = 0
        #y = 0
        #eq1 = sp.Function('eq1')
        #eq2 = sp.Function('eq2')

        #eq1 = Eq(2*x - y,-4)
        #eq2 = Eq(3*x - y,-2)
        
        x,y = sp.symbols('x y')
        row1 = [2, -2, -4]
        row2 = [6, -8, -2]

        system = Matrix((row1,row2))
        print(solve_linear_system(system,x,y))
Exemple #15
0
def associated1ps(monomials,boundary=None, dim=4): #generates the normalized 1-PS from a list of monomials.
        monomials_copy=list(monomials)
        if(len(monomials_copy)>0):
            m0=monomials_copy[0]
            monomial_list=[m0-m for m in monomials_copy]
        else:
            monomial_list=[]
        #observe that the previous line also adds the zero vector, but it does not change the code.
        
        #we add the monomial in the centre, which is equivalent to saying that lambda is in SL(n,C).
        monomial_list.append(Monomial([1 for x in range(dim)]))

        #We add the boundary components:
        if boundary!=None:
            for x in boundary:
                monomial_list.append(x)
        n_mon=len(monomial_list);
        #building the general matrix
        #first we put the first component with negative value and reverse the monomials
        #to assure that this one becomes the solution vector b, i.e. Ax=-y[0]. This is equivalent to
        #making sure that solution_1=1
        mon_reversed=[]
        for x in monomial_list:
            y=list(x)
            y[0]=-y[0]
            y.reverse()
            mon_reversed=mon_reversed+y
        extended=Matrix(n_mon, dim, mon_reversed)
        variables=list(symbols('x0:%d'%n_mon))

        #finding solutions
        system_solution=solve_linear_system(extended, *variables,  rational=True)
        if system_solution==None:
            return None
        #finding least common denominator
        val=system_solution.values()
        for x in val:
            if not isinstance(x,Rational):
                return None
        denominators=[x.q for x in val if x.p!=0]
        lcm=Jlcm(denominators)
        if not lcm:
            return None
        #clearing solutions
        solution=[int(x*lcm) for x in val]
        solution.append(lcm)
        solution.reverse()
        return solution
Exemple #16
0
def solve(f1, f2, x, y):
    soln = Matrix((fila1, fila2))  # declarar matriz sympy

    possiblesoln = possibleValues(solve_linear_system(
        soln, x, y))  # resolver sistema de ecuaciones para encontrar la
    # interseccion entre restricciones, verificar que el punto cumple y se mete en la variable possiblesoln como una
    # posible solucion al problema

    produccionMax = 0
    # probar que la solucion sea la indicada para maximizar la funcion objetivo
    if possiblesoln[0] > produccionMax and possiblesoln[
            1] in arrayPuntosCandidatos:
        produccionMax = possiblesoln[0]
        puntoMax = possiblesoln[1]
    # se devuelve el punto que maximiza
    return puntoMax
Exemple #17
0
def lin_solve_eqns(eqns, vars):
    """
    takes a list of equation objects
    creates a system matrix of and calls sp.solve
    """
    n = len(eqns)

    vars = list(vars) # if its a vector
    m = len(vars)

    rows = [get_coeff_row(eq, vars) for eq in eqns]

    sysmatrix = sp.Matrix(rows)

    sol = sp.solve_linear_system(sysmatrix, *vars)

    return sol
Exemple #18
0
def lin_solve_eqns(eqns, vars):
    """
    takes a list of equation objects
    creates a system matrix of and calls sp.solve
    """
    n = len(eqns)

    vars = list(vars) # if its a vector
    m = len(vars)

    rows = [get_coeff_row(eq, vars) for eq in eqns]

    sysmatrix = sp.Matrix(rows)

    sol = sp.solve_linear_system(sysmatrix, *vars)

    return sol
Exemple #19
0
def kusochno_kvadrat():
    n = len(x0)
    if n % 2 != 0:
        m = int(n / 2) + 1
    else:
        m = int(n / 2)
    x, y, z = sympy.symbols("x, y, z")

    systems = []
    for k in range(1, m):
        full_matrix = []
        for i in range(0, n - 2):
            full_matrix.append(
                [x0[2 * k - i]**2, x0[2 * k - i], 1, y0[2 * k - i]])
        full_matrix = sympy.Matrix(full_matrix)
        solution = sympy.solve_linear_system(full_matrix, x, y, z)
        systems.append(solution[x] * x**2 + solution[y] * x + solution[z])

    return systems
Exemple #20
0
def Main():
    #Read("spec.in")
    #Read("spec_warp_simpler.in")
    #Read("spec_warpPerspective.in")
    Read("spec_rotate.in")

    if False:
        [(c_name, c_code), (h_name, c_header)] = codegen(
            [("xdst", eqList[0]), ("ydst", eqList[1])], "C", "test", header=False, empty=False)

        print("c_code = %s" % c_code)

    print("eqList = %s" % str(eqList))
    resEqSysMat = eqs2matrix(eqs=eqList, unknownSymbols=(xdst, ydst), augment=True)
    print("resEqSysMat = %s" % str(resEqSysMat))

    from sympy import Matrix, solve_linear_system
    res = solve_linear_system(resEqSysMat, xdst, ydst)
    print("The result is (xdst, ydst) = %s" % str(res))
    print("res[xdst] = %s" % str(res[xdst]))
    print("res[ydst] = %s" % str(res[ydst]))

    #sympy.simplify.cse_main.cse(res[xdst], res[ydst])
    expListWithBoundedVars = cse([res[xdst], res[ydst]])
    print("After performing CSE, we have: %s" % str(expListWithBoundedVars))

    print("expListWithBoundedVars[0] (the bounded vars) = %s" % str(expListWithBoundedVars[0]))
    print("expListWithBoundedVars[1][0] = %s" % str(expListWithBoundedVars[1][0]))
    eFinal = []
    for e in expListWithBoundedVars[0]:
        eFinal.append( (str(e[0]), e[1]) )

    #expListWithBoundedVars[0] + \
    expListWithBoundedVars = eFinal + \
                            [("xdst", expListWithBoundedVars[1][0])] + \
                            [("ydst", expListWithBoundedVars[1][1])]
    print("expListWithBoundedVars = %s" % str(expListWithBoundedVars))
    [(c_name, c_code), (h_name, c_header)] = codegen(
        expListWithBoundedVars, "C", "final_test", header=False, empty=False)

    print("c_code = %s" % c_code)
    def calcAlignTrans( self, shape1, shape2 ):
        """
        start = time.time()
        coeffs = np.array( [
            [ self.Xgen( shape2 ), - self.Ygen( shape2 ), self.Wgen(), 0],
            [ self.Ygen( shape2 ), self.Xgen( shape2 ), 0, self.Wgen()],
            [ self.Zgen( shape2 ), 0, self.Xgen( shape2 ), self.Ygen( shape2 )],
            [ 0, self.Zgen( shape2 ), - self.Ygen( shape2 ), self.Xgen( shape2 )]
            ])
        eqs = np.array([ self.Xgen(shape1) ,  self.Ygen(shape1), self.C1gen(shape1, shape2), self.C2gen(shape1, shape2) ] )
        sol = np.linalg.solve( coeffs, eqs )
            # d = ax = s cos 0
            # e = ay = s sin 0
            # f = tx
            # g = ty

        rot = [[ sol[0], - sol[1]],
               [ sol[1], sol[0]] ]
        t = [[ sol[2]],[sol[3]]]
        
        """
        toSolve = Matrix( [
            [ self.Xgen( shape2 ), - self.Ygen( shape2 ), self.Wgen(), 0, self.Xgen(shape1) ],
            [ self.Ygen( shape2 ), self.Xgen( shape2 ), 0, self.Wgen(), self.Ygen(shape1) ],
            [ self.Zgen( shape2 ), 0, self.Xgen( shape2 ), self.Ygen( shape2 ), self.C1gen(shape1, shape2) ],
            [ 0, self.Zgen( shape2 ), - self.Ygen( shape2 ), self.Xgen( shape2 ), self.C2gen(shape1, shape2)]
            ])
                
        sol = solve_linear_system( toSolve, d, e, f, g)
            # d = ax = s cos 0
            # e = ay = s sin 0
            # f = tx
            # g = ty

        rot = [[ sol[d], - sol[e]],
               [ sol[e], sol[d]] ]
        t = [[ sol[f]],[sol[g]]]
        

        return { 'rot': rot, 't':t}
def compute_proba(matrix):
	eqs = []
	syms = []
	lastline = []
	for i in range(len(matrix)-1): #we want to avoid overdetermination
		line = []
		for j in range(len(matrix)):
			#print "value for i: %i" % i
			if (i==j):
				line.append(matrix[j][i]-1.0)
			else:
				line.append(matrix[j][i])
		# We are summing in the form a1 p1 + ... + an pn = 0
		line.append(0)
		syms.append(Symbol("p%i" % i))
		eqs.append(line)
		lastline.append(1)
	syms.append(Symbol("p%i" % (len(matrix)-1)))
	lastline.append(1)
	lastline.append(1)
	eqs.append(lastline)
	#print syms
	#print eqs	
	return solve_linear_system(Matrix(eqs),*syms)
Exemple #23
0
def ritz_method(number_of_points):
    data = get_data(False)
    k, q, f,a,b, alpha, beta, gamma, delta = (data[i] for i in ('k', 'q', 'f','a','b','alpha', 'beta', 'gamma', 'delta'))
    phi = get_basis(alpha, beta, gamma, delta, a, b, number_of_points)

    # phi = [x**i for i in range(number_of_points)]
    beta = -beta* 1.0 / alpha * k.subs(x, a)
    delta = delta*1.0/ gamma * k.subs(x, b)
    g = lambda u, v: (integrate(k * u.diff(x) * v.diff(x) + q * u * v, (x, a,b)) 
        + beta * u.subs(x, a) * v.subs(x, a) + delta * u.subs(x, b) * v.subs(x, b) )
    l = lambda u: integrate(f * u, (x, a, b))
    c = [Symbol('c' + repr(i)) for i in range(number_of_points)]
    system = []
    for j in range(number_of_points):
        system.append([g(phi[i], phi[j]) for i in range(number_of_points)])
        system[-1].append(l(phi[j]))
    solution = solve_linear_system(Matrix(system), *c)
    print(solution.items());
    # for j in range(number_of_points):
    #     system.append(sum([c[i] * g(phi[i], phi[j]) for i in range(number_of_points)]) - l(phi[j]))
    # solution = solve(system)
    u = sum([c[i] * phi[i] for i in range(number_of_points)])
    u = u.subs(solution.items())
    return u
Exemple #24
0
def makeQSSA(system, enzyme='E', variable='P'):
    r'''Calculate quasi steady-state equation from set of ODEs
    
    This function calculates the quasi steady-state equation for the
    variable of interest

    Parameters
    -----------
    system : dict
        dict containing system of equation describing the reactions.
    enzyme : string
        All enzyme forms have to start with the same letters, e.g. 'E' or
        'E_'. This allows the algorithm to select the enzyme forms, otherwise
        a reduction is not possible.
    variable: string
        Which rate equation has to be used to replace the enzyme forms with
        the QSSA.

    Returns
    ---------
    QSSA_var : sympy equation
        Symbolic sympy equation of variable which obeys the QSSA.

    Notes
    ------
    The idea for the calculations is based on [1]_, where the system is
    first transformed in its canonical form.

    References
    -----------
    .. [1] Ishikawa, H., Maeda, T., Hikita, H., Miyatake, K., The
        computerized derivation of rate equations for enzyme reactions on
        the basis of the pseudo-steady-state assumption and the
        rapid-equilibrium assumption (1988), Biochem J., 251, 175-181

    Examples
    ---------
    >>> from biointense.utilities import makeQSSA
    >>> system = {'dE': '-k1*E*S + k2*ES + kcat*ES',
                  'dES': 'k1*E*S - k2*ES - kcat*ES',
                  'dS': '-k1*E*S + k2*ES',
                  'dP': 'kcat*ES'}
    >>> makeQSSA(system, enzyme='E', variable='P')
    'En0*S*k1*kcat/(S*k1 + k2 + kcat)'
    '''
    # Make state var
    state_var = [i[1:] for i in system.keys() if i[0] == 'd']

    # Run _getCoefficients to get filtered rate equations
    coeff_matrix, enzyme_forms, enzyme_equations = _getCoefficients(
        system, state_var, enzyme)

    # Add row with ones to set the sum of all enzymes equal to En0
    coeff_matrix = coeff_matrix.col_join(sympy.ones(1, c=len(enzyme_forms)))

    # Make row matrix with zeros (QSSA!), but replace last element with
    # En0 for fixing total som of enzymes
    QSSA_matrix = sympy.zeros(coeff_matrix.shape[0], c=1)
    QSSA_matrix[-1] = sympy.sympify('En0')

    # Add column with outputs to coeff_matrix
    linear_system = coeff_matrix.row_join(QSSA_matrix)

    # Find QSSE by using linear solver (throw away one line (system is
    # closed!)) list should be passed as *args, therefore * before list
    QSSE_enz = sympy.solve_linear_system(linear_system[1:, :],
                                         *list(enzyme_forms))

    # Replace enzyme forms by its QSSE in rate equation of variable of interest
    QSSE_var = sympy.sympify(system['d' + variable], _clash)
    for enz in enzyme_forms:
        QSSE_var = QSSE_var.replace(enz, QSSE_enz[enz])

    # To simplify output expand all terms (=remove brackets) and afterwards
    # simplify the equation
    QSSE_var = sympy.simplify(sympy.expand(QSSE_var))

    return QSSE_var
 def template_16(self, a, b, c):
     m = sympy.symbols('x')
     n = sympy.symbols('y')
     system = sympy.Matrix(((a, a, b), (1, -1, c)))
     return sympy.solve_linear_system(system, m, n)
 def template_15(self, a, b, c, d):
     m = sympy.symbols('x')
     n = sympy.symbols('y')
     system = sympy.Matrix(((a, -b, c), (1, 1, d)))
     return sympy.solve_linear_system(system, m, n)
Exemple #27
0
def balance(eq):
    list_of_elements = []
    compounds = eq.split("=")  # splits the equation into its left and right
    lhs = compounds[0]  # left hand side
    rhs = compounds[1]  # right hand side
    l_compounds = lhs.split("+")  # splits the left hand side into compounds
    r_compounds = rhs.split(
        "+")  # splits the right hand side into its compounds
    l_list = []
    r_list = []
    for k in range(len(l_compounds)):
        l_list.append(elements_dictionary(l_compounds[k]))
        molecule = l_compounds[k]
        elements = re.findall(r'[A-Z][a-z]?[\d]?', molecule)
        for e in elements:
            if re.search(r'[A-Z][a-z]?$', e):
                list_of_elements.append(e)  # If e is an element
            else:
                e = re.sub(
                    r'(\w+)\d+', r'\1', e
                )  # Removes the number, then adds the element alone to the list
                list_of_elements.append(e)
    list_of_elements = list(set(list_of_elements))  # Removes duplicates
    for k in range(len(r_compounds)):
        r_list.append(elements_dictionary(r_compounds[k]))

    a = int(len(list_of_elements))  # Number of elements
    b = int(len(l_compounds) + len(r_compounds))  # Number of terms
    M = np.zeros((a, b + 1))  # Dimensions of the augmented matrix
    for i in range(len(list_of_elements)):
        e = list_of_elements[i]
        for j in range(len(l_list) + len(r_list)):
            if (j < len(l_list)):
                if e in l_list[j].keys():
                    atoms = (l_list[j])[e]
                    M[i][
                        j] = atoms  # Sets the corresponding entry of the matrix
            else:
                if e in r_list[j - len(l_list)].keys():
                    atoms = -(r_list[j - len(l_list)])[e]
                    M[i][
                        j] = atoms  # Sets the corresponding entry of the matrix
    M = M.astype(int)  # Converts the matrix to be of integers
    a, b, c, d, e, f, g, h, i, j, k, l, m, n = sp.symbols(
        "a,b,c,d,e,f,g,h,i,j,k,l,m,n")
    variables = [a, b, c, d, e, f, g, h, i, j, k, m, n]
    solution = sp.solve_linear_system(sp.Matrix(M), a, b, c, d, e, f, g, h, i,
                                      j, k, m, n)
    variables_used = []
    for v in variables:
        if v in solution.keys():
            variables_used.append(
                v)  # If the variable has been used, append it to the list
    last_variable = variables[len(
        variables_used)]  # Identifies the last variable used
    coeffs = []
    for v in variables_used:
        coeffs.append(solution[v] / last_variable)
    coeffs.append(1)  # The last coefficient is set to 1 by default
    fractions = []
    for i in range(len(coeffs) - 1):
        f = coeffs[i].subs(last_variable,
                           1)  # To remove the variables from the coefficients
        fractions.append(Fraction(str(f)).limit_denominator())
    fractions.append(Fraction(1))  # Appends the last 1

    denominators = []
    for fraction in fractions:
        denominators.append(fraction.denominator)
    denominators = list(set(denominators))  # Removes duplicates
    product = sp.lcm(denominators)  # Finds the LCM
    new_coeffs = []
    for fraction in fractions:
        new_coeffs.append(
            int(fraction.numerator * product / fraction.denominator)
        )  # Multiplies by the LCM to remove fractions
    positive_coeffs = []
    for c in new_coeffs:
        if c < 0:
            c = c * -1  # Removes negatives
            positive_coeffs.append(str(c))
        else:
            positive_coeffs.append(str(c))
    if positive_coeffs[0] == "1":
        balanced = l_compounds[0]  # Initiates the result string
    else:
        balanced = positive_coeffs[0] + l_compounds[0]
    for i in range(len(l_compounds)):
        if positive_coeffs[i] == "1":
            string = ""  # If the coefficient is 1, then add nothing
        else:
            string = positive_coeffs[i]
        if i != 0:
            balanced += "+" + string + l_compounds[i]
    balanced += "="  # Now for the right side
    for i in range(len(r_compounds)):
        if positive_coeffs[i + len(l_compounds)] == "1":
            string = ""
        else:
            string = positive_coeffs[i + len(l_compounds)]
        if i == 0:
            balanced += string + r_compounds[i]
        else:
            balanced += "+" + string + r_compounds[i]

    return balanced
Exemple #28
0
    def __call__(self, equations, variables=None, method_options=None):
        method_options = extract_method_options(method_options,
                                                {'simplify': True})

        if equations.is_stochastic:
            raise UnsupportedEquationsException('Cannot solve stochastic '
                                                'equations with this state '
                                                'updater.')
        if variables is None:
            variables = {}

        # Get a representation of the ODE system in the form of
        # dX/dt = M*X + B
        varnames, matrix, constants = get_linear_system(equations, variables)

        # No differential equations, nothing to do (this occurs sometimes in the
        # test suite where the whole model is nothing more than something like
        # 'v : 1')
        if matrix.shape == (0, 0):
            return ''

        # Make sure that the matrix M is constant, i.e. it only contains
        # external variables or constant variables
        t = Symbol('t', real=True, positive=True)

        # Check for time dependence
        dt_value = variables['dt'].get_value()[0] if 'dt' in variables else None

        # This will raise an error if we meet the symbol "t" anywhere
        # except as an argument of a locally constant function
        for entry in itertools.chain(matrix, constants):
            if not is_constant_over_dt(entry, variables, dt_value):
                raise UnsupportedEquationsException(
                    ('Expression "{}" is not guaranteed to be constant over a '
                     'time step').format(sympy_to_str(entry)))

        symbols = [Symbol(variable, real=True) for variable in varnames]
        solution = sp.solve_linear_system(matrix.row_join(constants), *symbols)
        if solution is None or set(symbols) != set(solution.keys()):
            raise UnsupportedEquationsException('Cannot solve the given '
                                                'equations with this '
                                                'stateupdater.')
        b = sp.ImmutableMatrix([solution[symbol] for symbol in symbols])

        # Solve the system
        dt = Symbol('dt', real=True, positive=True)
        try:
            A = (matrix * dt).exp()
        except NotImplementedError:
            raise UnsupportedEquationsException('Cannot solve the given '
                                                'equations with this '
                                                'stateupdater.')
        if method_options['simplify']:
            A = A.applyfunc(lambda x:
                            sp.factor_terms(sp.cancel(sp.signsimp(x))))
        C = sp.ImmutableMatrix(A * b) - b
        _S = sp.MatrixSymbol('_S', len(varnames), 1)
        updates = A * _S + C
        updates = updates.as_explicit()

        # The solution contains _S[0, 0], _S[1, 0] etc. for the state variables,
        # replace them with the state variable names 
        abstract_code = []
        for idx, (variable, update) in enumerate(zip(varnames, updates)):
            rhs = update
            if rhs.has(I, re, im):
                raise UnsupportedEquationsException('The solution to the linear system '
                                                    'contains complex values '
                                                    'which is currently not implemented.')
            for row_idx, varname in enumerate(varnames):
                rhs = rhs.subs(_S[row_idx, 0], varname)

            # Do not overwrite the real state variables yet, the update step
            # of other state variables might still need the original values
            abstract_code.append('_' + variable + ' = ' + sympy_to_str(rhs))

        # Update the state variables
        for variable in varnames:
            abstract_code.append('{variable} = _{variable}'.format(variable=variable))
        return '\n'.join(abstract_code)
Exemple #29
0
def timeit_linsolve_trivial():
    solve_linear_system(M, *S)
Exemple #30
0
print("            System of 2 Linear Equations            ")
print("====================================================")
print(" ")

eq1 = sp.Function('eq1')
eq2 = sp.Function('eq2')

x, y = sp.symbols('x y')

print("Equation 1")
a = float(input("Coefficent of x:"))
b = float(input("Coefficent of y:"))
c = float(input("Coefficent of constant:"))
print("Equation 2")
d = float(input("Coefficent of x:"))
e = float(input("Coefficent of y:"))
f = float(input("Coefficent of constant:"))

eq1 = sp.Eq(a * x + b * y, c)
eq2 = sp.Eq(d * x + e * y, f)
print(eq1)
print(eq2)

row1 = [a, b, c]
row2 = [d, e, f]
print(row1)
print(row2)

system = sp.Matrix((row1, row2))
print(sp.solve_linear_system(system, x, y))

# 求解Bellman期望方程
v_hungry, v_full = symbols('v_hungry v_full')
q_hungry_eat, q_hungry_none, q_full_eat, q_full_none = symbols('q_hungry_eat q_hungry_none q_full_eat q_full_none')
alpha, beta, x, y, gamma = symbols('alpha beta x y gamma')
system = sympy.Matrix((
    (1, 0, x-1, -x, 0, 0, 0),
    (0, 1, 0, 0, -y, y-1, 0),
    (-gamma, 0, 1, 0, 0, 0, -2),
    ((alpha-1)*gamma, -alpha*gamma, 0, 1, 0, 0, 4*alpha-3),
    (-beta*gamma, (beta-1)*gamma, 0, 0, 1, 0, -4*beta+2),
    (0, -gamma, 0, 0, 0, 1, 1)
))

re = sympy.solve_linear_system(system,v_hungry,v_full,q_hungry_none,q_hungry_eat,q_full_none,q_full_eat)
for i in re:
    print(re[i])


print('---  BellMan optimization ---')


# 求解Bellman最优方程
sympy.init_printing()
alpha, beta, gamma = symbols('alpha beta gamma')
v_hungry, v_full = symbols('v_hungry v_full')
q_hungry_eat, q_hungry_none,q_full_eat, q_full_none = symbols('q_hungry_eat, q_hungry_none,q_full_eat, q_full_none')
xy_tuples = ((0,0), (1,0), (0,1), (1,1))

for x,y in xy_tuples:  # 分类讨论
Exemple #32
0
 def solution(self):
     """Solves the system if it has a single solution. Returns a dictionary mapping symbol to solution value."""
     return sp.solve_linear_system(self._matrix, *self.unknowns)
Exemple #33
0
import gym
import scipy
from sympy import symbols
v_hungry, v_full = symbols('v_hungry v_full')
q_hungry_eat, q_hungry_none, q_full_eat, q_full_none = \
        symbols('q_hungry_eat q_hungry_none q_full_eat q_full_none')
alpha, beta, gamma = symbols('alpha beta gamma')
x, y = symbols('x y')

system = sympy.Matrix(
    ((1, 0, x - 1, -x, 0, 0, 0), (0, 1, 0, 0, -y, y - 1, 0), (-gamma, 0, 1, 0,
                                                              0, 0, -2),
     ((alpha - 1) * gamma, -alpha * gamma, 0, 1, 0, 0,
      4 * alpha - 3), (-beta * gamma, (beta - 1) * gamma, 0, 0, 1, 0,
                       -4 * beta + 2), (0, -gamma, 0, 0, 0, 1, 1)))
sympy.solve_linear_system(system, v_hungry, v_full, q_hungry_none,
                          q_hungry_eat, q_full_none, q_full_eat)

xy_tuples = ((0, 0), (1, 0), (0, 1), (1, 1))
for x, y in xy_tuples:
    system = sympy.Matrix(
        ((1, 0, x - 1, -x, 0, 0, 0), (0, 1, 0, 0, -y, y - 1, 0), (-gamma, 0, 1,
                                                                  0, 0, 0, -2),
         ((alpha - 1) * gamma, -alpha * gamma, 0, 1, 0, 0,
          4 * alpha - 3), (-beta * gamma, (beta - 1) * gamma, 0, 0, 1, 0,
                           -4 * beta + 2), (0, -gamma, 0, 0, 0, 1, 1)))
    result = sympy.solve_linear_system(system,
                                       v_hungry,
                                       v_full,
                                       q_hungry_none,
                                       q_hungry_eat,
                                       q_full_none,
Exemple #34
0
    def __call__(self, equations, variables=None, method_options=None):
        method_options = extract_method_options(method_options,
                                                {'simplify': True})

        if equations.is_stochastic:
            raise UnsupportedEquationsException("Cannot solve stochastic "
                                                "equations with this state "
                                                "updater.")
        if variables is None:
            variables = {}

        # Get a representation of the ODE system in the form of
        # dX/dt = M*X + B
        varnames, matrix, constants = get_linear_system(equations, variables)

        # No differential equations, nothing to do (this occurs sometimes in the
        # test suite where the whole model is nothing more than something like
        # 'v : 1')
        if matrix.shape == (0, 0):
            return ''

        # Make sure that the matrix M is constant, i.e. it only contains
        # external variables or constant variables

        # Check for time dependence
        dt_value = variables['dt'].get_value(
        )[0] if 'dt' in variables else None

        # This will raise an error if we meet the symbol "t" anywhere
        # except as an argument of a locally constant function
        for entry in itertools.chain(matrix, constants):
            if not is_constant_over_dt(entry, variables, dt_value):
                raise UnsupportedEquationsException(
                    f"Expression '{sympy_to_str(entry)}' is not guaranteed to be "
                    f"constant over a time step.")

        symbols = [Symbol(variable, real=True) for variable in varnames]
        solution = sp.solve_linear_system(matrix.row_join(constants), *symbols)
        if solution is None or set(symbols) != set(solution.keys()):
            raise UnsupportedEquationsException("Cannot solve the given "
                                                "equations with this "
                                                "stateupdater.")
        b = sp.ImmutableMatrix([solution[symbol] for symbol in symbols])

        # Solve the system
        dt = Symbol('dt', real=True, positive=True)
        try:
            A = (matrix * dt).exp()
        except NotImplementedError:
            raise UnsupportedEquationsException("Cannot solve the given "
                                                "equations with this "
                                                "stateupdater.")
        if method_options['simplify']:
            A = A.applyfunc(
                lambda x: sp.factor_terms(sp.cancel(sp.signsimp(x))))
        C = sp.ImmutableMatrix(A * b) - b
        _S = sp.MatrixSymbol('_S', len(varnames), 1)
        updates = A * _S + C
        updates = updates.as_explicit()

        # The solution contains _S[0, 0], _S[1, 0] etc. for the state variables,
        # replace them with the state variable names
        abstract_code = []
        for idx, (variable, update) in enumerate(zip(varnames, updates)):
            rhs = update
            if rhs.has(I, re, im):
                raise UnsupportedEquationsException(
                    "The solution to the linear system "
                    "contains complex values "
                    "which is currently not implemented.")
            for row_idx, varname in enumerate(varnames):
                rhs = rhs.subs(_S[row_idx, 0], varname)

            # Do not overwrite the real state variables yet, the update step
            # of other state variables might still need the original values
            abstract_code.append(f"_{variable} = {sympy_to_str(rhs)}")

        # Update the state variables
        for variable in varnames:
            abstract_code.append(f"{variable} = _{variable}")
        return '\n'.join(abstract_code)
Exemple #35
0
    def __call__(self, equations, variables=None):

        if variables is None:
            variables = {}

        # Get a representation of the ODE system in the form of
        # dX/dt = M*X + B
        varnames, matrix, constants = get_linear_system(equations)

        # Make sure that the matrix M is constant, i.e. it only contains
        # external variables or constant variables
        symbols = set.union(*(el.atoms() for el in matrix))
        non_constant = _non_constant_symbols(symbols, variables)
        if len(non_constant):
            raise ValueError(('The coefficient matrix for the equations '
                              'contains the symbols %s, which are not '
                              'constant.') % str(non_constant))

        symbols = [Symbol(variable, real=True) for variable in varnames]
        solution = sp.solve_linear_system(matrix.row_join(constants), *symbols)
        b = sp.ImmutableMatrix([solution[symbol]
                                for symbol in symbols]).transpose()

        # Solve the system
        dt = Symbol('dt', real=True, positive=True)
        A = (matrix * dt).exp()
        C = sp.ImmutableMatrix([A.dot(b)]) - b
        _S = sp.MatrixSymbol('_S', len(varnames), 1)
        updates = A * _S + C.transpose()
        try:
            # In sympy 0.7.3, we have to explicitly convert it to a single matrix
            # In sympy 0.7.2, it is already a matrix (which doesn't have an
            # is_explicit method)
            updates = updates.as_explicit()
        except AttributeError:
            pass

        # The solution contains _S[0, 0], _S[1, 0] etc. for the state variables,
        # replace them with the state variable names
        abstract_code = []
        for idx, (variable, update) in enumerate(zip(varnames, updates)):
            rhs = update.subs(_S[idx, 0], variable)
            identifiers = get_identifiers(sympy_to_str(rhs))
            for identifier in identifiers:
                if identifier in variables:
                    var = variables[identifier]
                    if var is None:
                        print identifier, variables
                    if var.scalar and var.constant:
                        float_val = var.get_value()
                        rhs = rhs.xreplace(
                            {Symbol(identifier, real=True): Float(float_val)})

            # Do not overwrite the real state variables yet, the update step
            # of other state variables might still need the original values
            abstract_code.append('_' + variable + ' = ' + sympy_to_str(rhs))

        # Update the state variables
        for variable in varnames:
            abstract_code.append(
                '{variable} = _{variable}'.format(variable=variable))
        return '\n'.join(abstract_code)
from sympy import symbols, Matrix, solve_linear_system
from sympy.abc import x, y

S2 = Matrix((
    # x1, x2, x3 ... x6
    (0.0, 0.0, 1.0, 2.0, 0.0, 2.0),  # [L]
    (1.0, 0.0, 0.0, 1.0, 0.0, 1.0),  # [M]
    (0.0, -1.0, 0.0, -2.0, 1.0, 0.00)  # [T]
))

x1, x2, x3, x4, x5, x6 = symbols('x1 x2 x3 x4 x5 x6')

solve_linear_system(S2, x1, x2, x3, x4, x5, x6)
 def template_12(self, a, b):
     m = sympy.symbols('x')
     n = sympy.symbols('y')
     system = sympy.Matrix(((1, 1, a), (1, -1, b)))
     return sympy.solve_linear_system(system, m, n)
Exemple #38
0
def balance(eq):
    M = getmatrix(eq)
    lefteq = re.split("=", eq)[0]
    righteq = re.split("=", eq)[1]

    left_compounds = re.split('\s*\+\s*', lefteq)
    right_compounds = re.split('\s*\+\s*', righteq)

    elements = []

    for l_ele in left_compounds:
        help_list = re.findall(r'([A-Z][a-z]{0,1})(\d*)', l_ele)
        for ele in help_list:
            if ele[0] not in elements:
                elements.append(ele[0])

    n = len(left_compounds) + len(right_compounds)
    x = [parse_expr('x%d' % i) for i in range(n)]
    x = sp.symbols('x0:%d' % n)
    sols = sp.solve_linear_system(M, *x)
    new_dict = {}

    for i in x:
        new_dict[i] = 1
    # print new_dict
    for key in sols:
        if sols[key].args == ():
            new_dict[key] = 1
        else:
            new_dict[key] = (sols[key]).args[0]

    # remove fractions
    final_list = []
    for i in range(n):
        final_list.append(sp.fraction(new_dict[x[i]])[1])
    f = sp.lcm(final_list)
    for key in new_dict:
        new_dict[key] = new_dict[key] * f

    # form the final output string
    final_string = ""
    for i in range(len(left_compounds)):
        if new_dict[x[i]] == 1:
            final_string += left_compounds[i]
        else:
            final_string += str(new_dict[x[i]]) + left_compounds[i]
        if i != (len(left_compounds) - 1):
            final_string += '+'

    final_string += '='

    for i in range(len(right_compounds)):
        temp = len(left_compounds)
        if new_dict[x[i + temp]] == 1:
            final_string += right_compounds[i]
        else:
            final_string += str(new_dict[x[i + temp]]) + right_compounds[i]
        if i != (len(right_compounds) - 1):
            final_string += '+'

    return final_string
 def template_1(self, a, b, c, d, e, f):
     m = sympy.symbols('x')
     n = sympy.symbols('y')
     system = sympy.Matrix(((a, b, c), (d, e, f)))
     return sympy.solve_linear_system(system, m, n)
Exemple #40
0
def timeit_linsolve_trivial():
    solve_linear_system(M, *S)
Exemple #41
0
    def __call__(self, equations, variables=None, simplify=True):

        if variables is None:
            variables = {}

        # Get a representation of the ODE system in the form of
        # dX/dt = M*X + B
        varnames, matrix, constants = get_linear_system(equations)

        # No differential equations, nothing to do (this occurs sometimes in the
        # test suite where the whole model is nothing more than something like
        # 'v : 1')
        if matrix.shape == (0, 0):
            return ''

        # Make sure that the matrix M is constant, i.e. it only contains
        # external variables or constant variables
        t = Symbol('t', real=True, positive=True)

        # Check for time dependence
        if 'dt' in variables:
            dt_value = variables['dt'].get_value()[0]

            # This will raise an error if we meet the symbol "t" anywhere
            # except as an argument of a locally constant function
            t = Symbol('t', real=True, positive=True)
            for entry in itertools.chain(matrix, constants):
                _check_for_locally_constant(entry, variables, dt_value, t)

        symbols = [Symbol(variable, real=True) for variable in varnames]
        solution = sp.solve_linear_system(matrix.row_join(constants), *symbols)
        b = sp.ImmutableMatrix([solution[symbol] for symbol in symbols]).transpose()

        # Solve the system
        dt = Symbol('dt', real=True, positive=True)
        A = (matrix * dt).exp()
        if simplify:
            A.simplify()
        C = sp.ImmutableMatrix([A.dot(b)]) - b
        _S = sp.MatrixSymbol('_S', len(varnames), 1)
        # The use of .as_mutable() here is a workaround for a
        # ``Transpose object does not have
        updates = A * _S + C.transpose()
        try:
            # In sympy 0.7.3, we have to explicitly convert it to a single matrix
            # In sympy 0.7.2, it is already a matrix (which doesn't have an
            # is_explicit method)
            updates = updates.as_explicit()
        except AttributeError:
            pass

        # The solution contains _S[0, 0], _S[1, 0] etc. for the state variables,
        # replace them with the state variable names 
        abstract_code = []
        for idx, (variable, update) in enumerate(zip(varnames, updates)):
            rhs = update
            for row_idx, varname in enumerate(varnames):
                rhs = rhs.subs(_S[row_idx, 0], varname)

            # Do not overwrite the real state variables yet, the update step
            # of other state variables might still need the original values
            abstract_code.append('_' + variable + ' = ' + sympy_to_str(rhs))

        # Update the state variables
        for variable in varnames:
            abstract_code.append('{variable} = _{variable}'.format(variable=variable))
        return '\n'.join(abstract_code)
Exemple #42
0
    def compute_L(self):
        """
        Compute L matrix of corrective solution:
        it works differently for symmetric and non-symmetric sections
        """

        nnode = len(self.g.nodes())

        # TODO: can it be globally defined?
        nodedict = dict(zip(self.g.nodes(), range(nnode)))

        self.L = sympy.zeros(nnode, nnode - 3)

        # define as many symbols as nodes
        aa = sympy.symbols("a0:%d" % nnode)

        self.expr = []

        # symmetric sections
        if any(self.is_symmetric):

            # select list of symmetric nodes (y-axis symmetry is privileged)
            if self.is_symmetric[0]:
                act_nodes = self.symmetry[0]["nodes"]
            else:
                act_nodes = self.symmetry[1]["nodes"]

            # assign a symbol to each node, for symmetric and antisymmetric loads
            self.val = sympy.zeros(nnode, 2)

            ai = 0
            a_sym = []
            a_asym = []
            for nc in act_nodes:

                # node on axis (zero for antisymmetric, symbol fo symmetric)

                if nc[0] != nc[1]:
                    # antisymmetric
                    self.val[nodedict[nc[0]], 1] = aa[ai]
                    self.val[nodedict[nc[1]], 1] = -aa[ai]
                    a_asym.append(aa[ai])
                    ai += 1

                # symmetric
                self.val[nodedict[nc[0]], 0] = aa[ai]
                self.val[nodedict[nc[1]], 0] = aa[ai]
                a_sym.append(aa[ai])
                ai += 1

            # write an equation for Rz = 0 (only symmetric)
            self.expr.append(sum(self.val[:, 0]))
            # write and equation for Mx = 0 (only symmetric)
            self.expr.append(sum([self.val[nodedict[ni], 0] * self.g.node[ni]["pos"][1] for ni in self.g.nodes()]))
            # write an equation for My = 0 (only antisymmetric)
            self.expr.append(sum([self.val[nodedict[ni], 1] * self.g.node[ni]["pos"][0] for ni in self.g.nodes()]))

            # write a system of equation for Rz = 0 and Mx = 0
            self.system1 = sympy.zeros(len(a_sym) + 1, 2)

            for k in range(2):
                dd = sympy.poly(self.expr[k], a_sym)
                for ii, ai in enumerate(a_sym):
                    self.system1[ii, k] = dd.coeff_monomial(ai)

                # self.system1[0:len(a_sym),k] = dd.coeffs()

            # solve the first underdetermined system
            self.sol1 = sympy.solve_linear_system(self.system1.T, *a_sym)

            # write a system (actually only a single equation) for My = 0
            self.system2 = sympy.zeros(len(a_asym) + 1, 1)
            dd = sympy.poly(self.expr[2], a_asym)

            for ii, ai in enumerate(a_asym):
                self.system2[ii, 0] = dd.coeff_monomial(ai)

            # self.system2[0:len(a_asym),0] = dd.coeffs()

            # solve second underdetermined system
            self.sol2 = sympy.solve_linear_system(self.system2.T, *a_asym)
            # search for free variables
            free_var = [[ai for ai in a_sym if ai not in self.sol1], [ai for ai in a_asym if ai not in self.sol2]]

            # buld lists of combinations of free variables
            self.free = [[], []]

            # for each set of equations (symmetric and antisymmetric)
            # write every possible combination of free variables (a single 1 and the rest 0)
            for kk in range(2):
                for snum, sym in enumerate(free_var[kk]):
                    self.free[kk].append([])
                    for snum1, sym1 in enumerate(free_var[kk]):
                        if snum == snum1:
                            self.free[kk][snum].append((sym1, 1))
                        else:
                            self.free[kk][snum].append((sym1, 0))

            # solution list of symmetric component
            self.symm_sol_list = []

            # assign every possible set of free variables to the underdetermined system
            for ns, ls in enumerate(self.free[0]):
                self.symm_sol_list.append([(ai, self.sol1[ai].subs(ls)) for ai in self.sol1])
                for li in ls:
                    self.symm_sol_list[ns].append(li)

            # polulate L
            for nsol, sol_list in enumerate(self.symm_sol_list):
                self.L[:, nsol] = self.val[:, 0].subs(sol_list)

            # solution list for antisymmetric component
            self.asym_sol_list = []

            # assign every possible set of free variables to the underdetermined system
            for ns, ls in enumerate(self.free[1]):
                self.asym_sol_list.append([(ai, self.sol2[ai].subs(ls)) for ai in self.sol2])
                for li in ls:
                    self.asym_sol_list[ns].append(li)

            # populate L
            for nsol, sol_list in enumerate(self.asym_sol_list):
                self.L[:, -1 - nsol] = self.val[:, 1].subs(sol_list)

        # section is not symmetric
        else:
            # assign variables progressively
            self.val = sympy.zeros(nnode, 1)
            for kk in range(nnode):
                self.val[kk] = aa[kk]

            # write equations for Rz Mx My = 0
            self.expr.append(sum(self.val))
            self.expr.append(sum([self.val[nodedict[ni]] * self.g.node[ni]["pos"][1] for ni in self.g.nodes()]))
            self.expr.append(sum([self.val[nodedict[ni]] * self.g.node[ni]["pos"][0] for ni in self.g.nodes()]))

            # write a system of equations
            self.system1 = sympy.zeros(len(aa) + 1, 3)

            for k in range(3):
                dd = sympy.poly(self.expr[k], aa)
                for ii, ai in enumerate(aa):
                    self.system1[ii, k] = dd.coeff_monomial(ai)
            # print(self.system1)
            # solve the underdetermined system
            self.sol1 = sympy.solve_linear_system(self.system1.T, *aa)

            # search for free variables
            free_var = [ai for ai in aa if ai not in self.sol1]

            self.free = []

            # find every possible combination of free variables (a single 1 and all zeros)
            for snum, sym in enumerate(free_var):
                self.free.append([])
                for snum1, sym1 in enumerate(free_var):
                    if snum == snum1:
                        self.free[snum].append((sym1, 1))
                    else:
                        self.free[snum].append((sym1, 0))

            # solution list
            self.sol_list = []
            # substitute each possible combination of free variables to others
            for ns, ls in enumerate(self.free):
                self.sol_list.append([(ai, self.sol1[ai].subs(ls)) for ai in self.sol1])
                for li in ls:
                    self.sol_list[ns].append(li)

            # polulate L
            for nsol, sol_list in enumerate(self.sol_list):
                self.L[:, nsol] = self.val[:, 0].subs(sol_list)

            self.L = sympy.simplify(self.L)
# Solución gráfica.
x_vals = np.linspace(-5, 5, 50)  # crea 50 valores entre 0 y 5
ax = dibuja_figura()
ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
ax.grid()
ax.plot(x_vals, (1.2 * x_vals) / -2.2)  # grafica 1.2x_1 - 2.2x_2 = 0
a = ax.plot(x_vals, (1.1 * x_vals) / 1.4)  # grafica 1.1x_1 + 1.4x_2 = 0


# Sympy para resolver el sistema de ecuaciones lineales
a1, a2, a3 = sympy.symbols("a1, a2, a3")
A = sympy.Matrix(((3, 3, 3, 0), (2, 2, 2, 0), (2, 1, 0, 0), (3, 2, 1, 0)))

sympy.solve_linear_system(A, a1, a2, a3)
A = sympy.Matrix(((1, 1, 1, 0), (-2, 1, 1, 0), (-1, 2, 0, 0)))
sympy.solve_linear_system(A, a1, a2, a3)

# Calculando el rango con SymPy
A = sympy.Matrix([[1, 1, 1, 4], [1, 2, 1, 5], [1, 1, 1, 6]])
# Rango con SymPy
print A.rank()

# Calculando el rango con numpy
A = np.array([[1, 1, 2, 4], [1, 1, 2, 5], [1, 1, 2, 6]])

print np.linalg.matrix_rank(A)


# Determinante con sympy