Пример #1
0
def tractionMax(mass, g, wtRearFrac, wheelbase, cgh, driveWheel, muTire):
    Fr = sym.Symbol('Fr')
    Ff = sym.Symbol('Ff')
    Fa = sym.Symbol('Fa')

    if driveWheel == 'AWD':
        print('AWD')
        wheelForceMax = mass*g*muTire
    elif driveWheel == 'FWD':
        print('FWD')
        eq1 = Fr + Ff - mass*g
        eq2 = Fr*(1-wtRearFrac)*wheelbase - Ff*wtRearFrac*wheelbase - Fa*cgh
        eq3 = Fa - Ff*muTire

        X = linsolve([eq1, eq2, eq3], (Fr, Ff, Fa))
        # extract the solution for eq3
        wheelForceMax = X.args[0][2]
    else: #RWD case

        eq1 = Fr + Ff - mass*g
        eq2 = Fr*(1-wtRearFrac)*wheelbase - Ff*wtRearFrac*wheelbase - Fa*cgh
        eq3 = Fa - Fr*muTire

        X = linsolve([eq1, eq2, eq3], (Fr, Ff, Fa))
        # extract the solution for eq3
        wheelForceMax = X.args[0][2]

    # cast to float for speed
    return float(wheelForceMax)
Пример #2
0
def test_linsolve():
    x, y, z, u, v, w = symbols("x, y, z, u, v, w")
    x1, x2, x3, x4 = symbols('x1, x2, x3, x4')

    # Test for different input forms

    M = Matrix([[1, 2, 1, 1, 7], [1, 2, 2, -1, 12], [2, 4, 0, 6, 4]])
    system1 = A, b = M[:, :-1], M[:, -1]
    Eqns = [
        x1 + 2 * x2 + x3 + x4 - 7, x1 + 2 * x2 + 2 * x3 - x4 - 12,
        2 * x1 + 4 * x2 + 6 * x4 - 4
    ]

    sol = FiniteSet((-2 * x2 - 3 * x4 + 2, x2, 2 * x4 + 5, x4))
    assert linsolve(M, (x1, x2, x3, x4)) == sol
    assert linsolve(Eqns, (x1, x2, x3, x4)) == sol
    assert linsolve(system1, (x1, x2, x3, x4)) == sol

    # raise ValueError if no symbols are given
    raises(ValueError, lambda: linsolve(system1))

    # raise ValueError if, A & b is not given as tuple
    raises(ValueError, lambda: linsolve(A, b, x1, x2, x3, x4))

    # raise ValueError for garbage value
    raises(ValueError, lambda: linsolve(Eqns[0], x1, x2, x3, x4))

    # Fully symbolic test
    a, b, c, d, e, f = symbols('a, b, c, d, e, f')
    A = Matrix([[a, b], [c, d]])
    B = Matrix([[e], [f]])
    system2 = (A, B)
    sol = FiniteSet((-b * (f - c * e / a) / (a * (d - b * c / a)) + e / a,
                     (f - c * e / a) / (d - b * c / a)))
    assert linsolve(system2, [x, y]) == sol

    # Test for Dummy Symbols issue #9667
    x1 = Dummy('x1')
    x2 = Dummy('x2')
    x3 = Dummy('x3')
    x4 = Dummy('x4')

    assert linsolve(system1, x1, x2, x3, x4) == FiniteSet(
        (-2 * x2 - 3 * x4 + 2, x2, 2 * x4 + 5, x4))

    # No solution
    A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
    b = Matrix([0, 0, 1])
    assert linsolve((A, b), (x, y, z)) == EmptySet()

    # Issue #10121 - Assignment of free variables
    a, b, c, d, e = symbols('a, b, c, d, e')
    Augmatrix = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]])
    assert linsolve(Augmatrix, a, b, c, d, e) == FiniteSet((a, 0, c, 0, e))
Пример #3
0
def test_linsolve():
    x, y, z, u, v, w = symbols("x, y, z, u, v, w")
    x1, x2, x3, x4 = symbols('x1, x2, x3, x4')

    # Test for different input forms

    M = Matrix([[1, 2, 1, 1, 7], [1, 2, 2, -1, 12], [2, 4, 0, 6, 4]])
    system1 = A, b = M[:, :-1], M[:, -1]
    Eqns = [x1 + 2*x2 + x3 + x4 - 7, x1 + 2*x2 + 2*x3 - x4 - 12,
            2*x1 + 4*x2 + 6*x4 - 4]

    sol = FiniteSet((-2*x2 - 3*x4 + 2, x2, 2*x4 + 5, x4))
    assert linsolve(M, (x1, x2, x3, x4)) == sol
    assert linsolve(Eqns, (x1, x2, x3, x4)) == sol
    assert linsolve(system1, (x1, x2, x3, x4)) == sol

    # raise ValueError if no symbols are given
    raises(ValueError, lambda: linsolve(system1))

    # raise ValueError if, A & b is not given as tuple
    raises(ValueError, lambda: linsolve(A, b, x1, x2, x3, x4))

    # raise ValueError for garbage value
    raises(ValueError, lambda: linsolve(Eqns[0], x1, x2, x3, x4))

    # Fully symbolic test
    a, b, c, d, e, f = symbols('a, b, c, d, e, f')
    A = Matrix([[a, b], [c, d]])
    B = Matrix([[e], [f]])
    system2 = (A, B)
    sol = FiniteSet((-b*(f - c*e/a)/(a*(d - b*c/a)) + e/a,
                    (f - c*e/a)/(d - b*c/a)))
    assert linsolve(system2, [x, y]) == sol

    # Test for Dummy Symbols issue #9667
    x1 = Dummy('x1')
    x2 = Dummy('x2')
    x3 = Dummy('x3')
    x4 = Dummy('x4')

    assert linsolve(system1, x1, x2, x3, x4) == FiniteSet((-2*x2 - 3*x4 + 2, x2, 2*x4 + 5, x4))

    # No solution
    A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
    b = Matrix([0, 0, 1])
    assert linsolve((A, b), (x, y, z)) == EmptySet()

    # Issue #10121 - Assignment of free variables
    a, b, c, d, e = symbols('a, b, c, d, e')
    Augmatrix = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]])
    assert linsolve(Augmatrix, a, b, c, d, e) == FiniteSet((a, 0, c, 0, e))
Пример #4
0
def testAll(chosen,numchose,poss,dctCov,cnt,A,numEq):
	ret=[];
	if numchose<len(poss):
		for i in range(0,len(poss[numchose])):
			next=[c for c in chosen];
			next.append(poss[numchose][i]);
			ret.extend(testAll(next,numchose+1,poss,dctCov,cnt,A,numEq))
		return ret;
	b=[0 for i in range(0,numEq)];

	
	num=0;
	##add eqations from histogram
	for d in dctCov:
		b[num]=cnt[d]
		num=num+1;
	for i in range(0,len(chosen)):
		for k in range(0,6):
			b[num+k]=chosen[i][k]
		num=num+6;
	##want all nice solutions to Ax=b!!
	b=Matrix(b);
	symb=[symbols("x"+str(i)) for i in range(0,3*len(dctCov))]

	##
	##FINISH!!
	##
	solution=linsolve((A,b),symb);

	if solution==EmptySet():
		return [];
	else:
		return [solution];
