def __init__(self): h, g, h0, g0, a, d = sympy.symbols('h g h0 g0 a d') #g1 = sympy.Max(-d, g0 + h0 - 1/(4*a)) g1 = g0 + h0 - 1/(4*a) h1 = h0 - 1/(2*a) parabola = d - a*h*h # =g on boundary slope = g1 + h - h1 # =g on line with slope=1 through z1 h2 = sympy.solve(parabola-slope,h)[0] # First solution is above z1 g2 = h2 - h1 + g1 # Line has slope of 1 g3 = g1 h3 = sympy.solve((parabola-g).subs(g, g1),h)[1] # Second is on right r_a = sympy.Rational(1,24) # a=1/24 always self.h = tuple(x.subs(a,r_a) for x in (h0, h1, h2, h3)) self.g = tuple(x.subs(a,r_a) for x in (g0, g1, g2, g3)) def integrate(f): ia = sympy.integrate( sympy.integrate(f,(g, g1, g1+h-h1)), (h, h1, h2)) # Integral of f over right triangle ib = sympy.integrate( sympy.integrate(f,(g, g1, parabola)), (h, h2, h3)) # Integral of f over region against parabola return (ia+ib).subs(a, r_a) i0 = integrate(1) # Area = integral of pie slice E = lambda f:(integrate(f)/i0) # Expected value wrt Lebesgue measure sigma = lambda f,g:E(f*g) - E(f)*E(g) self.d = d self.Eh = collect(E(h),sympy.sqrt(d-g0-h0+6)) self.Eg = E(g) self.Sigmahh = sigma(h,h) self.Sigmahg = sigma(h,g) self.Sigmagg = sigma(g,g) return
def test_issue_1572_1364_1368(): assert solve((sqrt(x**2 - 1) - 2)) in ([sqrt(5), -sqrt(5)], [-sqrt(5), sqrt(5)]) assert set(solve((2**exp(y**2/x) + 2)/(x**2 + 15), y)) == set([ -sqrt(x)*sqrt(-log(log(2)) + log(log(2) + I*pi)), sqrt(x)*sqrt(-log(log(2)) + log(log(2) + I*pi))]) C1, C2 = symbols('C1 C2') f = Function('f') assert solve(C1 + C2/x**2 - exp(-f(x)), f(x)) == [log(x**2/(C1*x**2 + C2))] a = Symbol('a') E = S.Exp1 assert solve(1 - log(a + 4*x**2), x) in ( [-sqrt(-a + E)/2, sqrt(-a + E)/2], [sqrt(-a + E)/2, -sqrt(-a + E)/2] ) assert solve(log(a**(-3) - x**2)/a, x) in ( [-sqrt(-1 + a**(-3)), sqrt(-1 + a**(-3))], [sqrt(-1 + a**(-3)), -sqrt(-1 + a**(-3))],) assert solve(1 - log(a + 4*x**2), x) in ( [-sqrt(-a + E)/2, sqrt(-a + E)/2], [sqrt(-a + E)/2, -sqrt(-a + E)/2],) assert set(solve(( a**2 + 1) * (sin(a*x) + cos(a*x)), x)) == set([-pi/(4*a), 3*pi/(4*a)]) assert solve(3 - (sinh(a*x) + cosh(a*x)), x) == [2*atanh(S.Half)/a] assert set(solve(3 - (sinh(a*x) + cosh(a*x)**2), x)) == \ set([ 2*atanh(-1 + sqrt(2))/a, 2*atanh(S(1)/2 + sqrt(5)/2)/a, 2*atanh(-sqrt(2) - 1)/a, 2*atanh(-sqrt(5)/2 + S(1)/2)/a ]) assert solve(atan(x) - 1) == [tan(1)]
def qExponentialSameBase_template(): '''Solves the same base e.g. 2^(2x+1) = 32.''' base = choice([2,3,5,7]) pow_rs = randint(3,6) rs = int(pow(base,pow_rs)) front_num = randint(-100,100) while front_num == 0: front_num = randint(-100,100) lspow = front_num*x+randint(-100,100) question = 'Solve ' + tostring(am.parse('%s^(%s) = %s' % (base, lspow, rs))) ls_samebase = tostring(am.parse('%s^(%s)' % (base, lspow))) rs_samebase = tostring(am.parse('%s^(%s)' % (base, pow_rs))) steps = [] steps.append('Covert right side to be same base as left side. Left side' \ ' has a base of: ' + str(base)) steps.append('As ' + tostring(am.parse('%s^(%s)=%s' % (base, pow_rs, rs)))) steps.append('Right side is now: ' + tostring(am.parse('%s^(%s)' % (base, pow_rs)))) steps.append('Therefore ' + ls_samebase + tostring(am.parse('=')) + \ rs_samebase) steps.append('Therefore solve: ' + tostring(am.parse('%s%s%s' % (lspow,'=',pow_rs)))) steps.append('Note: As bases are same the power equates to each other.') answer = [] answer.append(steps) if len(solve(Eq(lspow, rs))) > 1: answer.append(tostring(am.parse('x = %s' % solve(Eq(lspow, rs))[0]))) else: answer.append(tostring(am.parse('x = %s' % solve(Eq(lspow, rs))[0]))) return question, answer
def test_solve_inequalities(): system = [Lt(x ** 2 - 2, 0), Gt(x ** 2 - 1, 0)] assert solve(system) == And( Or(And(Lt(-sqrt(2), re(x)), Lt(re(x), -1)), And(Lt(1, re(x)), Lt(re(x), sqrt(2)))), Eq(im(x), 0) ) assert solve(system, assume=Q.real(x)) == Or(And(Lt(-sqrt(2), x), Lt(x, -1)), And(Lt(1, x), Lt(x, sqrt(2))))
def test_RootOf___eval_Eq__(): f = Function('f') r = RootOf(x**3 + x + 3, 2) r1 = RootOf(x**3 + x + 3, 1) assert Eq(r, r1) is S.false assert Eq(r, r) is S.true assert Eq(r, x) is S.false assert Eq(r, 0) is S.false assert Eq(r, S.Infinity) is S.false assert Eq(r, I) is S.false assert Eq(r, f(0)) is S.false assert Eq(r, f(0)) is S.false sol = solve(r.expr) for s in sol: if s.is_real: assert Eq(r, s) is S.false r = RootOf(r.expr, 0) for s in sol: if s.is_real: assert Eq(r, s) is S.true eq = (x**3 + x + 1) assert [Eq(RootOf(eq, i), j) for i in range(3) for j in solve(eq)] == [ False, False, True, False, True, False, True, False, False ] assert Eq(RootOf(eq, 0), 1 + S.ImaginaryUnit) == False
def test_CRootOf___eval_Eq__(): f = Function('f') eq = x**3 + x + 3 r = rootof(eq, 2) r1 = rootof(eq, 1) assert Eq(r, r1) is S.false assert Eq(r, r) is S.true assert Eq(r, x) is S.false assert Eq(r, 0) is S.false assert Eq(r, S.Infinity) is S.false assert Eq(r, I) is S.false assert Eq(r, f(0)) is S.false assert Eq(r, f(0)) is S.false sol = solve(eq) for s in sol: if s.is_real: assert Eq(r, s) is S.false r = rootof(eq, 0) for s in sol: if s.is_real: assert Eq(r, s) is S.true eq = x**3 + x + 1 sol = solve(eq) assert [Eq(rootof(eq, i), j) for i in range(3) for j in sol] == [ False, False, True, False, True, False, True, False, False] assert Eq(rootof(eq, 0), 1 + S.ImaginaryUnit) == False
def test_issue_2813(): assert solve(x ** 2 - x - 0.1, rational=True) == [S(1) / 2 + sqrt(35) / 10, -sqrt(35) / 10 + S(1) / 2] # [-0.0916079783099616, 1.09160797830996] ans = solve(x ** 2 - x - 0.1, rational=False) assert len(ans) == 2 and all(a.is_Number for a in ans) ans = solve(x ** 2 - x - 0.1) assert len(ans) == 2 and all(a.is_Number for a in ans)
def SequentialSolving(eqns): sorteq = SortEquations(eqns) seqsol = {} unkn = sorted(sorteq[0].atoms(sy.Symbol)) num_unkn = len(unkn) while num_unkn == 1 and not sorteq == []: val_unkn = sy.solve(sorteq[0], unkn[0], simplify = False) seqsol[unkn[0]] = sy.Rational(str(round(val_unkn[0], 4))) unkn = sorted(sorteq[0].atoms(sy.Symbol)) num_unkn = len(unkn) while num_unkn == 1: val_unkn = sy.solve(sorteq[0], unkn[0]) seqsol[unkn[0]] = val_unkn[0] i = 0 for eq in sorteq: if unkn[0] in sorteq[i]: val_unkn[0] = round(val_unkn[0], 5) repl = eq.subs(unkn[0], sy.Rational(str(val_unkn[0]))) if not isinstance(repl, sy.Float): sorteq[i] = repl else: sorteq[i] = repl i+=1 sorteq = RemoveZeros(sorteq) if sorteq == []: num_unkn = 0 else: sorteq = SortEquations(sorteq) unkn = sorted(sorteq[0].atoms(sy.Symbol)) num_unkn = len(unkn) return seqsol
def print_assignment(eq, s, s0=0, pochoir=False): s1 = print_myccode(s, None, pochoir) if(s0==0): s2 = print_myccode(simplify(solve(eq,s)[0]), None, pochoir) else: s2 = print_myccode(simplify(solve(eq,s)[0] - s0) + s0, None, pochoir) return s1 + '=' + s2
def test_polysys(): assert set(solve([x**2 + 2/y - 2 , x + y - 3], [x, y])) == \ set([(S(1), S(2)), (1 + sqrt(5), 2 - sqrt(5)), (1 - sqrt(5), 2 + sqrt(5))]) assert solve([x**2 + y - 2, x**2 + y]) == [] # the ordering should be whatever the user requested assert solve([x**2 + y - 3, x - y - 4], (x, y)) != solve([x**2 + y - 3, x - y - 4], (y, x))
def solve_eq(rho_m, u_m, u_s): u_max, u_star, rho_max, rho_star, A, B = sympy.symbols("u_max u_star rho_max rho_star A B") eq1 = sympy.Eq(0, u_max * rho_max * (1 - A * rho_max - B * rho_max ** 2)) eq2 = sympy.Eq(0, u_max * (1 - 2 * A * rho_star - 3 * B * rho_star ** 2)) eq3 = sympy.Eq(u_star, u_max * (1 - A * rho_star - B * rho_star ** 2)) eq4 = sympy.Eq(eq2.lhs - 3 * eq3.lhs, eq2.rhs - 3 * eq3.rhs) eq4.simplify() eq4.expand() rho_sol = sympy.solve(eq4, rho_star)[0] B_sol = sympy.solve(eq1, B)[0] quadA = eq2.subs([(rho_star, rho_sol), (B, B_sol)]) quadA.simplify() A_sol = sympy.solve(quadA, A)[0] aval = A_sol.evalf(subs={u_star: u_s, u_max: u_m, rho_max: rho_m}) bval = B_sol.evalf(subs={rho_max: rho_m, A: aval}) rho_sol = sympy.solve(eq2, rho_star)[0] rho_val = rho_sol.evalf(subs={u_max: u_m, A: aval, B: bval}) return aval, bval, rho_val
def test_polysys(): from sympy.abc import x, y assert solve([x**2 + 2/y - 2 , x + y - 3], [x, y]) == \ [(1, 2), (1 + sqrt(5), 2 - sqrt(5)), (1 - sqrt(5), 2 + sqrt(5))] assert solve([x**2 + y - 2, x**2 + y]) is None # the ordering should be whatever the user requested assert solve([x**2 + y - 3, x - y - 4], (x, y)) != solve([x**2 + y - 3, x - y - 4], (y, x))
def main(argv): u_max, u_star, rho_max, rho_star, A, B = sympy.symbols('u_max u_star rho_max rho_star A B') eq1 = sympy.Eq( 0, u_max * rho_max * (1 - A * rho_max - B * rho_max ** 2) ) eq2 = sympy.Eq( 0, u_max * (1 - 2 * A * rho_star - 3 * B * rho_star ** 2) ) eq3 = sympy.Eq( u_star, u_max * (1 - A * rho_star - B * rho_star ** 2) ) eq4 = sympy.Eq( eq2.lhs - 3 * eq3.lhs, eq2.rhs - 3 * eq3.rhs ) eq4.simplify() eq4.expand() rho_sol = sympy.solve(eq4, rho_star)[0] B_sol = sympy.solve(eq1, B)[0] quadA = eq2.subs([(rho_star, rho_sol), (B, B_sol)]) quadA.simplify() A_sol = sympy.solve(quadA, A)[0] aval = A_sol.evalf(subs = {u_star: 1.5, u_max: 2.0, rho_max: 15.0} ) bval = B_sol.evalf(subs = {rho_max: 15.0, A: aval} ) rho_sol = sympy.solve(eq2, rho_star)[0] rho_val = rho_sol.evalf(subs = {u_max: 2.0, A: aval, B: bval} ) print print ' A: %10.5f' % aval print ' B: %10.5f' % bval print 'rho_max: %10.5f' % rho_val print
def test_swap_back(): f, g = map(Function, 'fg') fx, gx = f(x), g(x) assert solve([fx + y - 2, fx - gx - 5], fx, y, gx) == \ {fx: gx + 5, y: -gx - 3} assert solve(fx + gx*x - 2, [fx, gx]) == {fx: 2, gx: 0} assert solve(fx + gx**2*x - y, [fx, gx]) == [{fx: y - gx**2*x}]
def test_checking(): assert set(solve(x*(x - y/x),x, check=False)) == set([sqrt(y), S(0), -sqrt(y)]) assert set(solve(x*(x - y/x),x, check=True)) == set([sqrt(y), -sqrt(y)]) # {x: 0, y: 4} sets denominator to 0 in the following so system should return None assert solve((1/(1/x + 2), 1/(y - 3) - 1)) is None # 0 sets denominator of 1/x to zero so [] is returned assert solve(1/(1/x + 2)) == []
def test_exclude(): R, C, Ri, Vout, V1, Vminus, Vplus, s = \ symbols('R, C, Ri, Vout, V1, Vminus, Vplus, s') Rf = symbols('Rf', positive=True) # to eliminate Rf = 0 soln eqs = [C*V1*s + Vplus*(-2*C*s - 1/R), Vminus*(-1/Ri - 1/Rf) + Vout/Rf, C*Vplus*s + V1*(-C*s - 1/R) + Vout/R, -Vminus + Vplus] assert solve(eqs, exclude=s*C*R) == [ { Rf: Ri*(C*R*s + 1)**2/(C*R*s), Vminus: Vplus, V1: Vplus*(2*C*R*s + 1)/(C*R*s), Vout: Vplus*(C**2*R**2*s**2 + 3*C*R*s + 1)/(C*R*s)}, { Vplus: 0, Vminus: 0, V1: 0, Vout: 0}, ] assert solve(eqs, exclude=[Vplus, s, C]) == [ { Rf: Ri*(V1 - Vplus)**2/(Vplus*(V1 - 2*Vplus)), Vminus: Vplus, Vout: (V1**2 - V1*Vplus - Vplus**2)/(V1 - 2*Vplus), R: Vplus/(C*s*(V1 - 2*Vplus))}]
def __init__(self, width, height, x_radius=None, curve=CIRCULAR): self.width = width self.height = height self.x_radius = x_radius self.curve = curve self.x, self.y, dx, dy = sympy.symbols("x y dx dy", real=True) a, b = sympy.symbols("a b", positive=True, real=True) self.ellipse = ((self.x - dx) / a) ** 2 + ((self.y - dy) / b) ** 2 - 1 self.ellipse = self.ellipse.subs([(dx, self.width), (dy, b)]) if curve == Transition.CIRCULAR: self.ellipse = self.ellipse.subs([(a, b)]) ellipse = self.ellipse.subs([(self.x, 0), (self.y, self.height)]) if curve == Transition.CIRCULAR: self.x_radius = self.y_radius = max(sympy.solve(ellipse, b)) self.angle = math.asin(self.width / self.x_radius) self.arc_length = self.x_radius * self.angle elif curve == Transition.ELLIPTICAL: self.y_radius = max(sympy.solve(ellipse, b)) # TODO: Fix me self.angle = 0 self.arc_length = 0 self.ellipse = self.ellipse.subs([(a, self.x_radius), (b, self.y_radius)])
def __init__(self): self._qp = {} function_type = random.choice([sympy.sin, sympy.cos, 'linear', 'quadratic']) if function_type in [sympy.sin, sympy.cos]: while True: self._qp['domain'] = domains.integer_domain(low=0, high=2, minimum_distance=1) m = random.choice([sympy.pi / 2, sympy.pi]) self._qp['equation'] = k * function_type(m * x) area = self._qp['equation'].integrate((x, self._qp['domain'].left, self._qp['domain'].right)) solution = sympy.solve(area - 1) if len(solution) == 0: continue self._qp['k'] = solution[0] break elif function_type == 'linear': self._qp['domain'] = domains.integer_domain() m = random.randint(1, 2) a = random.randint(7, 12) self._qp['equation'] = ((m * x + k) / a).together() area = self._qp['equation'].integrate((x, self._qp['domain'].left, self._qp['domain'].right)) self._qp['k'] = sympy.solve(area - 1)[0] elif function_type == 'quadratic': self._qp['domain'] = domains.integer_domain() self._qp['equation'] = k * (x - self._qp['domain'].left) * (x - self._qp['domain'].right) area = self._qp['equation'].integrate((x, self._qp['domain'].left, self._qp['domain'].right)) self._qp['k'] = sympy.solve(area - 1)[0]
def main(): u_max, u_star, rho_max, rho_star, A, B, rho = sympy.symbols('u_max u_star rho_max rho_star A B rho') eq1 = sympy.Eq( 0, u_max*rho_max*(1 - A*rho_max-B*rho_max**2) ) eq2 = sympy.Eq( 0, u_max*(1 - 2*A*rho_star-3*B*rho_star**2) ) eq3 = sympy.Eq( u_star, u_max*(1 - A*rho_star - B*rho_star**2) ) eq4 = sympy.Eq(eq2.lhs - 3*eq3.lhs, eq2.rhs - 3*eq3.rhs) eq4.simplify() rho_sol = sympy.solve(eq4,rho_star)[0] B_sol = sympy.solve(eq1,B)[0] quadA = eq2.subs([(rho_star, rho_sol), (B,B_sol)]) quadA.simplify() A_sol = sympy.solve(quadA, A) #print A_sol[0] #print A_sol[1] aval = A_sol[0].evalf(subs={u_star: 1.5, u_max:2.0, rho_max:15.0} ) bval = B_sol.evalf(subs={rho_max:15.0, A:aval} ) print aval #print A_sol[1].evalf(subs={u_star: 0.7, u_max:1.0, rho_max:10.0} ) print bval eq5 = sympy.Eq( 0, u_max*(1 - 2*aval*rho-3*bval*rho**2) ) rho_min = sympy.solve(eq5, rho) print 'rho_min= ', rho_min
def test_minsolve_linear_system(): def count(dic): return len([x for x in dic.itervalues() if x == 0]) assert count(solve([x + y + z, y + z + a + t], minimal=True, quick=True)) == 3 assert count(solve([x + y + z, y + z + a + t], minimal=True, quick=False)) == 3 assert count(solve([x + y + z, y + z + a], minimal=True, quick=True)) == 1 assert count(solve([x + y + z, y + z + a], minimal=True, quick=False)) == 2
def benefit_from_demand(x, p, demand): """Converts the demand curve to the benefit. It assumes that the demand is a x=d(p) function, where the x= is implicit. >>> sp.var('x p') (x, p) >>> sp.simplify(benefit_from_demand(x, p, 10/p -1) - ... 10*sp.log(x+1)) 0 >>> sp.simplify(benefit_from_demand(x, p, sp.Eq(x, 10/p -1)) - ... 10*sp.log(x+1)) 0 >>> sp.simplify(benefit_from_demand(x, p, 100-p) - ... (-x**2/2 + 100*x)) 0 >>> benefit_from_demand(x, p, sp.Piecewise((0, p < 0), ... (-p + 100, p <= 100), ... (0, True))) -x**2/2 + 100*x """ if isinstance(demand, sp.relational.Relational): return sp.integrate(sp.solve(demand, p)[0], (x, 0, x)) substracting = sp.solve(demand-x, p) if substracting: toint = substracting[0] else: substracting = sp.solve(demand, p) if substracting: toint = substracting[0] - x else: return None return sp.integrate(toint, (x, 0, x))
def PlotFor2Param(k1, k2, x, y, yVal, eq1, eq2, eqDet, eqTr, valK1m, valK3m, valK2 = 0.95, valK3 = 0.0032): eqk1_1Det = solve(eqDet.subs(x, eq2), k1) eqForK1Det = eq1 - eqk1_1Det[0] eqK2Det = solve(eqForK1Det.subs(km1, valK1m).subs(km3, valK3m).subs(k3, valK3), k2) funcK2Det = lambdify(y, eqK2Det[0]) funcK1Det = lambdify(y, eqk1_1Det[0].subs(x, eq2).subs(k2, eqK2Det[0]).subs(km1, valK1m).subs(km3, valK3m).subs(k3, valK3)) k1DetAll = funcK1Det(yVal) k2DetAll = funcK2Det(yVal) k1DetPos = [k1DetAll[i] for i in range(len(k1DetAll)) if k1DetAll[i] > 0 and k2DetAll[i] > 0] k2DetPos = [k2DetAll[i] for i in range(len(k2DetAll)) if k1DetAll[i] > 0 and k2DetAll[i] > 0] hopf, = plt.plot(k1DetPos, k2DetPos, linestyle = '--', color = 'r', label = 'hopf line') eqk1_1Tr = solve(eqTr.subs(x, eq2), k1) eqForK1Tr = eq1 - eqk1_1Tr[0] eqK2Tr = solve(eqForK1Tr.subs(km1, valK1m).subs(km3, valK3m).subs(k3, valK3), k2) funcK2Tr = lambdify(y, eqK2Tr[0]) funcK1Tr = lambdify(y, eq1.subs(x, eq2).subs(k2, eqK2Tr[0]).subs(km1, valK1m).subs(km3, valK3m).subs(k3, valK3)) k1AllTr = funcK1Tr(yVal) k2AllTr = funcK2Tr(yVal) k1PosTr = [k1AllTr[i] for i in range(len(k1AllTr)) if k1AllTr[i] > 0 and k2AllTr[i] > 0] print(len(k1PosTr)) k2PosTr = [k2AllTr[i] for i in range(len(k2AllTr)) if k1AllTr[i] > 0 and k2AllTr[i] > 0] print(len(k2PosTr)) sadle, = plt.plot(k1PosTr, k2PosTr, color = 'g', label = 'sadle-nodle line') plt.xlim([0, 2]) plt.ylim([0,5]) plt.legend(handles=[hopf, sadle]) plt.xlabel('k1') plt.ylabel('k2') plt.show()
def getfunc(p1, p2, p3, p4): """ Get a point-returning function for a cubic curve over four points, with domain [0 - 3]. """ # knowns points = p1, p2, p3, p4 # unknowns a, b, c, d, e, f, g, h = [Symbol(n) for n in 'abcdefgh'] # coefficients xco = solve([(a * i**3 + b * i**2 + c * i + d - p.x) for (i, p) in enumerate(points)], [a, b, c, d]) yco = solve([(e * i**3 + f * i**2 + g * i + h - p.y) for (i, p) in enumerate(points)], [e, f, g, h]) # shorter variable names a, b, c, d = [xco[n] for n in (a, b, c, d)] e, f, g, h = [yco[n] for n in (e, f, g, h)] def func(t, d1=False): """ Return a position for given t or velocity (1st derivative) if arg. is True. """ if d1: # first derivative return Point(3 * a * t**2 + 2 * b * t + c, 3 * e * t**2 + 2 * f * t + g) else: # actual function return Point(a * t**3 + b * t**2 + c * t + d, e * t**3 + f * t**2 + g * t + h) return func
def generate_x(self, N=1000): ''' this sampling method works wit all margins, but only frank and independent copulas can be used and it is limited to 2 dimensions ''' # compute marginal prob of u1 P_U1 = sy.simplify(sy.diff(self.C,self.U[0])) # invert marginal prob of u1 y = sy.symbols('y') tmp = sy.solve(sy.Eq(P_U1,y),self.U[1]) inv_P_U1 = sy.lambdify((self.U[0],y,self.D),tmp,'numpy') # invert margins inv_F = {} for m in [0,1]: u = sy.symbols('u') tmp = sy.solve(sy.Eq(self.F[m],u),self.X[m])[0] inv_F[m] = sy.lambdify((u,self.P[m]),tmp,'numpy') X = np.zeros((N,2)) for i in range(N): u0, y = np.random.uniform(size=2) u1 = inv_P_U1(u0,y,self.C_para) X[i,0] = inv_F[0](u0,self.F_para[0]) X[i,1] = inv_F[1](u1,self.F_para[1]) return X
def test_issue_3506(): x = symbols('x') assert solve(4**(x/2) - 2**(x/3)) == [0] # while the first one passed, this one failed x = symbols('x', real=True) assert solve(5**(x/2) - 2**(x/3)) == [0] b = sqrt(6)*sqrt(log(2))/sqrt(log(5)) assert solve(5**(x/2) - 2**(3/x)) == [-b, b]
def test_swap_back(): f, g = map(Function, 'fg') x, y = symbols('x,y') a, b = f(x), g(x) assert solve([a + y - 2, a - b - 5], a, y, b) == \ {a: b + 5, y: -b - 3} assert solve(a + b*x - 2, [a, b]) == {a: 2, b: 0} assert solve(a + b**2*x - y, [a, b]) == [{a: y - b**2*x}]
def maximal_domain(expr, domain=sympy.Interval(-oo, oo)): """ Return the maximal domain of an expression. >>> maximal_domain(sympy.log(x**2 - 1)) (-oo, -1) U (1, oo) >>> maximal_domain(1 / (x**2 - 4)) (-oo, -2) U (-2, 2) U (2, oo) >>> maximal_domain((x - 2) ** (sympy.Rational(3, 2))) (2, oo) """ # 4 possible scenarios: # 1. 1/(a) -- a != 0 # 2. sqrt(b) -- b > 0 # 3. log(c) -- c > 0 # 4. tan(d) -- d != the solutions of tan for symbol in expr.free_symbols: if symbol == x: expr = expr.replace(x, sympy.Symbol("x", real=True)) else: raise NotImplementedError("only x is currently supported - but that can be easily changed") powers = expr.find(sympy.Pow) # case 1 for power in powers: if power.args[1] < 0: denominator = power.args[0] solution = sympy.solve(denominator) domain &= -sympy.FiniteSet(solution) # case 2 if isinstance(power.args[1], sympy.Rational): if power.args[1].q % 2 != 0: continue sqrt_interior = power.args[0] solution = sympy.solve(sqrt_interior > 0) domain &= relation_to_interval(solution) # case 3 logs = expr.find(sympy.log) for log in logs: interior = log.args[0] solution = sympy.solve(interior > 0) domain &= relation_to_interval(solution) # case 4 if expr.find(sympy.tan) or expr.find(sympy.cot) or expr.find(sympy.sec) or expr.find(sympy.csc): raise NotImplementedError("tan/cot/sec/csc are not supported") return domain
def test_multivariate(): assert solve((x**2 - 2*x + 1).subs(x, log(x) + 3*x)) == [LambertW(3*S.Exp1)/3] assert solve((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1)) == \ [LambertW(3*exp(-sqrt(2)))/3, LambertW(3*exp(sqrt(2)))/3] assert solve((x**2 - 2*x - 2).subs(x, log(x) + 3*x)) == \ [LambertW(3*exp(1 - sqrt(3)))/3, LambertW(3*exp(1 + sqrt(3)))/3] assert solve(x*log(x) + 3*x + 1, x) == [exp(-3 + LambertW(-exp(3)))] # symmetry assert solve(3*sin(x) - x*sin(3), x) == [3]
def __generate_polydesc(self): # Symbols a,x,y = sp.symbols('a x y') A,X,MAX = sp.symbols('A X MAX') # Attractor limits x_min = (4*a**2 - a**3) / 16 x_max = a / 4 # Functions # f : Attr -> Attr # g : Attr -> [0,1] # gi : [0,1] -> Attr # F = g o f o gi : [0,1] -> [0,1] f = lambda x: a*x*(1-x) g = lambda x: (x - x_min) / (x_max - x_min) gi_expr = sp.solve(g(x) - y, x)[0] gi = lambda y_val: gi_expr.subs(y,y_val) F_expr = g(f(gi(x))).simplify() F = lambda x_val: F_expr.subs(x,x_val) # Parameters # From [Pisarchik]: 3.57 < a < 4 a_min = sp.Rational(387,100) #357 a_max = sp.Rational(400,100) # Map [0,1] -> [a_max,a_min] h = lambda a: (a - a_min) / (a_max - a_min) hi_expr = sp.solve(h(a)-x,a)[0] hi = lambda x_val: hi_expr.subs(x,x_val) # Discretization of F FD = lambda X: (MAX * F(X/MAX)).subs(a, hi(A/MAX)).simplify() #FD(X).diff(C) = MAX*(1849*A**2 + 22102*A*MAX + 16049*MAX**2)/(1849*A**2 + 22102*A*MAX + 56049*MAX**2) # Taylor coefficients C = [(FD(X).taylor_term(i,X) / X**i).simplify() for i in range(3)] # Polynomial descriptor num = [c.as_numer_denom()[0] for c in C] den = [c.as_numer_denom()[1] for c in C] ngcd = sp.gcd(sp.gcd(num[0],num[1]),num[2]) dgcd = sp.gcd(sp.gcd(den[0],den[1]),den[2]) # Descriptor discrete.__polydesc = { 'num' : tuple([n/ngcd for n in num]), 'den' : tuple([d/dgcd for d in den]), 'N' : ngcd, 'D' : dgcd } discrete.__polydesc = { 'num' : tuple([n/ngcd for n in num]), 'den' : tuple([d/dgcd for d in den]), 'N' : ngcd, 'D' : dgcd }
def test_solve_polynomial_cv_1a(): """ Test for solving on equations that can be converted to a polynomial equation using the change of variable y -> x**Rational(p, q) """ assert solve( sqrt(x) - 1, x) == [1] assert solve( sqrt(x) - 2, x) == [4] assert solve( x**Rational(1, 4) - 2, x) == [16] assert solve( x**Rational(1, 3) - 3, x) == [27] assert solve(sqrt(x) + x**Rational(1, 3) + x**Rational(1, 4), x) == [0]
zinv = Symbol("z^-1") # z ** -1 # Bilinear transform equation print_header("Bilinear transformation method") print("\nLaplace and Z Transforms are related by:") pprint(Eq(z, exp(s / rate))) print("\nBilinear transform approximation (no prewarping):") z_num = exp(s / (2 * rate)) z_den = exp(-s / (2 * rate)) assert z_num / z_den == exp(s / rate) z_bilinear = together(taylor(z_num, x=s, x0=0) / taylor(z_den, x=s, x0=0)) pprint(Eq(z, z_bilinear)) print("\nWhich also means:") s_bilinear = solve(Eq(z, z_bilinear), s)[0] pprint(Eq(s, radsimp(s_bilinear.subs(z, 1 / zinv)))) print("\nPrewarping H(z) = H(s) at a frequency " + pretty(w) + " (rad/sample) to " + pretty(f) + " (rad/s):") pprint(Eq(z, exp(I * w))) pprint(Eq(s, I * f)) f_prewarped = (s_bilinear / I).subs(z, exp(I * w)).rewrite(sin) \ .rewrite(tan).cancel() pprint(Eq(f, f_prewarped)) # Lowpass/highpass filters with prewarped bilinear transform equation T = tan(w / 2) for name, afilt_str in [("high", "s / (s - p)"), ("low", "-p / (s - p)")]: print() print_header("Laplace {0}pass filter (matches {0}pass.z)".format(name))
def get_extremum(self): for suspect in self.remove_simulated_number(solve(self.derivative, x)): if self.derivative.diff(x).subs(x, suspect) < 0: self.extremums.append(('max', (suspect, self.function.subs(x, suspect)))) elif self.derivative.diff(x).subs(x, suspect) > 0: self.extremums.append(('min', (suspect, self.function.subs(x, suspect))))
import shlex valOfK = 0 k = sp.symbols('k', integer=True) solutions = [] areaValue = 28 A = np.array([k, -3 * k, 1]) B = np.array([5, k, 1]) C = np.array([-k, 2, 1]) areaMatrix = np.vstack((A, B, C)) areaMatrix = sp.Matrix(areaMatrix) areaMatrixDeterminant1 = areaMatrix.det() - 56 areaMatrixDeterminant2 = areaMatrix.det() + 56 solutions.append(sp.solve(areaMatrixDeterminant1, k)) solutions.append(sp.solve(areaMatrixDeterminant2, k)) print(solutions) valOfK = solutions[0][0] print(valOfK) k1 = int(valOfK) A = np.array([k1, -3 * k1]) B = np.array([5, k1]) C = np.array([-k1, 2]) def proj(A, B, C): X = ((A - B).T) Y = ((C - B)) F = np.matmul(X, Y) G = np.matmul(Y.T, Y)
def __init__(self, **kwargs): # gestion du format d'affichage des probabilités # self.nbformat in ['fraction','pourcentage', 'decimal'] if "nbformat" in kwargs: self.nbformat = kwargs["nbformat"] else: self.nbformat = "pourcentage" # calcul de la précision self.precision = max([ len(str(float(v)).partition(".")[2]) for v in kwargs.values() if type(v) in [float, Rational, One, Zero] ]) s = "a ca b cb ab cab acb cacb b_a cb_a b_ca cb_ca a_b ca_b a_cb ca_cb".split( ) global a, ca, b, cb, ab, cab, acb, cacb, b_a, cb_a, b_ca, cb_ca, a_b, ca_b, a_cb, ca_cb Symb = [ a, ca, b, cb, ab, cab, acb, cacb, b_a, cb_a, b_ca, cb_ca, a_b, ca_b, a_cb, ca_cb ] # remplissage des données de l'énoncé Ltmp = list() L2tmp = list() L3tmp = list() for e in s: for f in Symb: if e in kwargs and f.name == e: val = kwargs[e] Ltmp.append((f, val)) L2tmp.append((e, val)) elif f.name == e: L3tmp.append((e, "…")) self.known = dict(Ltmp) self.known_names = dict(L2tmp) self.probas = dict(L2tmp) # inconnues: self.unknown = [s for s in Symb if s.name not in kwargs] self.unknown_names = dict(L3tmp) # poids pour énoncé self.prob_énoncé = dict(L2tmp) self.prob_énoncé.update(self.unknown_names) # poids … pour énoncé complètement vide self.prob_énoncé_vide = {e: "…" for e in s} # système des contraintes if "indep" not in kwargs: self.SYS = [ Eq(a + ca, 1), Eq(b + cb, 1), Eq(ab + cab, b), Eq(ab + acb, a), Eq(acb + cacb, cb), Eq(cab + cacb, ca), Eq(a_b + ca_b, 1), Eq(a_cb + ca_cb, 1), Eq(b_a + cb_a, 1), Eq(b_ca + cb_ca, 1), Eq(a * b_a, ab), Eq(a * cb_a, acb), Eq(ca * b_ca, cab), Eq(ca * cb_ca, cacb), Eq(b * a_b, ab), Eq(b * ca_b, cab), Eq(cb * a_cb, acb), Eq(cb * ca_cb, cacb) ] else: self.SYS = [ Eq(a + ca, 1), Eq(b + cb, 1), Eq(ab + cab, b), Eq(ab + acb, a), Eq(acb + cacb, cb), Eq(cab + cacb, ca), Eq(a_b + ca_b, 1), Eq(a_cb + ca_cb, 1), Eq(b_a + cb_a, 1), Eq(b_ca + cb_ca, 1), Eq(a * b_a, ab), Eq(a * cb_a, acb), Eq(ca * b_ca, cab), Eq(ca * cb_ca, cacb), Eq(b * a_b, ab), Eq(b * ca_b, cab), Eq(cb * a_cb, acb), Eq(cb * ca_cb, cacb), Eq(a * b, ab), Eq(a * cb, acb), Eq(ca * b, cab), Eq(ca * cb, cacb) ] # màj des valeurs connues self.SYS = [E.subs(self.known) for E in self.SYS] self.noms = list(symbols("A B")) if "noms" in kwargs: self.noms[0].name = kwargs["noms"][0] self.noms[1].name = kwargs["noms"][1] # essai infructueux conjugate pour ca cb #self.titres = {"a": self.noms[0], "ca": conjugate(self.noms[0]), # "b": self.noms[1], "cb": conjugate(self.noms[1])} self.titres = { "a": f"<B>{self.noms[0].name}</B>", "ca": f"<B><O>{self.noms[0].name}</O></B>", "b": f"<B>{self.noms[1].name}</B>", "cb": f"<B><O>{self.noms[1].name}</O></B>" } # dictionnaire des rendus web self.r = { "mathml": print_mathml, "latex": self._latex, "str": str, "choice": self._format } # dictionnaire de résolution complète: self.probas # auparavant les valeurs inconnues sont remplacées par "…" solstmp = solve(self.SYS, self.unknown, dict=True)[0] dtmp = {k.name: v for k, v in solstmp.items()} self.probas.update(dtmp) if "a" in kwargs or "ca" in kwargs: self.makeGrapheviz(1, prob=self.probas) elif "b" in kwargs or "cb" in kwargs: #précaution test elif self.makeGrapheviz(2, prob=self.probas)
##} # Using solver method ##{ X2 = np.linalg.solve(A, B) X2 ##} ##{ from sympy import Eq, Symbol, solve y = Symbol('y') eqn = Eq(y * (8.0 - y**3), 8.0) solve(eqn) ##} ##{ # solve #x+y^2 = 4 #e^x + xy = 3 from scipy.optimize import fsolve import math def equation(p): x, y = p return (x + y**2 - 4, math.exp(x) + x * y - 3)
# Write a program to solve a classic ancient Chinese puzzle: We count 35 heads and 94 legs among the chickens and rabbits in a farm. # How many rabbits and how many chickens do we have? from sympy import Eq, solve from sympy.abc import x, y eq1 = Eq((x * 2 + y * 4), 94) eq2 = Eq(x + y, 35) print(solve((eq1, eq2), (x, y)))
def connect(): maze = read_maze() clear = lambda: os.system('clear') clear() num_of_steps = 0 num_of_turnbacks = 0 dis_and_loc = [] closest = 50 with open("dist&hints" + str(PARALLEL_NUM) + ".txt", "w") as f: f.write("") direc_display = {'u': ' ^^^ ', 'r': ' >', 'd': ' V ', 'l': '< '} buf = 200 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('maze.csa-challenge.com', 80)) text = "" for i in range(12): text += str(s.recv(buf)) loc_text = text.split("(")[1].split(")")[0].split(",") loc = [int(loc_text[0]), int(loc_text[1])] solution = (-1, -1) print(loc) direc = "u" cmd = "n" while direc != "q": #clear() s.send(bytes("i", 'utf-8')) reply_to_direc = s.recv(buf).decode("utf-8") insert_blocks(maze, loc, reply_to_direc) #print(f"{num_of_steps}-{loc}-last_direc: ",direc_display[direc]) if solution == (-1, -1): # didn't find the treasure location yet direc, num_of_turnbacks = next_dir_free_roam( maze[loc[0]][loc[1]], direc, num_of_turnbacks) else: # found treasure location! cur_dist = distance(solution, loc) if closest > cur_dist: closest = cur_dist direc, num_of_turnbacks = next_dir_to_solution( maze, maze[loc[0]][loc[1]], direc, num_of_turnbacks, solution, loc, closest) text = s.recv(buf).decode("utf-8") # == "> What is your command?" if loc == solution: print("Entered Solution Location!") update_xl(maze) s.send(bytes('g', 'utf-8')) dist = s.recv(buf).decode("utf-8") print(f"dist in solution: {dist}") text = s.recv(buf).decode("utf-8") print(f"text in solution: {text}") s.send(bytes('i', 'utf-8')) info = s.recv(buf).decode("utf-8") print(f"info in solution: {info}") text = s.recv(buf).decode("utf-8") print(f"text in solution: {text}") for i in range(10): os.system('play -nq -t alsa synth {} sine {}'.format(0.3, 440)) cmd = input( f"what is next command? (p - recv more/ i - info / g - distance) " ) while cmd == "p": text = s.recv(buf).decode( "utf-8") # reply to solution in correct location cmd = input( f"reply is: {text}, what is next command? (p/i/g) ") s.send(bytes('g', 'utf-8')) dist = s.recv(buf).decode("utf-8") text = s.recv(buf).decode("utf-8") # == "> What is your command?" if dist[:5] != "far f": if solution != (-1, -1): print(f"{loc}-{cur_dist}-{len(dis_and_loc)}-{solution}") else: print(f"{loc}-{len(dis_and_loc)}") dis = int(dist.split()[-1].replace("\n", "")) dis_and_loc.append((dis, loc)) s.send(bytes('h', 'utf-8')) hint = s.recv(buf).decode("utf-8") text = s.recv(buf).decode("utf-8") # == "> What is your command?" if hint[:5] in ["I wis", "I bel", "Reall", "Don't", "Don't"]: hint = "irrelevent " with open("dist&hints" + str(PARALLEL_NUM) + ".txt", "a") as f: f.write(f"steps:{num_of_steps} loc:{loc} d:{dist[:-1]}\n") else: if solution != (-1, -1): print(f"{loc}-{cur_dist}-{len(dis_and_loc)}-{solution}") if len(dis_and_loc) % 100 != 3: # send direction command to socket s.send(bytes(str(direc), 'utf-8')) reply_to_direc = s.recv(buf).decode("utf-8") if reply_to_direc[0] == "0": blocked(maze, loc, direc) elif reply_to_direc[0] == "1": loc = travel(maze, loc, direc) else: emer = input( f"reply_to_direc: {reply_to_direc}, text: {text}, press enter to proceed" ) if emer == "c": continue text = s.recv(buf).decode("utf-8") # == "> What is your command?" if text[:5] != "> Wha": input(f"text: {text} press enter to proceed") num_of_steps += 1 if num_of_steps % 5000 == 0: update_xl(maze) if num_of_turnbacks == 2: update_xl(maze) if input("Done with this path, enter q to stop. ") == "q": print("Stopping") direc = "q" else: print("Got close enough (again?)") update_xl(maze) if len(dis_and_loc) == 3: eqs = [""] * 3 d1, loc1 = dis_and_loc[0] x1, y1 = loc1 d2, loc2 = dis_and_loc[1] x2, y2 = loc2 d3, loc3 = dis_and_loc[-1] x3, y3 = loc3 x, y = symbols('x y') D = [d1, d2, d3] X = [x1, x2, x3] Y = [y1, y2, y3] for i in range(3): if X[i] < 50: X[i] += 250 if Y[i] < 50: Y[i] += 250 eqs[i] = ((x - X[i])**2 + (y - Y[i])**2 - D[i]) sol_dic = solve(eqs, (x, y)) solution = sol_dic[0] solution = [ var if var < 250 else var - 250 for var in solution ] else: print(maze[loc[0]][loc[1]]) print(f"the Nuaglamir is in {str(solution)}") if distance(solution, loc) < 5: for i in range(5): os.system('play -nq -t alsa synth {} sine {}'.format( 0.3, 440)) cmd = input("We are close. Do you want to take over? (y/n/q) ") else: cmd = "n" print("We are close. Didn't let you take over ") if cmd == "q": print("Stopping") direc = "q" elif cmd == "y": show_area(maze, loc, solution, direc) while cmd in "yiludrghspa": cmd = input( "\nWhat is the command?\ni - info\np - recv\ng - dis\nh - hint\ns - solution\nn - return to auto\na - alter target\nDid you get '> What is your command yet?' " ) if cmd == "a": solution = list( input("write correct target : '(x0,y0): '")) elif cmd == "q": direc = "q" elif cmd != "n": if cmd != "p": if cmd in "ludr": direc = cmd s.send(bytes(cmd, 'utf-8')) reply_to_direc = s.recv(buf).decode("utf-8") if reply_to_direc[0] == "1": loc = travel(maze, loc, direc) print(f"Traveled to: {loc}, Target is: {solution}") print(reply_to_direc) show_area(maze, loc, solution, direc) if cmd[0] == "(": cmd = "y" else: cmd = "n"
from db import DataBase nameFile = input() def set_model(equataion, solution): try: DataBase.callFunction('set_model', equataion, solution) return True except BaseException as e: print(str(e)) return False def add_log(equataion, log_text): try: DataBase.callFunction('add_log', equataion, log_text) except BaseException as e: print(str(e)) with open(nameFile, "r") as t: for line in t: equataion = str(line) try: s = sympy.solve(line) set_model(equataion, str(s)) except: if set_model(equataion, None): add_log(equataion, 'Error in equation')
import sympy as sp sp.init_printing() a0, a1 = sp.symbols('a0 a1', real=True) gamma, x = sp.symbols('gamma x', real=True) v = sp.sqrt(1 - 1 / gamma**2) y = gamma * x #%% eq1 = sp.Eq(y**2 * a0 + v * gamma**2 * a1) eq2 = sp.Eq(a0**2 * (-y**2 / gamma**2) + a1**2 * (gamma**2 / y**2), 1) sp.solve([eq1, eq2], a0, a1)
def x_point_of_intersection(self): for solution in self.remove_simulated_number(solve(self.function, x)): self.x_point_of_intersections.append((solution, 0))
def __create_decision_vector(self): atoms_of_p_non_key = [] for i in self.__non_key_species_indices: atoms_of_p_non_key.append(self.__symbolic_poly_func[i].atoms( sympy.Symbol)) available_mus = list(set.union(*atoms_of_p_non_key)) # putting them in order for the sake of reproducibility available_mus = [i for i in self.__mu_vec if i in available_mus] # putting them in order for the sake of reproducibility for i in range(len(atoms_of_p_non_key)): atoms_of_p_non_key[i] = [ j for j in self.__mu_vec if j in atoms_of_p_non_key[i] ] self.__mus_solved_for = [] for i in range(len(atoms_of_p_non_key)): for j in atoms_of_p_non_key[i]: if j in available_mus: if not any([ j in atoms_of_p_non_key[ii] for ii in range(len(atoms_of_p_non_key)) if i != ii ]): self.__mus_solved_for.append(j) available_mus.remove(j) break self.__symbolic_equality_poly_fun = [] count = 0 for i in self.__non_key_species_indices: self.__symbolic_equality_poly_fun.append( sympy.solve(self.__symbolic_poly_func[i], self.__mus_solved_for[count])) count += 1 variables_in_decision_vector = list( set(self.__mu_vec) - set(self.__mus_solved_for)) self.__decision_vector = [ i for i in self.__mu_vec if i in variables_in_decision_vector ] true_outflow_reaction_labels = [ self.__g.edges[list(self.__g_edges)[i]]['label'] for i in self.__edges_true_outflow ] self.__decision_vector_indices = [ self.__mu_vec.index(i) for i in self.__decision_vector ] self.__mus_solved_for_indices = [ self.__mu_vec.index(i) for i in self.__mus_solved_for ] self.__decision_vector_reaction_labels = [ true_outflow_reaction_labels[i] for i in self.__decision_vector_indices ]
# # Determine o circuito equivalente de Thévenin ($v_{th}$, $R_{th}$) do ponto de vista dos terminais $(a,b)$ do circuito abaixo. # # a) Determine a $v_{th}$.\ # b) Determine a corrente de curto-circuito $i_{cc}$.\ # c) Determine a $R_{th}$ pelo método da fonte auxiliar. Image("./figures/J7C1.png", width=600) import sympy as sp import numpy as np # + # define as N variáveis desconhecidas v1, v2, v3 = sp.symbols('v1, v2, v3') # define os sistema de N equações eq1 = sp.Eq(-5.5*v1+10.5*v2-8*v3,-120) eq2 = sp.Eq(v1-3*v2+2*v3,25) eq3 = sp.Eq(v1+3*v2-10*v3,0) # resolve o sistema soluc = sp.solve((eq1, eq2, eq3), dict=True) v1 = np.array([sol[v1] for sol in soluc]) v2 = np.array([sol[v2] for sol in soluc]) v3 = np.array([sol[v3] for sol in soluc]) print('Solução do sistema:\n\n v1 = %.2f V,\n v2 = %.2f V,\n v3 = %.2f V.' %(v1, v2, v3))
# Now set values that we require the mean and variance estimates to be within with prob ~95% i.e. 2sd values ## We want our 2*sd to be less than the *_gam values mean_gam = 0.0005 var_gam = 0.0005 # Finally set the function to minimise (this relates to time taken for the whole MC run) delta = 1 # This corresponds to the time required to set up a simulation for given hidden stats time = N * (n + delta) # Now set the alpha and beta parameters and perform the constrained optimisation true_alpha = 0.5 true_beta = 0.5 constraint1 = (mean_gam / 2)**2 - mean_asp_var.subs([(alpha, true_alpha), (beta, true_beta)]) constraint2 = (var_gam / 2)**2 - var_asp_var.subs([(alpha, true_alpha), (beta, true_beta)]) sy.pprint(sy.simplify(constraint1)) sy.pprint(sy.simplify(constraint2)) sy.pprint(time) # Lets solve constraints for N for different values of n n_values = [1, 10, 100, 1000, 10000] for n_value in n_values: print('n: {}'.format(n_value)) print('constraint1 -> N: {}'.format(sy.solve(constraint1.subs(n, n_value)))) print('constraint2 -> N: {}'.format(sy.solve(constraint2.subs(n, n_value))))
def case3(N, a=1, a_symbols={}, f=0, f_symbols={}, basis='poly', symbolic=True, B_type='linear'): """ Solve -(a(x)u)'=0 on [0,1], u(0)=1, u(1)=0. Method: Galerkin. a and f must be sympy expressions with x as the only symbol (other symbols in a gives very long symbolic expressions in the solution and is of little value). """ # Note: a(x) with symbols #f = sm.Rational(10,7) # for a=1, corresponds to f=0 when a=1/(2+10x) """ def a(x): # very slow return sm.Piecewise((a1, x < sm.Rational(1,2)), (a2, x >= sm.Rational(1,2))) def a(x): # cannot be treated by sympy or wolframalpha.com return 1./(a1 + a2*x) # Symbolic a(x) makes large expressions... def a(x): return 2 + b*x def a(x): return 1/(2 + b*x) def a(x): return 1/(2 + 10*x) b = sm.Symbol('b') def a(x): return sm.exp(b*x) """ if f == 0: h = sm.integrate(1 / a, x) h1 = h.subs(x, 1) h0 = h.subs(x, 0) u_exact = 1 - (h - h0) / (h1 - h0) else: # Assume a=1 f1 = sm.integrate(f, x) f2 = sm.integrate(f1, x) C1, C2 = sm.symbols('C1 C2') u = -f2 + C1 * x + C2 BC1 = u.subs(x, 0) - 1 BC2 = u.subs(x, 1) - 0 s = sm.solve([BC1, BC2], [C1, C2]) u_exact = -f2 + s[C1] * x + s[C2] print 'u_exact:', u_exact def integrand_lhs(phi, i, j): return a * phi[1][i] * phi[1][j] def integrand_rhs(phi, i): return f * phi[0][i] - a * dBdx * phi[1][i] boundary_lhs = boundary_rhs = None # not used here Omega = [0, 1] if B_type == 'linear': B = 1 - x elif B_type == 'cubic': B = 1 - x**3 elif B_type == 'sqrt': B = 1 - sm.sqrt(x) else: B = 1 - x if basis == 'poly': phi = phi_factory('poly', N, 1) elif basis == 'Lagrange': phi = phi_factory('Lagrange', N, 1) print 'len phi:', len(phi) B = phi[0][0] * 1 + phi[0][-1] * 0 phi[0] = phi[0][1:-1] phi[1] = phi[1][1:-1] elif basis == 'sines': phi = phi_factory('sines', N, 1) else: raise ValueError('basis=%s must be poly, Lagrange or sines' % basis) print 'Basis functions:', phi[0] dBdx = sm.diff(B, x) verbose = True if symbolic else False phi_sum = solve(integrand_lhs, integrand_rhs, phi, Omega, boundary_lhs, boundary_rhs, verbose=verbose, symbolic=symbolic) print 'sum c_j*phi_j:', phi_sum name = 'numerical, N=%d' % N u = {name: phi_sum + B, 'exact': sm.simplify(u_exact)} print 'Numerical solution:', u[name] if verbose: print '...simplified to', sm.simplify(u[name]) print '...exact solution:', sm.simplify(u['exact']) f_str = str(f).replace(' ', '') a_str = str(a).replace(' ', '') filename = 'DaDu=-%s_a=%s_N%s_%s.eps' % (f_str, a_str, N, basis) # Change from symblic to numerical computing for plotting. all_symbols = {} all_symbols.update(a_symbols) all_symbols.update(f_symbols) if all_symbols: for s in all_symbols: value = all_symbols[s] print 'symbol', s, 'gets value', value u[name] = u[name].subs(s, value) u['exact'] = u['exact'].subs(s, value) print 'Numerical u_exact formula before plot:', u_exact comparison_plot(u, [0, 1], filename)
def get_fr(var_, L, H): fx = a_ * (var_ / L)**2 + b_ * (var_ / L) eqns = [fx.subs(var_, L), fx.subs(var_, L / 2) - H] ab_subs = sp.solve(eqns, [a_, b_]) fx = fx.subs(ab_subs) return fx
def case2(N): """ Solve -u''=f(x) on [0,1], u'(0)=C, u(1)=D. Method: Galerkin only. """ x = sm.Symbol('x') f = 2 D = 2 E = 3 L = 1 # basis function factory restricted to [0,1] D = sm.Symbol('D') C = sm.Symbol('C') # u exact f1 = sm.integrate(f, x) f2 = sm.integrate(f1, x) C1, C2 = sm.symbols('C1 C2') u = -f2 + C1 * x + C2 BC1 = sm.diff(u, x).subs(x, 0) - C BC2 = u.subs(x, 1) - D s = sm.solve([BC1, BC2], [C1, C2]) u_e = -f2 + s[C1] * x + s[C2] def diff_eq(u, x): eqs = { 'diff': -sm.diff(u, x, x) - f, 'BC1': sm.diff(u, x).subs(x, 0) - C, 'BC2': u.subs(x, L) - D } for eq in eqs: eqs[eq] = sm.simplify(eqs[eq]) print 'Check of exact solution:', diff_eq(u_e, x) def integrand_lhs(phi, i, j): return phi[1][i] * phi[1][j] B = D * x / L dBdx = sm.diff(B, x) def integrand_rhs(phi, i): return f * phi[0][i] - dBdx * phi[1][i] boundary_lhs = None # not used here def boundary_rhs(phi, i): return -C * phi[0][i].subs(x, 0) Omega = [0, L] phi = phi_factory('poly3', N, 1) #phi = phi_factory('Lagrange', N, 1) print phi[0] u = { 'G1': solve(integrand_lhs, integrand_rhs, phi, Omega, boundary_lhs, boundary_rhs, verbose=True) + B, 'exact': u_e } print 'numerical solution:', u['G1'] print 'simplified:', sm.simplify(u['G1']) print 'u exact', u['exact'] # Change from symblic to numerical computing for plotting. # That is, replace C and D symbols by numbers # (comparison_plot takes the expressions with x to functions of x # so C and D must have numbers). for name in u: u[name] = u[name].subs(C, 2).subs(D, -2) print 'u:', u C = 2 D = -2 # Note that these are also remembered by u_e comparison_plot(u, [0, 1])
#!/usr/bin/python from sympy import latex from sympy import solve from sympy import symbols from sympy import Eq from sympy import Rational P, V, n, R, T = symbols('P V n R T') igl = Eq(P * V, n * R * T) values = {R: 8.3144621, T: 273, P: 101300, n: 1} answers = solve(igl.subs(values), V) answer = answers[0] print "" print "The ideal gas law is ", latex(igl) print "" print "Where the gas constant R is {} in SI units".format(values[R]) print "Standard temperature is {} Kelvin, or 0 degrees Celsius".format( values[T]) print "Standard pressure is {} pascals, or 1 atm".format(values[P]) print "" print "So, at standard temperature and pressure, one mole of an ideal gas" print " occupies {} cubic meters of volume".format(answer) print ""
# In[ ]: #constants maxSpeed = 100 #dic to store data dic = {} noPositive = 0 # In[24]: Fc = sympy.symbols("Fc", real=True) eq = sympy.Eq((Fc)**2, maxSpeed**2) sol=sympy.solve(eq) print(sol) # In[77]: Fa, Fb = sympy.symbols("Fa Fb", real=True) Fx = 0 Fy = 128 eq1 = sympy.Eq((Fy-sqrt(3)*Fx)*Fb-(Fy+sqrt(3)*Fx)*Fa, 0) eq2 = sympy.Eq(((sqrt(3)/2)*Fb+(sqrt(3)/2)*Fa)**2+(0.5*Fb-0.5*Fa)**2, 10000) sol=sympy.solve([eq1, eq2]) if sol[0][Fa] >0 and sol[0][Fb]>0: print("yes") elif sol[1][Fa] >0 and sol[1][Fb]>0: print("haha")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 17 09:42:30 2018 @author: xsxsz """ import sympy as sy sy.init_printing(use_unicode=True, use_latex=True) x, y = sy.symbols('x y') expr = x + y**2 latex = sy.latex(expr) print(latex) print('----------') print(sy.solve(x + 1, x)) print('----------') print(sy.limit(sy.sin(x) / x, x, 0)) print('----------') print(sy.limit(sy.sin(x) / x, x, sy.oo)) print('----------') print(sy.limit(sy.ln(x + 1) / x, x, 0)) print('----------') print(sy.integrate(sy.sin(x), (x, -sy.oo, sy.oo))) print('----------') print(sy.integrate(1 / x, (x, 1, 2))) print('----------') print(sy.Rational(1, 2)) print('----------')
fp = f.diff(x) # evaluate both at x=0 and x=1 f0 = f.subs(x, 0) f1 = f.subs(x, 1) fp0 = fp.subs(x, 0) fp1 = fp.subs(x, 1) # we want a, b, c, d such that the following conditions hold: # # f(0) = 0 # f(1) = 0 # f'(0) = alpha # f'(1) = beta S = sympy.solve([f0, f1, fp0-alpha, fp1-beta], [a, b, c, d]) # print the analytic solution and plot a graphical example coeffs = [] num_alpha = 0.3 num_beta = 0.03 for key in [a, b, c, d]: coeffs.append(S[key].subs(dict(alpha=num_alpha, beta=num_beta))) xvals = np.linspace(0, 1, 101) yvals = np.polyval(coeffs, xvals) plt.plot(xvals, yvals)
# coding: UTF-8 # 2直線の交点を求める # y = -3/2x + 6 , y = 1/2x + 2 from sympy import Symbol, solve # sympyの中から Symbolとsolveをimport # 式を定義 x = Symbol('x') y = Symbol('y') ex1 = -3.0 / 2 * x + 6 - y ex2 = 1.0 / 2 * x + 2 - y # 連立方程式を解く print(solve((ex1, ex2)))
def test_piecewise_solve2(): f = Piecewise(((x - 2)**2, x >= 0), (0, True)) assert solve(f, x) == [2, Interval(0, oo, True, True)]
def main(): selected_item = -1 selected_item2 = -1 while True: cfg.clr() if selected_item == -1: print(cfg.TEXT) print("Главное меню") print(cfg.SELECT) try: selected_item = int(input(">>> ")) except: continue elif selected_item == 1: # Если выбрали Решение уравнений while True: cfg.clr() if selected_item2 == -1: # Начальный текст print(cfg.TEXT) print("Решение уравнений") print(cfg.SELECT2) try: selected_item2 = int(input(">>> ")) except: continue elif selected_item2 == 1: # Задать символ cfg.clr() print(cfg.GUIDE) input("Нажмите [ENTER] чтобы вернуться назад") selected_item2 = -1 elif selected_item2 == 2: cfg.clr() print(cfg.TEXT) print("Напишите уравнение") yr = input(">>> ").strip().replace(" ", "").split("=") if len(yr) != 2: print("Неверное уравнение") input("Нажмите [ENTER] чтобы вернуться назад") selected_item2 = -1 else: try: # DEBUG: print(f"{yr=}; {x=}") answer = sympy.solve(sympy.Eq(eval(yr[0]), eval(yr[1]))) except: print("Неверное уравнение") input("Нажмите [ENTER] чтобы вернуться назад") selected_item2 = -1 else: print("Ответ(ы): {}".format(", ".join(str(v) for v in answer))) input("Нажмите [ENTER] чтобы вернуться назад") selected_item2 = -1 elif selected_item2 == 3: # Назад break selected_item = -1 selected_item2 = -1 elif selected_item == 2: # Если выбрали Инфо print(cfg.CREDITS) input("Нажмите [ENTER] чтобы вернуться назад") selected_item = -1 elif selected_item == 3: # Если выбрали Выход selected_item = -1 cfg.clr() exit(0)
def run_test(tag, length, gd_expr, title="Rheometry Test", ln_prefix="rheometry_test", ln_override=None): global mot # Calculate initial GD for warm up gd_expr = str(gd_expr) gd = sp.Symbol('gd') t = 0.0 expr = pe(gd_expr) - gd gd_val = eval(str(sp.solve(expr, gd)[0])) mot.setup_gpio() mot.set_dc(50) #display([title, "", ""], [""], input_type=inputs.none_) ln = "./../logs/{}_{}_{}.csv".format(ln_prefix, tag, time.strftime("%d%m%y_%H%M", time.gmtime())) if ln_override != None: ln = ln_override blurb = [ title, "(warming up motor)", "{} {}".format("Electronics".center(38), "Mechanics".center(38)), "{}{} {}{}".format("Vms:".center(19), "-- V".center(19), "omega:".center(19), "-- rad/s".center(19)), "{}{} {}{}".format("Ims:".center(19), "-- A".center(19), "gamma dot:".center(19), "-- (s^-1)".center(19)), "{}{} {}{}".format("".center(19), "".center(19), "tau:".center(19), "-- Pa".center(19)), "{}{} {}{}".format("PWM DC:".center(19), "-- %".center(19), "mu:".center(19), "-- Pa.s".center(19)), "", "", "[{}]".format(" " * 40) ] options = [" "] display(blurb, options, input_type=inputs.none_) time.sleep(1) set_strain_rate(gd_val) time.sleep(3) mot.start_poll(name=ln, controlled=True, debug_=debug) for i in range(0, length): gd_expr = str(gd_expr) gd = sp.Symbol('gd') t = float(copy.copy(i)) expr = pe(gd_expr) - gd gd_val = eval(str(sp.solve(expr, gd)[0])) set_strain_rate(gd_val) ## Progress bar width = 40 perc = int(math.ceil((i / float(length)) * width)) neg_perc = int(math.floor(((float(length) - i) / length) * width)) ## Status aspd = mot.get_speed() aspd_rads = (aspd * 2 * np.pi) / 60.0 dc = mot.ldc vms = mot.volts[7] * dproc.vmsmult ims = dproc.get_current(mot.volts[2]) gd, __, tau, mu = dproc.calc_mu(1, vms, ims, 15, aspd_rads, dwdt_override=0) blurb = [ title, "", "{} {}".format("Electronics".center(38), "Mechanics".center(38)), "{}{} {}{}".format("Vms:".center(19), "{:.3f} V".format(vms).center(19), "omega:".center(19), "{:.3f} rad/s".format(aspd_rads).center(19)), "{}{} {}{}".format("Ims:".center(19), "{:.3f} A".format(ims).center(19), "gamma dot:".center(19), "{:.3f} (s^-1)".format(gd).center(19)), "{}{} {}{}".format("".center(19), "".center(19), "tau:".center(19), "{} Pa".format(tau).center(19)), "{}{} {}{}".format("PWM DC:".center(19), "{:.3f} %".format(dc).center(19), "mu:".center(19), "{:.2E} Pa.s".format(mu).center(19)), "", "{}s to go...".format(length - i).center(80), "[{}{}]".format("#" * perc, " " * neg_perc) ] options = [" "] display(blurb, options, input_type=inputs.none_) time.sleep(1) mot.clean_exit() blurb = [ title, "", "Processing results..." ] options = [" "] display(blurb, options, input_type=inputs.none_) calculate_viscosity(ln) blurb = [ title, "", "Processing complete!" ] options = [" "] display(blurb, options, input_type=inputs.none_) return ln
def menu(initsel=0): global stdscr global debug global mot blurb = [ " " #"Welcome to RPi-R: Simple rheometry recording with a Raspberry Pi", ] options = [ "Run test", # 0 "Calibrate Motor", # 1 "Quit" # 4 ] res = display(blurb, options) if res == 0: ####################################################################################################### RUN TEST: 0 inp_k = False extra_info = " " while not inp_k: blurb = ["Run sample - setup", "", "{}{}".format("Length:".center(40), "--".center(40)), "{}{}".format("Function:".center(40), "--".center(40)), "{}{}".format("Log tag:".center(40), "--".center(40)), "", extra_info, "Enter run length (seconds)"] options = [""] length = display(blurb, options, input_type=inputs.string_) inp_k = True try: length = int(length) except: inp_k = False extra_info = "Input not recognised (must be an integer)" # strain rate function inp_k = False extra_info = " " while not inp_k: blurb = ["Run sample - setup", "", "{}{}".format("Length:".center(40), str(length).center(40)), "{}{}".format("Function:".center(40), "--".center(40)), "{}{}".format("Log tag:".center(40), "--".center(40)), "", extra_info, "Enter strain rate function (inverse seconds)", "", "Input in form of an expression (gamma dot = ...)", "", "Max GD = 250, min GD = 5.", "", "A special case: GD = linear from <MIN> to <MAX>"] options = [""] gd_expr = display(blurb, options, input_type=inputs.string_) gd_expr_split = gd_expr.split() ### Special Cases ### if gd_expr_split[0] == "linear": gd_min = gd_expr_split[2] gd_max = gd_expr_split[4] gd_expr = "{0} + (({1} - {0}) / {2}) * t".format(gd_min, gd_max, length) inp_k = True try: t = 2 gd = sp.Symbol('gd') expr = pe(gd_expr) - gd val = sp.solve(expr, gd) if len(val) > 1: raise Exception("you dun entered it rong lol") a = eval(str(sp.solve(expr, gd)[0])) except: inp_k = False extra_info = "Input not recognised (ensure it is a function of 't', or a constant)" # Run tag inp_k = False extra_info = " " while not inp_k: blurb = ["Run sample - setup", "", "{}{}".format("Length:".center(40), str(length).center(40)), "{}{}".format("Function:".center(40),"gd = {} (s^-1)".format(gd_expr).center(40)), "{}{}".format("Log tag:".center(40), "--".center(40)), "", extra_info, "Enter identifier for the run: (test material composition etc)"] options = [""] tag = display(blurb, options, input_type=inputs.string_) gd_expr_split = gd_expr.split() ### Special Cases ### if gd_expr_split[0] == "linear": gd_min = gd_expr_split[2] gd_max = gd_expr_split[4] gd_expr = "{0} + (({1} - {0}) / {2}) * t".format(gd_min, gd_max, length) inp_k = True try: tag = str(tag) except: inp_k = False extra_info = "Input not recognised (how on earth did you input a non-string?!)" blurb = ["Run sample - setup", "", "{}{}".format("Length:".center(40), str(length).center(40)), "{}{}".format("Function:".center(40),"gd = {} (s^-1)".format(gd_expr).center(40)), "{}{}".format("Log tag:".center(40), tag.center(40)), ""] options = ["Continue", "Quit"] res = display(blurb, options) if res == 1: raise CAE ln = run_test(tag, length, gd_expr) blurb = ["Run sample - complete", "", "output log saved as {}".format(ln)] options = ["Continue"] res = display(blurb, options) elif res == 1: ##################################################################################################### RECAL: 1 -- REMOVE? UNNECESSARY? # Recalibrate ### Part 1: Current Calibration ### len_ccal = 300 blurb = [ "Current Calibration", "", "The current drawn due to inefficiencies in the motor will be found in this test.", "", "The cylinders must be empty, but in position as if a test was being run.", "The test will take around {} minutes.".format(float(len_ccal) / 60.0), "" ] options = [ "Start", "Skip to motor calibration" ] res = display(blurb, options) if not res: cur_log = "./../logs/ccal_{}.csv".format(time.strftime("%d.%m.%y-%H%M", time.gmtime())) mot.start_poll(name=cur_log, controlled=False, debug_=debug) for i in range(0, len_ccal): dc = (100.0 / (len_ccal - 1)) * i mot.set_dc(dc) width = 40 # Calculate Progress Percentage perc = int(math.ceil((i / float(len_ccal)) * width)) neg_perc = int(math.floor(((float(len_ccal) - i) / len_ccal) * width)) # Calculate speed data aspd = mot.get_speed() aspd_rads = aspd * 2.0 * np.pi / 60.0 # Get motor supply voltage vms = mot.volts[7] * dproc.vmsmult if vms == 0: vms = 10**-10 # Calculate viscosity from sensor data gd = dproc.get_strain(aspd_rads) if gd == 0: gd = 10**-10 ico = dproc.get_current_coil(vms) ims = dproc.get_current(mot.volts[2]) iemf = ims - ico T = dproc.T_of_Iemf(iemf) tau = dproc.get_stress(T, 15) if tau < 0: tau = 0.0 mu = tau / gd # Display! blurb = [ "Current Calibration", "", "{} {}".format("Electronics".center(38), "Mechanics".center(38)), "{}{} {}{}".format("Vms:".center(19), "{:.3f} V".format(vms).center(19), "omega:".center(19), "{:.3f} rad/s".format(aspd_rads).center(19)), "{}{} {}{}".format("Ims:".center(19), "{:.3f} A".format(ims).center(19), "gamma dot:".center(19), "{:.3f} (s^-1)".format(gd).center(19)), "{}{} {}{}".format("Iemf:".center(19), "{:.3f} A".format(iemf).center(19), "tau:".center(19), "{:.3f} Pa".format(tau).center(19)), "{}{} {}{}".format("PWM DC:".center(19), "{:.3f} %".format(dc).center(19), "mu:".center(19), "{:.2E} Pa.s".format(mu).center(19)), "", "{}s to go...".format(len_ccal - i).center(80), "[{}{}]".format("#" * perc, " " * neg_perc) ] options = [" "] display(blurb, options, input_type=inputs.none_) time.sleep(1) mot.clean_exit() __, st, __, __, __, __, __, __, cra, __, __, __, Vms, __, __, __ = read_logf(cur_log) Vms = filt_r(st, Vms) cra = filt_r(st, cra) Ims = dproc.get_current(cra) blurb = [ "Current Calibration", "", "Processing data..." ] options = [" "] display(blurb, options, input_type=inputs.none_) fit, fit_eqn, coeffs = plot_fit(Vms, Ims, 1, x_name="Vms", y_name="Ico", outp="./../plots/cal_cur.png") blurb = ["Current Calibration", "", "Complete! Plot saved as \"./../plots/cal_cur.png\"", "", "Previous fit:", "\tIco = Vms * {} + {}".format(dproc.cal_IcoVms[0], dproc.cal_IcoVms[1]), "", "New fit:", "\tIco = Vms * {} + {}".format(coeffs[0], coeffs[1])] options = ["Save results", "Discard"] res = display(blurb, options) if res == 0: dproc.cal_IcoVms = coeffs dproc.writeout() ### Part 2: Motor Calibration ### blurb = [ "Motor Calibration", "", "The torque output of the motor will be related to the current it draws.", "Required are at least two newtonian reference fluids of known viscosity.", "", "This calibration does not need to be done every time the rheometer is used,", "but should be done once in a while." ] options = [ "Continue", "Back to main menu" ] res = display(blurb, options) if res == 1: raise CAE ## Cancellations are exceptional ref_logs = list() ref_viscs = list() ref_nams = list() cal_len = 120 cal_strain = 125 finished = False count = 1 while not finished: inp_k = False ex_inf = "" while not inp_k: blurb = [ "Motor Calibration: fluid {}".format(count), "", "Fill the cylinder with a reference fluid up to the \"15ml min\" line.", "Then raise the platform so that the liquid level raises to the \"15ml max\" line.", "", "Enter the nominal viscosity (in Pa.s), or enter the name of the fluid, OR enter a", "fluid mixture followed by the composition (weight%)", ex_inf, "e.g. '0.01'", "or 'glycerol'", "or '[email protected]' the characters used here are important! Do not deviate." ] options = [" "] str_nom_visc = display(blurb, options, input_type=inputs.string_) try: ref_viscs.append(float(str_nom_visc)) # assumes is float of nominal viscosity... inp_k = True except: try: dproc.get_mu_of_T(str_nom_visc, 25.0) # ... or name of species... ref_viscs.append(str_nom_visc) inp_k = True except: try: parts = str_nom_visc.split("@") dproc.get_mu_of_T(parts[0], 25.0, parts[1]) ref_viscs.append(str_nom_visc) inp_k = True except: ex_inf = "Couldn't understand... Did you spell it correctly?" inp_k = False inp_k = False while not inp_k: blurb = [ "Motor Calibration: fluid {}".format(count), "", "Enter a name to distinguish this log from the rest:" ] options = [" "] str_ref_nam = display(blurb, options, input_type=inputs.string_) blurb = [ "Motor Calibration: fluid {}".format(count), "", "\"{}\"?".format(str_ref_nam) ] options = ["Continue", "Re-enter"] rep = display(blurb, options, input_type=inputs.enum_) if rep == 0: inp_k = True ref_nams.append(str_ref_nam) blurb = [ "Motor Calibration: fluid {}".format(count), "", "Now the fluid will be sheared for {} minutes at a strain of ~{} (s^-1).".format(float(cal_len) / 60.0, cal_strain), ] options = [ "Continue", "Cancel" ] res = display(blurb, options) if res == 1: raise CAE ref_log = "./../logs/mcal_{}_{}_{}.csv".format(ref_nams[-1], ref_viscs[-1], time.strftime("%d.%m.%y-%H%M", time.gmtime())) run_test("newt_ref", cal_len, 125, title="Reference {} Test: {}".format(count, ref_nams[-1]), ln_override=ref_log) ref_logs.append(ref_log) count += 1 if count == 2: finished = False else: # count > 2 blurb = [ "Motor Calibration", "", "Do you wish to add further reference fluids? ({} so far)".format(count - 1) ] options = ["Yes", "No"] res = display(blurb, options) if res == 1: finished = True mot_cal(ref_logs) else: return 4 return 1
if len(pts) > 1: ax1.plot(pts, pts, 'o', color='black') ax1.grid(True, which='both') #eje x ax1.axhline(y=0, color='k') #eje y ax1.axvline(x=0, color='k') t = symbols('t', real=True) #definimos dominio de la función x = np.arange(-5, 5, 0.1) f = lambda t: t**2 + 1 pts = solve(t**2 + 1 - t) grafFuncion(f, x, 121, pts) """ x = np.arange(-3, 3, 0.1) f = lambda t: t**3 - 3*x pts = solve(t**3 - 3*t - t) grafFuncion(f, x, 122, pts)""" x = np.arange(-5, 5, 0.1) f = lambda t: t**2 - 2 pts = solve(t**2 - 2 - t) grafFuncion(f, x, 122, pts) plt.show()
import numpy as np import sympy from sympy import cos, sin, sqrt, pi sympy.var('A, An, T, rho') t = sympy.Symbol('t') n = sympy.Symbol('n', integer=True, positive=True) x = sympy.Symbol('x', positive=True) L = 7 a = 3 * L / 4 y0 = sympy.Piecewise((A * x / a, ((x >= 0) & (x <= a))), (A * (L - x) / (L - a), ((x > a) & (x <= L)))) Yn = An * sympy.sin(n * pi * x / L) exp = sympy.integrate(rho * Yn**2, (x, 0, L)) - 1 An = sympy.solve(exp, An)[1].simplify() Yn = An * sin(n * pi * x / L) # Finding Modal Force F0 = 1. Omega = 0.99 * 1 * pi * sqrt(T / (rho * L**2)) Fx = F0 Fn = sympy.integrate(Fx * Yn, (x, 0, L)) # Finding modal initial conditions eta0 = sympy.integrate(rho * Yn * y0, (x, 0, L)).simplify() omegan = n * pi * sqrt(T / (rho * L**2)) k1 = eta0 - Fn / (omegan**2 - Omega**2) etan = Fn / (omegan**2 - Omega**2) * cos(Omega * t) + k1 * cos(omegan * t) import matplotlib matplotlib.use('TkAgg')
def noneuclidian_distance_calculation(): from sympy import solve,sqrt Print_Function() metric = '0 # #,# 0 #,# # 1' (X,Y,e) = MV.setup('X Y e',metric) print 'g_{ij} =',MV.metric print '(X^Y)**2 =',(X^Y)*(X^Y) L = X^Y^e B = L*e # D&L 10.152 print 'B =',B Bsq = B*B print 'B**2 =',Bsq Bsq = Bsq.scalar() print '#L = X^Y^e is a non-euclidian line' print 'B = L*e =',B BeBr =B*e*B.rev() print 'B*e*B.rev() =',BeBr print 'B**2 =',B*B print 'L**2 =',L*L # D&L 10.153 (s,c,Binv,M,S,C,alpha,XdotY,Xdote,Ydote) = symbols('s c (1/B) M S C alpha (X.Y) (X.e) (Y.e)') Bhat = Binv*B # D&L 10.154 R = c+s*Bhat # Rotor R = exp(alpha*Bhat/2) print 's = sinh(alpha/2) and c = cosh(alpha/2)' print 'exp(alpha*B/(2*|B|)) =',R Z = R*X*R.rev() # D&L 10.155 Z.obj = expand(Z.obj) Z.obj = Z.obj.collect([Binv,s,c,XdotY]) Z.Fmt(3,'R*X*R.rev()') W = Z|Y # Extract scalar part of multivector # From this point forward all calculations are with sympy scalars print 'Objective is to determine value of C = cosh(alpha) such that W = 0' W = W.scalar() print 'Z|Y =',W W = expand(W) W = simplify(W) W = W.collect([s*Binv]) M = 1/Bsq W = W.subs(Binv**2,M) W = simplify(W) Bmag = sqrt(XdotY**2-2*XdotY*Xdote*Ydote) W = W.collect([Binv*c*s,XdotY]) #Double angle substitutions W = W.subs(2*XdotY**2-4*XdotY*Xdote*Ydote,2/(Binv**2)) W = W.subs(2*c*s,S) W = W.subs(c**2,(C+1)/2) W = W.subs(s**2,(C-1)/2) W = simplify(W) W = W.subs(1/Binv,Bmag) W = expand(W) print 'S = sinh(alpha) and C = cosh(alpha)' print 'W =',W Wd = collect(W,[C,S],exact=True,evaluate=False) Wd_1 = Wd[ONE] Wd_C = Wd[C] Wd_S = Wd[S] print 'Scalar Coefficient =',Wd_1 print 'Cosh Coefficient =',Wd_C print 'Sinh Coefficient =',Wd_S print '|B| =',Bmag Wd_1 = Wd_1.subs(Bmag,1/Binv) Wd_C = Wd_C.subs(Bmag,1/Binv) Wd_S = Wd_S.subs(Bmag,1/Binv) lhs = Wd_1+Wd_C*C rhs = -Wd_S*S lhs = lhs**2 rhs = rhs**2 W = expand(lhs-rhs) W = expand(W.subs(1/Binv**2,Bmag**2)) W = expand(W.subs(S**2,C**2-1)) W = W.collect([C,C**2],evaluate=False) a = simplify(W[C**2]) b = simplify(W[C]) c = simplify(W[ONE]) print 'Require a*C**2+b*C+c = 0' print 'a =',a print 'b =',b print 'c =',c x = Symbol('x') C = solve(a*x**2+b*x+c,x)[0] print 'cosh(alpha) = C = -b/(2*a) =',expand(simplify(expand(C))) return
# A company plans to enclose three parallel rectangular areas for sorting returned goods. # The three areas are within one large rectangular area and 1400 yd of fencing is available. What is the largest total area that can be enclosed? from sympy import symbols, solve, diff x, y = symbols('x y', positive=True) A = 2 * x + 4 * y - 904 y_eq = solve(A, y)[0] Ax = y_eq * x dA = diff(Ax, x) crit_val = solve(dA, x)[0] short_side = y_eq.subs({x: crit_val}) total_area = Ax.subs({x: crit_val}) if __name__ == '__main__': print('Shorter Len: {0} yd'.format(short_side)) print('Longer side: {0} yd'.format(crit_val)) print('Total Area: {0} yd^2'.format(total_area))
def get_roots(expr): """Given the transfer function ``expr``, returns ``poles, zeros``. """ num, den = sympy.fraction(expr) return sympy.solve(den, s), sympy.solve(num, s)