Пример #5
0
def symbolCIP7():
    # Set symbolic parameters
    x, a, b, c, d, e, f, g, l, h, ui, ui1, gi, gi1, ggi, ggi1, gggi, gggi1 \
        = symbols('x, a, b, c, d, e, f, g, l, h, ui, ui1, gi, gi1, ggi, ggi1, gggi, gggi1')
    # Set interpolation polynomial
    func = l + g * x + f * x**2 + e * x**3 + d * x**4 + c * x**5 + b * x**6 + a * x**7
    df = func.diff(x)
    ddf = df.diff(x)
    dddf = ddf.diff(x)
    eq01 = func.subs(x, 0)
    eq02 = df.subs(x, 0)
    eq03 = func.subs(x, -h)
    eq04 = df.subs(x, -h)
    eq05 = ddf.subs(x, 0)
    eq06 = ddf.subs(x, -h)
    eq07 = dddf.subs(x, 0)
    eq08 = dddf.subs(x, -h)
    # Solve system under constrains
    sol = linsolve([
        eq01 - ui, eq02 - gi, eq03 - ui1, eq05 - ggi, eq04 - gi1, eq07 - gggi,
        eq06 - ggi1, eq08 - gggi1
    ], (a, b, c, d, e, f, g, l))
    sol_get = next(iter(sol))
    symbol_expr = ["a", "b", "c", "d", "e", "f", "g", "l"]
    for i in range(0, 8):
        print("{0} = {1}\n".format(symbol_expr[i], sol_get[i]))
Пример #6
0
def _transform_explike_DE(DE, g, x, order, syms):
    """Converts DE with free parameters into DE with constant coefficients."""
    from sympy.solvers.solveset import linsolve

    eq = []
    highest_coeff = DE.coeff(Derivative(g(x), x, order))
    for i in range(order):
        coeff = DE.coeff(Derivative(g(x), x, i))
        coeff = (coeff / highest_coeff).expand().collect(x)
        for t in Add.make_args(coeff):
            eq.append(t)
    temp = []
    for e in eq:
        if e.has(x):
            break
        elif e.has(Symbol):
            temp.append(e)
    else:
        eq = temp
    if eq:
        sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s)))
        if sol:
            DE = DE.subs(sol)
            DE = DE.factor().as_coeff_mul(Derivative)[1][0]
            DE = DE.collect(Derivative(g(x)))
    return DE
Пример #7
0
def solveSystemOfEqs(eqs):
	x = Symbol("x")
	y = Symbol("y")
	sol = linsolve([parse_expr(eqs[0],evaluate=0), parse_expr(eqs[1], evaluate=0)],(x,y))
	x_sol,y_sol = next(iter(sol))
	print ("x = " + str(x_sol) + ", y = " + str(y_sol))
	return (x_sol, y_sol)
Пример #8
0
    def weingarten_transform(self, vec):
        """
        Args:
        v: planar vector in tangent plane, which would be decomposed into r_u and r_v.
        """
        from sympy.solvers.solveset import linsolve
        from sympy import Matrix, symbols
        r_u, r_v = self.r_u, self.r_v

        c_ru, c_rv = symbols('c_ru, c_rv', real=True)
        solset = linsolve(
            Matrix(((r_u[0], r_v[0], vec[0]), (r_u[1], r_v[1], vec[1]),
                    (r_u[2], r_v[2], vec[2]))), (c_ru, c_rv))
        try:
            if len(solset) != 1:
                raise RuntimeError(
                    f"Sympy is not smart enough to decompose the v vector with r_u, r_v as the basis.\
                It found these solutions: {solset}.\
                Users need to choose from them or deduce manually, and then set it by arguments."
                )
        except:
            raise RuntimeError(
                "We failed to decompose the input vec into r_u and r_v")
        else:
            c_ru, c_rv = next(iter(solset))
        omega = self.weingarten_matrix
        W_r_u = omega[0, 0] * r_u + omega[1, 0] * r_v
        W_r_v = omega[0, 1] * r_u + omega[1, 1] * r_v
        return c_ru * W_r_u + c_rv * W_r_v
Пример #9
0
def eval_constraints(tf_constraints, solution_dict={}):
    # var dict: string variables names -> sympy variables
    # sol'n dict: string variable snames -> real values
    vardict = {}
    for i in range(1, tf_constraints.numVars + 1):
        vardict['x' + str(i)] = symbols('x' + str(i))

    for c in tf_constraints.constraints:
        if not isinstance(c, ReluConstraint):
            varsineq = [vardict[v] for v in c.x.flatten().tolist()]
            A = c.A
            b = c.b
            for string_varname in solution_dict.keys():
                # if appears in solution dict already, add row to matrix
                if string_varname in c.x:
                    Aaddition = np.array([
                        1 if e == string_varname else 0 for e in c.x
                    ]).reshape(1, -1)
                    A = Matrix(np.vstack((Aaddition, A)))
                    b = Matrix(
                        np.vstack(([[solution_dict[string_varname]]], b)))
            solns = linsolve((A, b), varsineq)
            sol_list = list([i for i in solns][0])
            for i in range(len(c.x)):
                solution_dict[c.x[i][0]] = sol_list[i]
        else:
            # if isa ReluConstraint
            for i in range(len(c.varout)):
                solution_dict[c.varout[i]] = max(0, solution_dict[c.varin[i]])

    return solution_dict
Пример #10
0
def ExactPressure(p_, lamb, mu, sx):

    lamb1, lamb2, lamb3, lamb4 = lamb
    mu1, mu2, mu3, mu4 = mu
    sx0, sx1, sx2, sx3, sx4 = sx

    x = sp.symbols('x')

    #b1=0
    ##only compression, epsz =0
    a1, a2, a3, a4, b2, b3, b4 = sp.symbols(
        'a_1, a_2, a_3, a_4, b_2, b_3, b_4')
    p = p_

    cof= linsolve([(a1-a2)*sx1 -b2/sx1, (a2-a3)*sx2 -b3/sx2 + b2/sx2, (a3-a4)*sx3 -b4/sx3 + b3/sx3,\
        2*(lamb1+mu1)*(a1) -  2*(lamb2+mu2)*(a2) +  2*mu2/sx1**2*b2,\
            2*(lamb2+mu2)*(a2) -  2*(lamb3+mu3)*(a3) -2*mu2/sx2**2*b2 +  2*mu3/sx2**2*b3, \
                2*(lamb3+mu3)*(a3) -  2*(lamb4+mu4)*(a4) -2*mu3/sx3**2*b3 +  2*mu4/sx3**2*b4,\
                    2*(lamb4+mu4)*(a4) -2*mu4/sx4**2*b4  -p ], (a1,a2,a3,a4,b2,b3,b4))
    a1_, a2_, a3_, a4_, b2_, b3_, b4_ = tuple(*cof)
    ans = sp.Piecewise((a1_ * x, x <= sx1),
                       (a2_ * x + b2_ / x, (x <= sx2) & (x > sx1)),
                       (a3_ * x + b3_ / x, (x <= sx3) & (x > sx2)),
                       (a4_ * x + b4_ / x, (x <= sx4) & (x > sx3)), (0, True))
    msh = np.linspace(sx0, sx4, 400)

    f_ans = sp.lambdify(x, ans)

    #print(tuple(*cof))

    return msh, f_ans(msh)
Пример #11
0
def collocations_method_modifyed_points(basis, 
                                        points, 
                                        func_for_substantiation,
                                        c,
                                        k,
                                        q):
    # unite basis functions to one
    func = build_function_from_basis(basis)
    # create from base func our psi func
    psi_func_1 = func_for_substantiation(func, k[0], q[0])
    psi_func_2 = func_for_substantiation(func, k[1], q[1])
    # generate variables for linsolve
    symbols = [sympy.Symbol('a' + str(i)) for i in range(len(points))]
    lin_system = []
    
    # substitude variables for linear system and simplify to linear with evalf
    for point in points:
        if point < c:
            psi_func = psi_func_1
        else:
            psi_func = psi_func_2
            
        lin_system.append(psi_func.subs(x, point).evalf())
    
    # solving our system
    answer = list(list(linsolve(lin_system, *symbols))[0])
    return answer
Пример #12
0
def solve_final_solution(init_conditions, a_n, c):
    debug_print('Equation to solve values for a_(i):', a_n)
    # -- step 5 (step 7 if nonhomogeneous) -- determine values for a_i
    eqs = []

    symbols_dict = dict(('a_%d' % k, symbols('a_%d' % k)) for k in range(1, c))
    locals().update(symbols_dict)

    for i in init_conditions:
        a = a_n.replace('n', str(i))
        a = a.split(' = ')
        eqs.append(parse_expr(a[1] + ' - ' + init_conditions.get(i)))

    #for eq in eqs:
    #    print('---->',eq)
    var = [symbols_dict.get(sym) for sym in symbols_dict]
    #for i in eqs:
    #    print(i)

    #print('------>',var)
    #solved = list(linsolve(eqs, var))
    solved = list(linsolve(eqs, var))[0]
    #print('---->',solved)
    #alpha = sorted([[var[key],solved[key]] for key in range(len(solved))])

    var, solved = zip(*sorted(zip([str(v) for v in var], solved))[::-1])
    #print('---->',var1)

    debug_print('Solved values for a_(i):', solved)
    for i in range(c - 1):
        a_n = a_n.replace(str(var[i]), str(solved[i]))
    a_n = a_n.split(' = ')[1]
    result = str(simplify(a_n))
    return result
Пример #13
0
def ExactEigenstrain(eig, lamb, mu, sx):

    lamb1, lamb2, lamb3, lamb4 = lamb
    mu1, mu2, mu3, mu4 = mu
    sx0, sx1, sx2, sx3, sx4 = sx
    eig_12, eig_23 = eig

    x = sp.symbols('x')

    #b1=0
    ##, epsz =0
    a1, a2, a3, a4, b2, b3, b4 = sp.symbols(
        'a_1, a_2, a_3, a_4, b_2, b_3, b_4')

    cof= linsolve([(a1-a2)*sx1 -b2/sx1, (a2-a3)*sx2 -b3/sx2 + b2/sx2, (a3-a4)*sx3 -b4/sx3 + b3/sx3,\
        2*(lamb1+mu1)*(a1) -  2*(lamb2+mu2)*(a2) +  2*mu2/sx1**2*b2 + (3*lamb2+2*mu2)*eig_12,\
            2*(lamb2+mu2)*(a2) -  2*(lamb3+mu3)*(a3) -2*mu2/sx2**2*b2 +  2*mu3/sx2**2*b3 -(3*lamb2+2*mu2)*eig_12 + (3*lamb3+2*mu3)*eig_23, \
                2*(lamb3+mu3)*(a3) -  2*(lamb4+mu4)*(a4) -2*mu3/sx3**2*b3 +  2*mu4/sx3**2*b4 - (3*lamb3+2*mu3)*eig_23,\
                    2*(lamb4+mu4)*(a4) -2*mu4/sx4**2*b4], (a1,a2,a3,a4,b2,b3,b4))
    a1_, a2_, a3_, a4_, b2_, b3_, b4_ = tuple(*cof)
    ans = sp.Piecewise((a1_ * x, x <= sx1),
                       (a2_ * x + b2_ / x, (x <= sx2) & (x > sx1)),
                       (a3_ * x + b3_ / x, (x <= sx3) & (x > sx2)),
                       (a4_ * x + b4_ / x, (x <= sx4) & (x > sx3)), (0, True))
    msh = np.linspace(sx0, sx4, 400)

    f_ans = sp.lambdify(x, ans)

    return msh, f_ans(msh)
Пример #14
0
def remove_redundant_sols(sol1, sol2, x):
    """
    Helper function to remove redundant
    solutions to the differential equation.
    """
    # If y1 and y2 are redundant solutions, there is
    # some value of the arbitrary constant for which
    # they will be equal

    syms1 = sol1.atoms(Symbol, Dummy)
    syms2 = sol2.atoms(Symbol, Dummy)
    num1, den1 = [Poly(e, x, extension=True) for e in sol1.together().as_numer_denom()]
    num2, den2 = [Poly(e, x, extension=True) for e in sol2.together().as_numer_denom()]
    # Cross multiply
    e = num1*den2 - den1*num2
    # Check if there are any constants
    syms = list(e.atoms(Symbol, Dummy))
    if len(syms):
        # Find values of constants for which solutions are equal
        redn = linsolve(e.all_coeffs(), syms)
        if len(redn):
            # Return the general solution over a particular solution
            if len(syms1) > len(syms2):
                return sol2
            # If both have constants, return the lesser complex solution
            elif len(syms1) == len(syms2):
                return sol1 if count_ops(syms1) >= count_ops(syms2) else sol2
            else:
                return sol1
Пример #15
0
def _transform_explike_DE(DE, g, x, order, syms):
    """Converts DE with free parameters into DE with constant coefficients."""
    from sympy.solvers.solveset import linsolve

    eq = []
    highest_coeff = DE.coeff(Derivative(g(x), x, order))
    for i in range(order):
        coeff = DE.coeff(Derivative(g(x), x, i))
        coeff = (coeff / highest_coeff).expand().collect(x)
        for t in Add.make_args(coeff):
            eq.append(t)
    temp = []
    for e in eq:
        if e.has(x):
            break
        elif e.has(Symbol):
            temp.append(e)
    else:
        eq = temp
    if eq:
        sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s)))
        if sol:
            DE = DE.subs(sol)
            DE = DE.factor().as_coeff_mul(Derivative)[1][0]
            DE = DE.collect(Derivative(g(x)))
    return DE
Пример #16
0
def symbolCIP9():
    # Set symbolic parameters
    x, a, b, c, d, e, f, g, l, k, q, h, ui, ui1, gi, gi1, ggi, ggi1, g3i, g3i1, g4i, g4i1 \
        = symbols('x, a, b, c, d, e, f, g, l, k, q, h, ui, ui1, gi, gi1, ggi, ggi1, g3i, g3i1, g4i, g4i1')

    # Set interpolation polynomial
    func = q + k * x + l * x**2 + g * x**3 + f * x**4 + e * x**5 + d * x**6 + c * x**7 + b * x**8 + a * x**9

    df = func.diff(x)
    ddf = df.diff(x)
    d3f = ddf.diff(x)
    d4f = d3f.diff(x)
    eq01 = func.subs(x, 0)
    eq02 = df.subs(x, 0)
    eq03 = func.subs(x, -h)
    eq04 = df.subs(x, -h)
    eq05 = ddf.subs(x, 0)
    eq06 = ddf.subs(x, -h)
    eq07 = d3f.subs(x, 0)
    eq08 = d3f.subs(x, -h)
    eq09 = d4f.subs(x, 0)
    eq10 = d4f.subs(x, -h)

    # Solve system under constrains

    sol = linsolve([
        eq01 - ui, eq02 - gi, eq03 - ui1, eq05 - ggi, eq04 - gi1, eq07 - g3i,
        eq06 - ggi1, eq08 - g3i1, eq09 - g4i, eq10 - g4i1
    ], (a, b, c, d, e, f, g, l, k, q))

    sol_get = next(iter(sol))
    symbol_expr = ["a", "b", "c", "d", "e", "f", "g", "l", "k", "q"]
    for i in range(0, 10):
        print("{0} = {1}\n".format(symbol_expr[i], sol_get[i]))
Пример #17
0
def combineDct(dctt1, dct2, cnt):
    if len(dct1) == 0 or len(dct2) == 0:
        return []
    ret = []
    b = [0 for i in range(0, 8 * len(dct1))]
    A = [[0 for i in range(0, 6 * len(dct1))] for j in range(0, 8 * len(dct1))]

    cnt_keys = [c for c in cnt]

    cnt_dct = {}
    for i in range(0, len(cnt)):
        cnt_dct[cnt_keys[i]] = i

    num = 0
    for j in range(0, 3):
        for d in dct1:
            val1 = d + (1)
            val2 = d + (0)
            b[num] = dct1[d][j]
            A[num][3 * cnt_dct[val1] + j] = 1
            A[num][3 * cnt_dct[val2] + j] = 1
            num = num + 1
            val1 = (1) + d
            val2 = (0) + d
            b[num] = dct2[d][j]
            A[num][3 * cnt_dct[val1] + j] = 1
            A[num][3 * cnt_dct[val2] + j] = 1
            num = num + 1
    for d in dct:
        val1 = d + (1)
        val2 = d + (0)
        b[num] = cnt[val1]
        for j in range(0, 3):
            A[num][3 * cnt_dct[val1] + j] = 1
        num = num + 1
        b[num] = cnt[val2]
        for j in range(0, 3):
            A[num][3 * cnt_dct[val2] + j] = 1
        num = num + 1
    #A=np.asarray();
    poss = []
    A = Matrix(A)
    b = Matrix(b)

    linsolve()
Пример #18
0
def test_linsolve():
    x, y, z, u, v, w = symbols("x, y, z, u, v, w")
    x1, x2, x3, x4 = symbols('x1, x2, x3, x4')

    # Test for different input forms

    M = Matrix([[1, 2, 1, 1, 7], [1, 2, 2, -1, 12], [2, 4, 0, 6, 4]])
    system = A, b = M[:, :-1], M[:, -1]
    Eqns = [x1 + 2*x2 + x3 + x4 - 7, x1 + 2*x2 + 2*x3 - x4 - 12,
            2*x1 + 4*x2 + 6*x4 - 4]

    sol = FiniteSet((-2*x2 - 3*x4 + 2, x2, 2*x4 + 5, x4))
    assert linsolve(M, (x1, x2, x3, x4)) == sol
    assert linsolve(Eqns, (x1, x2, x3, x4)) == sol
    assert linsolve(system, (x1, x2, x3, x4)) == sol

    # raise ValueError if no symbols are given
    raises(ValueError, lambda: linsolve(system))

    # raise ValueError if, A & b is not given as tuple
    raises(ValueError, lambda: linsolve(A, b, x1, x2, x3, x4))

    # raise ValueError for garbage value
    raises(ValueError, lambda: linsolve(Eqns[0], x1, x2, x3, x4))

    # Fully symbolic test
    a, b, c, d, e, f = symbols('a, b, c, d, e, f')
    A = Matrix([[a, b], [c, d]])
    B = Matrix([[e], [f]])
    system = (A, B)
    sol = FiniteSet((-b*(f - c*e/a)/(a*(d - b*c/a)) + e/a,
                    (f - c*e/a)/(d - b*c/a)))
    assert linsolve(system, [x, y]) == sol
Пример #19
0
def test_linsolve():
    x, y, z, u, v, w = symbols("x, y, z, u, v, w")
    x1, x2, x3, x4 = symbols("x1, x2, x3, x4")

    # Test for different input forms

    M = Matrix([[1, 2, 1, 1, 7], [1, 2, 2, -1, 12], [2, 4, 0, 6, 4]])
    system = A, b = M[:, :-1], M[:, -1]
    Eqns = [x1 + 2 * x2 + x3 + x4 - 7, x1 + 2 * x2 + 2 * x3 - x4 - 12, 2 * x1 + 4 * x2 + 6 * x4 - 4]

    sol = FiniteSet((-2 * x2 - 3 * x4 + 2, x2, 2 * x4 + 5, x4))
    assert linsolve(M, (x1, x2, x3, x4)) == sol
    assert linsolve(Eqns, (x1, x2, x3, x4)) == sol
    assert linsolve(system, (x1, x2, x3, x4)) == sol

    # raise ValueError if no symbols are given
    raises(ValueError, lambda: linsolve(system))

    # raise ValueError if, A & b is not given as tuple
    raises(ValueError, lambda: linsolve(A, b, x1, x2, x3, x4))

    # raise ValueError for garbage value
    raises(ValueError, lambda: linsolve(Eqns[0], x1, x2, x3, x4))

    # Fully symbolic test
    a, b, c, d, e, f = symbols("a, b, c, d, e, f")
    A = Matrix([[a, b], [c, d]])
    B = Matrix([[e], [f]])
    system = (A, B)
    sol = FiniteSet((-b * (f - c * e / a) / (a * (d - b * c / a)) + e / a, (f - c * e / a) / (d - b * c / a)))
    assert linsolve(system, [x, y]) == sol
Пример #20
0
 def _contains(self, other):
     from sympy.matrices import Matrix
     from sympy.solvers.solveset import solveset, linsolve
     from sympy.utilities.iterables import iterable, cartes
     L = self.lamda
     if self._is_multivariate():
         if not iterable(L.expr):
             if iterable(other):
                 return S.false
             return other.as_numer_denom() in self.func(
                 Lambda(L.variables, L.expr.as_numer_denom()), self.base_set)
         if len(L.expr) != len(self.lamda.variables):
             raise NotImplementedError(filldedent('''
 Dimensions of input and output of Lambda are different.'''))
         eqs = [expr - val for val, expr in zip(other, L.expr)]
         variables = L.variables
         free = set(variables)
         if all(i.is_number for i in list(Matrix(eqs).jacobian(variables))):
             solns = list(linsolve([e - val for e, val in
             zip(L.expr, other)], variables))
         else:
             syms = [e.free_symbols & free for e in eqs]
             solns = {}
             for i, (e, s, v) in enumerate(zip(eqs, syms, other)):
                 if not s:
                     if e != v:
                         return S.false
                     solns[vars[i]] = [v]
                     continue
                 elif len(s) == 1:
                     sy = s.pop()
                     sol = solveset(e, sy)
                     if sol is S.EmptySet:
                         return S.false
                     elif isinstance(sol, FiniteSet):
                         solns[sy] = list(sol)
                     else:
                         raise NotImplementedError
                 else:
                     raise NotImplementedError
             solns = cartes(*[solns[s] for s in variables])
     else:
         # assume scalar -> scalar mapping
         solnsSet = solveset(L.expr - other, L.variables[0])
         if solnsSet.is_FiniteSet:
             solns = list(solnsSet)
         else:
             raise NotImplementedError(filldedent('''
             Determining whether an ImageSet contains %s has not
             been implemented.''' % func_name(other)))
     for soln in solns:
         try:
             if soln in self.base_set:
                 return S.true
         except TypeError:
             return self.base_set.contains(soln.evalf())
     return S.false
Пример #21
0
def symbolCIP(nOrder):
    # Simple check
    if nOrder % 2 == 0:
        sys.exit("Order might be odd more than 3,\n"
                 "for issue 3, 5, 7, 9, etc.")

    # Set values
    coeff = symbols('a0:%d' % (nOrder + 1))
    xi, h = symbols('xi, h')
    ucval = symbols('uC:%d' % (nOrder - 1))
    urval = symbols('uR:%d' % (nOrder - 1))
    ulval = symbols('uL:%d' % (nOrder - 1))

    # Set interpolation polynomials
    fpoly = sum(coeff[k] * xi**k for k in range(nOrder + 1))
    dfpoly = []
    for k in range(np.int((nOrder + 1) / 2)):
        dfpoly.append(fpoly.diff(xi, k))

    # Set constrains
    eqs_left = []
    eqs_right = []
    for k in range(np.int((nOrder + 1) / 2)):
        eqs_right.append(dfpoly[k].subs(xi, 0))
        eqs_right.append(dfpoly[k].subs(xi, -h))
        eqs_left.append(dfpoly[k].subs(xi, 0))
        eqs_left.append(dfpoly[k].subs(xi, h))

    # Solve system under constrains
    # Right wave
    vals_right = ucval + ulval
    sys_eqns_right = [
        eqs_right[k] - vals_right[k] for k in range((nOrder + 1))
    ]
    sol_right = linsolve(sys_eqns_right, coeff)
    sol_right_list = list(sol_right)
    print('Right wave:\n', sol_right_list[0])
    # Left wave
    vals_left = ucval + urval
    sys_eqns_left = [eqs_left[k] - vals_left[k] for k in range((nOrder + 1))]
    sol_left = linsolve(sys_eqns_left, coeff)
    sol_left_list = list(sol_left)
    print('Left wave:\n', sol_left_list[0])
Пример #22
0
def expectation(lam):
    p = Matrix([[-prob(i, j, lam) for j in range(k)] for i in range(k)])
    for i in range(k):
        p[(k + 1) * i] = -sum(p.row(i)) + (Fraction(
            lam, n))**(k - i) * (Fraction(n - lam, n))**(n - k + i)
    return next(
        iter(
            linsolve(
                (p, ones(k, 1)),
                symbols(', '.join(['x_{}'.format(i) for i in range(k)])))))[0]
Пример #23
0
def linsolve_dict(eq, syms):
    """
    Get the output of linsolve as a dict
    """
    # Convert tuple type return value of linsolve
    # to a dictionary for ease of use
    sol = linsolve(eq, syms)
    if not sol:
        return {}
    return {k:v for k, v in zip(syms, list(sol)[0])}
Пример #24
0
def symboldeltaP3():
    x, a, h, t, nu, c1, c2, c3, c4, ui, ui1, ri, ri1, uxx, u3x, rx, rxx, _uni \
        = symbols('x, a, h, t, nu, c1, c2, c3, c4, ui, ui1, ri, ri1, uxx, u3x, rx, rxx, _uni')

    u = c1 + c2 * x + c3 * x**2 + c4 * x**3

    du = u.diff(x)
    # Set constrains
    eq01 = u.subs(x, 0)
    eq02 = du.subs(x, 0)
    eq03 = u.subs(x, -h)
    eq04 = du.subs(x, -h)
    # Solve system under constrains
    sol = linsolve([eq01 - ui, eq02 - ri, eq03 - ui1, eq04 - ri1],
                   (c1, c2, c3, c4))
    # Get coefficients
    sol_get = next(iter(sol))
    c1_expr = sol_get[0].subs(ri, ri / h)
    c2_expr = sol_get[1].subs(ri, ri / h)
    c3_expr = sol_get[2].subs(ri, ri / h).subs(ri1, ri1 / h)
    c4_expr = sol_get[3].subs(ri, ri / h).subs(ri1, ri1 / h)
    print(("c1 = {0}\nc2 = {1}\nc3 = {2}\nc4 = {3}".format(
        c1_expr, c2_expr, c3_expr, c4_expr)))

    # Set constrains
    ui = u.subs(x, 0)

    ux = u.diff(x)
    uxi = ux.subs(x, 0)

    uxx = ux.diff(x)
    uxxi = uxx.subs(x, 0)

    u3x = uxx.diff(x)
    u3xi = u3x.subs(x, 0)

    r = h * u.diff(x)
    ri = r.subs(x, 0)

    rx = r.diff(x)
    rxi = rx.subs(x, 0)

    rxx = rx.diff(x)
    rxxi = rxx.subs(x, 0)

    uni = ui - a * t * uxi + a**2 * t**2 / 2 * uxxi - a**3 * t**3 / 6 * u3xi
    _uni = uni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(
        c4, c4_expr).subs(a * t / h, nu)
    _uni = collect(expand(_uni), nu)
    print(_uni)

    rni = simplify(ri - a * t * rxi + a**2 * t**2 / 2 * rxxi)
    _rni = rni.subs(c1, c1_expr).subs(c2, c2_expr).subs(c3, c3_expr).subs(
        c4, c4_expr).subs(a * t / h, nu)
    print(collect(expand(_rni), nu))
Пример #25
0
def find_point(p1, p2, r, oc):
    p = p1[0]
    q = p1[1]
    a = p2[0]
    b = p2[1]
    x0 = oc[0]
    y0 = oc[1]

    # solution 1
    cons11 = (p * q + r * (math.sqrt(p**2 + q**2 - r**2))) / (r**2 - p**2)
    cons12 = (p * q - r * (math.sqrt(p**2 + q**2 - r**2))) / (r**2 - p**2)
    cons21 = (a * b + r * (math.sqrt(a**2 + b**2 - r**2))) / (r**2 - a**2)
    cons22 = (a * b - r * (math.sqrt(a**2 + b**2 - r**2))) / (r**2 - a**2)

    x, y = symbols('x,y')
    a1 = -(cons11) * (x - x0 - p) + q + y0 - y
    a2 = -(cons12) * (x - x0 - p) + q + y0 - y
    b1 = -(cons21) * (x - x0 - a) + b + y0 - y
    b2 = -(cons22) * (x - x0 - a) + b + y0 - y

    ans1 = linsolve([a1, b1], (x, y))
    x1, y1 = next(iter(ans1))
    ans2 = linsolve([a1, b2], (x, y))
    x2, y2 = next(iter(ans2))
    ans3 = linsolve([a2, b1], (x, y))
    x3, y3 = next(iter(ans3))
    ans4 = linsolve([a2, b2], (x, y))
    x4, y4 = next(iter(ans4))

    d1 = distance(p, q, x1, y1)
    d2 = distance(p, q, x2, y2)
    d3 = distance(p, q, x3, y3)
    d4 = distance(p, q, x4, y4)

    if (d1 <= min(d2, d3, d4)):
        return x1, y1
    elif (d2 <= min(d1, d3, d4)):
        return x2, y2
    elif (d3 <= min(d2, d1, d4)):
        return x3, y3
    elif (d4 <= min(d2, d3, d1)):
        return x4, y4
Пример #26
0
def main():
    equations = get_equations(layout)
    symbols = set()
    for eqn in equations:
        symbols = symbols.union(eqn.atoms(Symbol))
    symbols = list(symbols)
    solved_equations = linsolve(equations, *symbols)
    if not solved_equations:
        raise OverconstrainedError("A solution could not be found.")
    solve = list(solved_equations)[0]
    print(list(zip(symbols, solve)))
Пример #27
0
    def calc(self):  # The function that calculates the expression of f(t)

        f = Function('f')
        t = symbols('t')

        #The lagrangian
        self.L = ode.kinetic(self) - ode.potential(self)
        print('the lagrangian is : ')
        display(self.L)

        ##The different placebos for the Lagrange equation##
        de = diff(self.L, Derivative(f(t), t))
        de = diff(de, t)
        dw = diff(self.L, f(t))

        da = 0.5 * self.alpha * (self.v**2)  #Dissipation function
        da = da.subs({sin(f(t)): f(t)})

        da = da.subs({cos(f(t)): 1 - (f(t))**2 / 2})

        da = diff(da, Derivative(f(t), t))
        eq = de - dw + da  #LAgrange Equation
        ##############----------##############

        ##Solving the equation##
        print('The equation is : ')
        eq = simplify(eq)
        display(eq)
        solution = dsolve(eq, f(t))
        print('The solution is : ')
        display(solution)
        #######----------#######

        #Initial conditions:
        cnd0 = Eq(solution.subs({t: 0}), self.x0)
        cnd1 = Eq(solution.diff(t).subs({t: 0}), self.xd0)
        display(cnd0)

        #Solve for C1 and C2:
        C1, C2 = symbols('C1 C2')  #Temporary symbols
        C1C2_sl = linsolve([cnd0, cnd1], (C1, C2))

        #Substitute into the Solution of the equation
        solution2 = simplify(solution.subs(C1C2_sl))
        if 'C1' in str(solution2):
            solution3 = solution2.subs({C1: 1})
        if 'C2' in str(solution2):
            solution3 = solution2.subs({C2: 2})
        print('The solution is :')
        display(solution3)  #The Solution
        return solution3
def show_prices(sequence:str, price_vars:list, budget_eqs:list, switches:list):
    switch_eqs = switch_equalities(switches, price_vars)
    prices_sol = linsolve(budget_eqs + switch_eqs, price_vars).args
    if len(prices_sol)==0:
        logger.debug("{}, {}: No prices!".format(sequence, switches))
        return
    prices = prices_sol[0]
    possible_budgets = budget_range(prices)
    if possible_budgets.is_EmptySet:
        logger.debug("{}, {}: {}, No budget!".format(sequence, switches, prices))
        return
    else:
        switches_str = ", ".join([str(s) for s in switches])
        logger.info("{}:      handles {}.     Requires a in {}".format("    ".join([str(p) for p in prices]), switches_str, possible_budgets))
Пример #29
0
    def _contains(self, other):
        from sympy.solvers.solveset import solveset, linsolve
        L = self.lamda
        if self._is_multivariate():
            solns = list(linsolve([expr - val for val, expr in zip(other, L.expr)],
                         L.variables).args[0])
        else:
            solns = list(solveset(L.expr - other, L.variables[0]))

        for soln in solns:
            try:
                if soln in self.base_set:
                    return S.true
            except TypeError:
                return self.base_set.contains(soln.evalf())
        return S.false
Пример #30
0
def collocations_method(basis, points):
    # unite basis functions to one
    func = build_function_from_basis(basis)
    # create from base func our psi func
    psi_func = func_for_substantiation(func)
    # generate variables for linsolve
    symbols = [sympy.Symbol('a' + str(i)) for i in range(len(points))]
    lin_system = []

    # substitude variables for linear system and simplify to linear with evalf
    for point in points:
        lin_system.append(psi_func.subs(x, point).evalf())

    # solving our system
    answer = linsolve(lin_system, *symbols)
    return answer
def onParabola(points):
    '''
    y = a*x**2 + b*x + c 
    '''
    quadratic_eq = a * x**2 + b * x + c - y

    linear_equations = []
    for (i, j) in points:
        linear_equations.append(quadratic_eq.subs({x: i, y: j}))

    try:
        ak, bk, ck = list(linsolve(linear_equations, (a, b, c)))[0]
    except IndexError:
        print('[!] Solution doesn\'t exist')
        return {()}
    return quadratic_eq.subs({a: ak, b: bk, c: ck, y: 0})
Пример #32
0
    def _contains(self, other):
        from sympy.solvers.solveset import solveset, linsolve
        L = self.lamda
        if self._is_multivariate():
            solns = list(linsolve([expr - val for val, expr in zip(other, L.expr)],
                         L.variables).args[0])
        else:
            solns = list(solveset(L.expr - other, L.variables[0]))

        for soln in solns:
            try:
                if soln in self.base_set:
                    return S.true
            except TypeError:
                return self.base_set.contains(soln.evalf())
        return S.false
Пример #33
0
def differences_method(start_variables_count,
                       a,
                       b,
                       y_a,
                       y_b,
                       func_for_partition,
                       points_k,
                       func=None):

    # generate variables for linsolve
    start_variables_count += 2
    symbols = [
        sympy.Symbol('y' + str(i)) for i in range(start_variables_count)
    ]
    # define our step
    h = (b - a) / start_variables_count
    # generate x points:
    points = linspace(a + h, b - h, start_variables_count - 2).tolist()
    # build system of equations
    lin_system = []
    selected_k = 0
    for i in range(1, start_variables_count - 1):
        if points[i - 1] > points_k[selected_k][0]:
            selected_k += 1

        lin_system.append(
            func_for_partition(symbols[i - 1], symbols[i], symbols[i + 1], h,
                               points_k[selected_k][1], func).evalf())
    for i in range(start_variables_count - 2):
        lin_system[i] = lin_system[i].subs(x, points[i])

    lin_system[0] = lin_system[0].subs(symbols[0], y_a)
    lin_system[-1] = lin_system[-1].subs(symbols[-1], y_b)

    del symbols[0], symbols[-1]

    # solving our system and converting FiniteSet to simple list
    answer = list(list(linsolve(lin_system, *symbols))[0])

    data_type = namedtuple('data', ('points', 'answer', 'step'))
    points.insert(0, a)
    points.append(b)

    answer.insert(0, y_a)
    answer.append(y_b)

    return data_type(points, answer, (b - a) / start_variables_count)
Пример #34
0
def galerkin_method(basis, a, b):
    # unite basis functions to one
    func = build_function_from_basis(basis)
    # create from base func our psi func
    psi_func = func_for_substantiation(func)
    # generate variables for linsolve
    symbols = [sympy.Symbol('a' + str(i)) for i in range(len(basis))]
    lin_system = []

    # getting our integral system and simplify equations to linear with evalf
    for i in range(len(basis)):
        lin_system.append(
            sympy.integrate(psi_func * basis[i], (x, a, b)).evalf())

    # solving our system
    answer = linsolve(lin_system, *symbols)
    return answer
Пример #35
0
    def __solve_equations(equations, m_symbols, p_symbols, s_symbols):
        all_symbols = list(p_symbols.values()) + list(
            s_symbols.values()) + list(m_symbols.values())
        raw_result = linsolve(equations, all_symbols)
        if not isinstance(raw_result, sympy.FiniteSet):
            raise ValueError()

        result = list(raw_result)[0]
        p_values = result[:len(p_symbols)]
        s_values = result[len(p_symbols):len(p_symbols) + len(s_symbols)]
        m_values = result[len(p_symbols) + len(s_symbols):len(p_symbols) +
                          len(s_symbols) + len(m_symbols)]

        p_result = dict(list(zip(p_symbols.keys(), p_values)))
        s_result = dict(list(zip(s_symbols.keys(), s_values)))
        m_result = dict(list(zip(m_symbols.keys(), m_values)))
        return p_result, s_result, m_result
Пример #36
0
def simpleDE(f, x, g, order=4):
    r"""Generates simple DE.

    DE is of the form

    .. math::
        f^k(x) + \sum\limits_{j=0}^{k-1} A_j f^j(x) = 0

    where :math:`A_j` should be rational function in x.

    Generates DE's upto order 4 (default). DE's can also have free parameters.

    By increasing order, higher order DE's can be found.

    Yields a tuple of (DE, order).
    """
    from sympy.solvers.solveset import linsolve

    a = symbols('a:%d' % (order))

    def _makeDE(k):
        eq = f.diff(x, k) + Add(*[a[i]*f.diff(x, i) for i in range(0, k)])
        DE = g(x).diff(x, k) + Add(*[a[i]*g(x).diff(x, i) for i in range(0, k)])
        return eq, DE

    eq, DE = _makeDE(order)

    found = False
    for k in range(1, order + 1):
        eq, DE = _makeDE(k)
        eq = eq.expand()
        terms = eq.as_ordered_terms()
        ind = rational_independent(terms, x)
        if found or len(ind) == k:
            sol = dict(zip(a, (i for s in linsolve(ind, a[:k]) for i in s)))
            if sol:
                found = True
                DE = DE.subs(sol)
            DE = DE.as_numer_denom()[0]
            DE = DE.factor().as_coeff_mul(Derivative)[1][0]
            yield DE.collect(Derivative(g(x))), k
Пример #37
0
def _transform_DE_RE(DE, g, k, order, syms):
    """Converts DE with free parameters into RE of hypergeometric type."""
    from sympy.solvers.solveset import linsolve

    RE = hyper_re(DE, g, k)

    eq = []
    for i in range(1, order):
        coeff = RE.coeff(g(k + i))
        eq.append(coeff)
    sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s)))
    if sol:
        m = Wild('m')
        RE = RE.subs(sol)
        RE = RE.factor().as_numer_denom()[0].collect(g(k + m))
        RE = RE.as_coeff_mul(g)[1][0]
        for i in range(order):  # smallest order should be g(k)
            if RE.coeff(g(k + i)) and i:
                RE = RE.subs(k, k - i)
                break
    return RE
Пример #38
0
 def _contains(self, other):
     from sympy.solvers.solveset import solveset, linsolve
     L = self.lamda
     if self._is_multivariate():
         solns = list(linsolve([expr - val for val, expr in
         zip(other, L.expr)], L.variables).args[0])
     else:
         solnsSet = solveset(L.expr-other, L.variables[0])
         if solnsSet.is_FiniteSet:
             solns = list(solveset(L.expr - other, L.variables[0]))
         else:
             raise NotImplementedError(filldedent('''
             Determining whether an ImageSet contains %s has not
             been implemented.''' % func_name(other)))
     for soln in solns:
         try:
             if soln in self.base_set:
                 return S.true
         except TypeError:
             return self.base_set.contains(soln.evalf())
     return S.false
    coeff = '1'
    Q,rest = str_term.split('*',1)
  else:
    coeff,Q,rest = str_term.split('*',2)
  if Q not in our_Qs:
    our_Qs[Q] = [coeff + "*" + rest]
  else:
    our_Qs[Q].append(coeff + "*" + rest)

for key,value in our_Qs.items():
  print("%s: %s" % (key,value))

variables = symbols(" ".join(list(our_Qs)))                # assumes our_Qs is an ordered dictionary, not a standard one.
print(variables)

result = linsolve(system_of_eqns,variables)
print("result:",result)

Q_values = OrderedDict()
for k,Q in enumerate(our_Qs):
  value = list(result)[0][k]
  print("%s: %s" % (Q,value))
  Q_values[Q] = value

sys.exit(0)


# bah this is ugly!!!
R_det = R.det()
#det_table = {}
det_table = OrderedDict()
Пример #40
0
def interpolating_spline(d, x, X, Y):
    """Return spline of degree ``d``, passing through the given ``X``
    and ``Y`` values.

    This function returns a piecewise function such that each part is
    a polynomial of degree not greater than ``d``. The value of ``d``
    must be 1 or greater and the values of ``X`` must be strictly
    increasing.

    Examples
    ========

    >>> from sympy import interpolating_spline
    >>> from sympy.abc import x
    >>> interpolating_spline(1, x, [1, 2, 4, 7], [3, 6, 5, 7])
    Piecewise((3*x, (x >= 1) & (x <= 2)),
            (7 - x/2, (x >= 2) & (x <= 4)),
            (2*x/3 + 7/3, (x >= 4) & (x <= 7)))
    >>> interpolating_spline(3, x, [-2, 0, 1, 3, 4], [4, 2, 1, 1, 3])
    Piecewise((-x**3/36 - x**2/36 - 17*x/18 + 2, (x >= -2) & (x <= 1)),
            (5*x**3/36 - 13*x**2/36 - 11*x/18 + 7/3, (x >= 1) & (x <= 4)))

    See Also
    ========

    bsplines_basis_set, sympy.polys.specialpolys.interpolating_poly
    """
    from sympy import symbols, Number, Dummy, Rational
    from sympy.solvers.solveset import linsolve
    from sympy.matrices.dense import Matrix

    # Input sanitization
    d = sympify(d)
    if not(d.is_Integer and d.is_positive):
        raise ValueError(
            "Spline degree must be a positive integer, not %s." % d)
    if len(X) != len(Y):
        raise ValueError(
            "Number of X and Y coordinates must be the same.")
    if len(X) < d + 1:
        raise ValueError(
            "Degree must be less than the number of control points.")
    if not all(a < b for a, b in zip(X, X[1:])):
        raise ValueError(
            "The x-coordinates must be strictly increasing.")

    # Evaluating knots value
    if d.is_odd:
        j = (d + 1) // 2
        interior_knots = X[j:-j]
    else:
        j = d // 2
        interior_knots = [Rational(a + b, 2) for a, b in
            zip(X[j:-j - 1], X[j + 1:-j])]

    knots = [X[0]] * (d + 1) + list(interior_knots) + [X[-1]] * (d + 1)

    basis = bspline_basis_set(d, knots, x)

    A = [[b.subs(x, v) for b in basis] for v in X]

    coeff = linsolve((Matrix(A), Matrix(Y)), symbols('c0:{}'.format(
        len(X)), cls=Dummy))
    coeff = list(coeff)[0]
    intervals = set([c for b in basis for (e, c) in b.args
        if c != True])

    # Sorting the intervals
    #  ival contains the end-points of each interval
    ival = [e.atoms(Number) for e in intervals]
    ival = [list(sorted(e))[0] for e in ival]
    com = zip(ival, intervals)
    com = sorted(com, key=lambda x: x[0])
    intervals = [y for x, y in com]

    basis_dicts = [dict((c, e) for (e, c) in b.args) for b in basis]
    spline = []
    for i in intervals:
        piece = sum([c*d.get(i, S.Zero) for (c, d) in
            zip(coeff, basis_dicts)], S.Zero)
        spline.append((piece, i))
    return(Piecewise(*spline))
Пример #41
0
def test_issue_9953():
    assert linsolve([ ], x) == S.EmptySet
Пример #42
0
    def intersection(self, o):
        """The intersection with another geometrical entity.

        Parameters
        ==========

        o : Point or LinearEntity3D

        Returns
        =======

        intersection : list of geometrical entities

        See Also
        ========

        sympy.geometry.point.Point3D

        Examples
        ========

        >>> from sympy import Point3D, Line3D, Segment3D
        >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(7, 7, 7)
        >>> l1 = Line3D(p1, p2)
        >>> l1.intersection(p3)
        [Point3D(7, 7, 7)]

        >>> l1 = Line3D(Point3D(4,19,12), Point3D(5,25,17))
        >>> l2 = Line3D(Point3D(-3, -15, -19), direction_ratio=[2,8,8])
        >>> l1.intersection(l2)
        [Point3D(1, 1, -3)]

        >>> p6, p7 = Point3D(0, 5, 2), Point3D(2, 6, 3)
        >>> s1 = Segment3D(p6, p7)
        >>> l1.intersection(s1)
        []

        """
        if isinstance(o, Point3D):
            if o in self:
                return [o]
            else:
                return []

        elif isinstance(o, LinearEntity3D):
            if self == o:
                return [self]
            elif self.is_parallel(o):
                if isinstance(self, Line3D):
                    if o.p1 in self:
                        return [o]
                    return []
                elif isinstance(self, Ray3D):
                    if isinstance(o, Ray3D):
                        # case 1, rays in the same direction
                        if self.xdirection == o.xdirection and \
                                self.ydirection == o.ydirection and \
                                self.zdirection == o.zdirection:
                            return [self] if (self.source in o) else [o]
                        # case 2, rays in the opposite directions
                        else:
                            if o.source in self:
                                if self.source == o.source:
                                    return [self.source]
                                return [Segment3D(o.source, self.source)]
                            return []
                    elif isinstance(o, Segment3D):
                        if o.p1 in self:
                            if o.p2 in self:
                                return [o]
                            return [Segment3D(o.p1, self.source)]
                        elif o.p2 in self:
                            return [Segment3D(o.p2, self.source)]
                        return []
                elif isinstance(self, Segment3D):
                    if isinstance(o, Segment3D):
                        # A reminder that the points of Segments are ordered
                        # in such a way that the following works. See
                        # Segment3D.__new__ for details on the ordering.
                        if self.p1 not in o:
                            if self.p2 not in o:
                                # Neither of the endpoints are in o so either
                                # o is contained in this segment or it isn't
                                if o in self:
                                    return [o]
                                return []
                            else:
                                # p1 not in o but p2 is. Either there is a
                                # segment as an intersection, or they only
                                # intersect at an endpoint
                                if self.p2 == o.p1:
                                    return [o.p1]
                                return [Segment3D(o.p1, self.p2)]
                        elif self.p2 not in o:
                            # p2 not in o but p1 is. Either there is a
                            # segment as an intersection, or they only
                            # intersect at an endpoint
                            if self.p1 == o.p2:
                                return [o.p2]
                            return [Segment3D(o.p2, self.p1)]

                        # Both points of self in o so the whole segment
                        # is in o
                        return [self]

                else:  # unrecognized LinearEntity
                    raise NotImplementedError

            else:
                # If the lines are not parallel then solve their arbitrary points
                # to obtain the point of intersection
                t = t1, t2 = Dummy(), Dummy()
                a = self.arbitrary_point(t1)
                b = o.arbitrary_point(t2)
                dx = a.x - b.x
                c = linsolve([dx, a.y - b.y], t).args[0]
                d = linsolve([dx, a.z - b.z], t).args[0]
                if len(c.free_symbols) == 1 and len(d.free_symbols) == 1:
                    return []
                e = a.subs(t1, c[0])
                if e in self and e in o:
                    return [e]
                else:
                    return []

        return o.intersection(self)
Пример #43
0
def test_linsolve():
    x, y, z, u, v, w = symbols("x, y, z, u, v, w")
    x1, x2, x3, x4 = symbols("x1, x2, x3, x4")

    # Test for different input forms

    M = Matrix([[1, 2, 1, 1, 7], [1, 2, 2, -1, 12], [2, 4, 0, 6, 4]])
    system1 = A, b = M[:, :-1], M[:, -1]
    Eqns = [x1 + 2 * x2 + x3 + x4 - 7, x1 + 2 * x2 + 2 * x3 - x4 - 12, 2 * x1 + 4 * x2 + 6 * x4 - 4]

    sol = FiniteSet((-2 * x2 - 3 * x4 + 2, x2, 2 * x4 + 5, x4))
    assert linsolve(M, (x1, x2, x3, x4)) == sol
    assert linsolve(Eqns, (x1, x2, x3, x4)) == sol
    assert linsolve(system1, (x1, x2, x3, x4)) == sol

    # raise ValueError if no symbols are given
    raises(ValueError, lambda: linsolve(system1))

    # raise ValueError if, A & b is not given as tuple
    raises(ValueError, lambda: linsolve(A, b, x1, x2, x3, x4))

    # raise ValueError for garbage value
    raises(ValueError, lambda: linsolve(Eqns[0], x1, x2, x3, x4))

    # Fully symbolic test
    a, b, c, d, e, f = symbols("a, b, c, d, e, f")
    A = Matrix([[a, b], [c, d]])
    B = Matrix([[e], [f]])
    system2 = (A, B)
    sol = FiniteSet(((-b * f + d * e) / (a * d - b * c), (a * f - c * e) / (a * d - b * c)))
    assert linsolve(system2, [x, y]) == sol

    # Test for Dummy Symbols issue #9667
    x1 = Dummy("x1")
    x2 = Dummy("x2")
    x3 = Dummy("x3")
    x4 = Dummy("x4")

    assert linsolve(system1, x1, x2, x3, x4) == FiniteSet((-2 * x2 - 3 * x4 + 2, x2, 2 * x4 + 5, x4))

    # No solution
    A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
    b = Matrix([0, 0, 1])
    assert linsolve((A, b), (x, y, z)) == EmptySet()

    # Issue #10056
    A, B, J1, J2 = symbols("A B J1 J2")
    Augmatrix = Matrix(
        [[2 * I * J1, 2 * I * J2, -2 / J1], [-2 * I * J2, -2 * I * J1, 2 / J2], [0, 2, 2 * I / (J1 * J2)], [2, 0, 0]]
    )

    assert linsolve(Augmatrix, A, B) == FiniteSet((0, I / (J1 * J2)))

    # Issue #10121 - Assignment of free variables
    a, b, c, d, e = symbols("a, b, c, d, e")
    Augmatrix = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]])
    assert linsolve(Augmatrix, a, b, c, d, e) == FiniteSet((a, 0, c, 0, e))
Пример #44
0
    def _contains(self, other):
        from sympy.matrices import Matrix
        from sympy.solvers.solveset import solveset, linsolve
        from sympy.utilities.iterables import is_sequence, iterable, cartes
        L = self.lamda
        if is_sequence(other):
            if not is_sequence(L.expr):
                return S.false
            if len(L.expr) != len(other):
                raise ValueError(filldedent('''
    Dimensions of other and output of Lambda are different.'''))
        elif iterable(other):
                raise ValueError(filldedent('''
    `other` should be an ordered object like a Tuple.'''))

        solns = None
        if self._is_multivariate():
            if not is_sequence(L.expr):
                # exprs -> (numer, denom) and check again
                # XXX this is a bad idea -- make the user
                # remap self to desired form
                return other.as_numer_denom() in self.func(
                    Lambda(L.variables, L.expr.as_numer_denom()), self.base_set)
            eqs = [expr - val for val, expr in zip(other, L.expr)]
            variables = L.variables
            free = set(variables)
            if all(i.is_number for i in list(Matrix(eqs).jacobian(variables))):
                solns = list(linsolve([e - val for e, val in
                zip(L.expr, other)], variables))
            else:
                syms = [e.free_symbols & free for e in eqs]
                solns = {}
                for i, (e, s, v) in enumerate(zip(eqs, syms, other)):
                    if not s:
                        if e != v:
                            return S.false
                        solns[vars[i]] = [v]
                        continue
                    elif len(s) == 1:
                        sy = s.pop()
                        sol = solveset(e, sy)
                        if sol is S.EmptySet:
                            return S.false
                        elif isinstance(sol, FiniteSet):
                            solns[sy] = list(sol)
                        else:
                            raise NotImplementedError
                    else:
                        raise NotImplementedError
                solns = cartes(*[solns[s] for s in variables])
        else:
            x = L.variables[0]
            if isinstance(L.expr, Expr):
                # scalar -> scalar mapping
                solnsSet = solveset(L.expr - other, x)
                if solnsSet.is_FiniteSet:
                    solns = list(solnsSet)
                else:
                    msgset = solnsSet
            else:
                # scalar -> vector
                for e, o in zip(L.expr, other):
                    solns = solveset(e - o, x)
                    if solns is S.EmptySet:
                        return S.false
                    for soln in solns:
                        try:
                            if soln in self.base_set:
                                break  # check next pair
                        except TypeError:
                            if self.base_set.contains(soln.evalf()):
                                break
                    else:
                        return S.false  # never broke so there was no True
                return S.true

        if solns is None:
            raise NotImplementedError(filldedent('''
            Determining whether %s contains %s has not
            been implemented.''' % (msgset, other)))
        for soln in solns:
            try:
                if soln in self.base_set:
                    return S.true
            except TypeError:
                return self.base_set.contains(soln.evalf())
        return S.false