def get_symbolic(u, x, a, b): int1 = sp.Integral(u(x) * u(x), (x, a, b)) du = lambda x: sp.diff(u(x), x) int2 = sp.Integral(du(x) * du(x), (x, a, b)) l2_norm = sqrt(int1.evalf()) h1_semi_norm = sqrt(int2.evalf()) h1_norm = np.linalg.norm((l2_norm, h1_semi_norm)) return l2_norm, h1_norm
def _solve_symbolicaly(self, u, x0, t, t0, exp_method="diagonalize", do_integrals=True): """ returns the symbolic evaluation of the system for input u and known state x0 at time t0 """ # set the valid methods for the sp.Matrix exponential # TODO: Laplace Transform valid_methods = ("diagonalize") if exp_method not in valid_methods: raise ValueError("unknown method for sp.Matrix exponential:", exp_method) # define temporary symbols tau tau = sp.Symbol('tau', positive=True) x = sp.Symbol('x') # compute the two sp.Matrix exponentials that are used in the general solution # to avoid two eigenvalue problems, first solve for a general real x and substitude then expAx = sp.simplify(sp.exp(self.represent[0] * x)) expA = sp.simplify(expAx.subs(x, t - t0)) expAt = sp.simplify(expAx.subs(x, t - tau)) # define the sp.Integral and heuristic simplification nowing that in the sp.Integral, tau < t always holds integrand = sp.simplify(self.represent[2] * expAt * self.represent[1] * u.subs(t, tau)) integrand = sp.simplify( integrand.subs([(abs(t - tau), t - tau), (abs(tau - t), t - tau)])) sp.Integral = sp.zeros(integrand.shape[0], integrand.shape[1]) for col_idx in range(integrand.cols): for row_idx in range(integrand.rows): try: if not integrand[row_idx, col_idx] == 0: if do_integrals is True: sp.Integral[row_idx, col_idx] = sp.simplify( sp.integrate(integrand[row_idx, col_idx], (tau, t0, t))) else: sp.Integral[row_idx, col_idx] = sp.Integral( integrand, (tau, t0, t)) except: sp.Integral[row_idx, col_idx] = sp.Integral(integrand, (tau, t0, t)) # return the general solution: return sp.simplify(self.represent[2] * expA * x0 + self.represent[3] * u + sp.Integral)
def print_ConstantTimes(self, rule): with self.new_step(): self.append("The integral of a constant times a function " "is the constant times the integral of the function:") self.append(self.format_math_display( sympy.Eq( sympy.Integral(rule.context, rule.symbol), rule.constant * sympy.Integral(rule.other, rule.symbol)))) with self.new_level(): self.print_rule(rule.substep) self.append("So, the result is: {}".format( self.format_math(_manualintegrate(rule))))
class convergent(core.Factory): integer_constants = True positive_constants = True # Simple negative powers template_0 = sp.Integral(1 / ((x + A) * (x + B)), (x, C, sp.oo)) conds_0 = [sp.Ne(A, B)] # Exponential template_1 = sp.Integral(x * sp.exp(-A * (x - B)), (x, B, sp.oo)) # Power and logarithm template_2 = sp.Integral(1 / (x * (sp.ln(x)) ** P), (x, D, sp.oo)) conds_2 = [core.Domain(A, [1, 2])]
def test_integral(self): symbolic = Broadcast(a * c, (3, )) indexed = symbolic[1] integ = sympy.Integral(symbolic, (a, 0, b)) idx_integ = sympy.Integral(indexed, (a, 0, b)) self.assertEqual(integ, Broadcast(sympy.Integral(a * c, (a, 0, b)), (3, ))) self.assertEqual(idx_integ, Broadcast(sympy.Integral(a * c, (a, 0, b)), (3, ))[1]) diffed = sympy.diff(symbolic, a) idx_diffed = sympy.diff(indexed, a) self.assertEqual(symbolic.subs(a, 1), diffed) self.assertEqual(indexed.subs(a, 1), idx_diffed)
def print_CyclicParts(self, rule): with self.new_step(): self.append("Use integration by parts, noting that the integrand" " eventually repeats itself.") u, v, du, dv = [ sympy.Function(f)(rule.symbol) for f in 'u v du dv'.split() ] current_integrand = rule.context total_result = sympy.S.Zero with self.new_level(): sign = 1 for rl in rule.parts_rules: with self.new_step(): self.append("For the integrand {}:".format( self.format_math(current_integrand))) self.append("Let {} and let {}.".format( self.format_math(sympy.Eq(u, rl.u)), self.format_math(sympy.Eq(dv, rl.dv)))) v_f, du_f = _manualintegrate(rl.v_step), rl.u.diff( rule.symbol) total_result += sign * rl.u * v_f current_integrand = v_f * du_f self.append("Then {}.".format( self.format_math( sympy.Eq( sympy.Integral(rule.context, rule.symbol), total_result - sign * sympy.Integral( current_integrand, rule.symbol))))) sign *= -1 with self.new_step(): self.append( "Notice that the integrand has repeated itself, so " "move it to one side:") self.append("{}".format( self.format_math_display( sympy.Eq((1 - rule.coefficient) * sympy.Integral(rule.context, rule.symbol), total_result)))) self.append("Therefore,") self.append("{}".format( self.format_math_display( sympy.Eq(sympy.Integral(rule.context, rule.symbol), _manualintegrate(rule)))))
def inverse_laplace_product(expr, s, t): # Handle expressions with a function of s, e.g., # V(s), V(s) * Y(s), 3 * V(s) / s etc. const, expr = factor_const(expr, s) factors = expr.as_ordered_factors() if len(factors) < 2: raise ValueError('Expression does not have multiple factors: %s' % expr) result1, result2 = inverse_laplace_term1(factors[0], s, t) result = (result1 + result2) for m in range(len(factors) - 1): if m == 0: tau = sym.sympify('tau') else: tau = sym.sympify('tau_%d' % m) result1, result2 = inverse_laplace_term1(factors[m + 1], s, t) expr2 = result1 + result2 result = sym.Integral(result.subs(t, t - tau) * expr2.subs(t, tau), (tau, -sym.oo, sym.oo)) return result * const
def Q1(): x = sp.symbols('x') integ = sp.Integral(1 / (1 + pow(x, 2)), x) pprint.pprint(integ) pprint.pprint((integ.doit())) return
def make_int_poly_prob(var="x", order=3): """ Generates a n-order polynomial to be integrated. x : charector for the variable to be solved for. defaults to "x". OR a list of possible charectors. A random selection will be made from them. n : order of the polynomial or a list of possible orders. Defaults to 3. A random selection will be made from them. """ if isinstance(var, str): var = sympy.Symbol(var) elif isinstance(var, list): var = sympy.Symbol(random.choice(var)) if isinstance(order, list): order = random.choice(order) eq = polyn(var,order) sol = sympy.latex(sympy.integrate(eq, var)) eq = sympy.latex(sympy.Integral(eq, var)) eq = 'd'.join(eq.split("\\partial")) eq = "$$" + eq + "$$" sol = "$$" + sol + " + C $$" return eq, sol
def noevaluate(self, expr, t, s): t0 = sympify('t0') return sym.Limit(sym.Integral(expr * sym.exp(-s * t), (t, t0, sym.oo)), t0, 0, dir='-')
def compute(): x = sp.symbols('x') # Angles xi, phi = sp.symbols('xi phi') # Material parameters F0, alpha = sp.symbols('F_{0} alpha') # Dot products n_dot_v = sp.cos(xi) n_dot_l = x n_dot_h = (sp.cos(xi) + x) / sp.sqrt(2 + 2*sp.sin(xi)*sp.cos(phi)*sp.sqrt(1-x**2) + 2*sp.cos(xi)*x) v_dot_h = sp.sqrt((1 + sp.sin(xi)*sp.cos(phi)*sp.sqrt(1-x**2) + sp.cos(xi)*x)/2) # BRDF components V = 2 / (n_dot_v*sp.sqrt(alpha**2 + (1-alpha**2)*n_dot_l)\ + n_dot_l*sp.sqrt(alpha**2 + (1-alpha**2)*n_dot_v)) V = ses(V) D = alpha**2 / (sp.pi * (n_dot_h*(alpha**2-1) + 1)**2) D = ses(D) F = F0 + (1-F0)*(1-v_dot_h)**5 F = ses(F) S = (F * D * V) / 4 S = ses(S) # Integral integrand = ses(S * x) integral = sp.Integral(integrand, (x, 0, 1), (phi, 0, 2*sp.pi)) display(integral)
def create_A_and_b(self, s, c_vec): b = np.ones(s) A = np.ones((s, s)) for count in range(s): lagrange, t = self.get_lagrange_polynomial(c_vec, count) t = sym.Symbol('t') b[count] = sym.Integral(lagrange, (t, 0, 1)).evalf() for count2 in range(s): A[count2][count] = sym.Integral(lagrange, (t, 0, c_vec[count2])).evalf() # print("A is") # print(A) # print("b is") # print(b) return A, b
def test_get_symbols_by_name(self): c1, C1, x, a, t, Y = sp.symbols('c1, C1, x, a, t, Y') F = sp.Function('F') expr1 = c1 * (C1 + x**x) / (sp.sin(a * t)) expr2 = sp.Matrix([sp.Integral(F(x), x)*sp.sin(a*t) - \ 1/F(x).diff(x)*C1*Y]) res1 = st.get_symbols_by_name(expr1, 'c1') self.assertEqual(res1, c1) res2 = st.get_symbols_by_name(expr1, 'C1') self.assertEqual(res2, C1) res3 = st.get_symbols_by_name(expr1, *'c1 x a'.split()) self.assertEqual(res3, [c1, x, a]) with self.assertRaises(ValueError) as cm: st.get_symbols_by_name(expr1, 'Y') with self.assertRaises(ValueError) as cm: st.get_symbols_by_name(expr1, 'c1', 'Y') res4 = st.get_symbols_by_name(expr2, 'Y') self.assertEqual(res4, Y) res5 = st.get_symbols_by_name(expr2, 'C1') self.assertEqual(res5, C1) res6 = st.get_symbols_by_name(expr2, *'C1 x a'.split()) self.assertEqual(res6, [C1, x, a])
class divergent(Factory): integer_constants = True positive_constants = True # Simple negative powers template_0 = sp.Integral(1 / ((x + A) * (x + B)), (x, C, sp.oo)) conds_0 = [sp.Ne(A, B)]
def integrate_and_simplify(*args, **kwargs): """ A wrapper for Integral(...).doit() Pass in the same parameters as you would to Integral """ return s.Integral(*args, **kwargs).doit()
def primitiva(m): cid = m.chat.id funcion = m.text[len("/primitiva "):] try: f = parse_expr(funcion) except: bot.send_message(cid, "La función {} no es una función de x válida".format(funcion)) return try: queue = Queue() p = Process(target=intento_integracion, args=(f, queue,)) p.start() I = queue.get() p.join(20) if (p.is_alive()): p.terminate() p.join() except: bot.send_message(cid, "La función {} no puede integrarse, asegúrese de que solo tiene x de variable".format(funcion)) return ecuacion = sympy.Eq(sympy.Integral(f), I) tex_content = latex_doc[0] + sympy.latex(ecuacion) + "+C" + latex_doc[1] f = open("/home/bots/files/pingueinstein/primitiva.tex", 'w') f.write(tex_content) f.close() os.system("pdflatex /home/bots/files/pingueinstein/primitiva.tex -output-directory=/home/bots/files/pingueinstein && pdfcrop /home/bots/files/pingueinstein/primitiva.pdf /home/bots/files/pingueinstein/primitiva-crop.pdf && pdftoppm /home/bots/files/pingueinstein/primitiva-crop.pdf | pnmtopng > /home/bots/files/pingueinstein/primitiva.png") bot.send_photo(cid, open("/home/bots/files/pingueinstein/primitiva.png", "rb"))
def A2(f): f = sy.sympify(f) subst = ((x, x0 * (1 - s - t) + x1 * s + x2 * t), (y, y0 * (1 - s - t) + y1 * s + y2 * t)) integrand = 2 * f.subs(subst) iexpr = sy.Integral(integrand, (t, 0, 1 - s), (s, 0, 1)) return process(iexpr)
def print_U(self, rule): with self.new_step(), self.new_u_vars() as (u, du): # commutative always puts the symbol at the end when printed dx = sympy.Symbol('d' + rule.symbol.name, commutative=0) self.append("Let {}.".format( self.format_math(sympy.Eq(u, rule.u_func)))) self.append("Then let {} and substitute {}:".format( self.format_math( sympy.Eq(du, rule.u_func.diff(rule.symbol) * dx)), self.format_math(rule.constant * du))) integrand = rule.constant * \ rule.substep.context.subs(rule.u_var, u) self.append(self.format_math_display(sympy.Integral(integrand, u))) with self.new_level(): self.print_rule( replace_u_var(rule.substep, rule.symbol.name, u)) self.append( '<div class="collapsible"><h2>open answer</h2><ol class="content">Now replace {} to get:' .format(self.format_math(u))) self.append( self.format_math_display(_manualintegrate(rule)) + '</ol></div>')
def laplace_transform(expr, t, s, evaluate=True): """Compute unilateral Laplace transform of expr with lower limit 0-. Undefined functions such as v(t) are converted to V(s).""" if expr.is_Equality: return sym.Eq(laplace_transform(expr.args[0], t, s), laplace_transform(expr.args[1], t, s)) if not evaluate: t0 = sympify('t0') result = sym.Limit(sym.Integral(expr * sym.exp(-s * t), (t, t0, sym.oo)), t0, 0, dir='-') return result const, expr = factor_const(expr, t) key = (expr, t, s) if key in laplace_cache: return const * laplace_cache[key] if expr.has(s): raise ValueError( 'Cannot Laplace transform for expression %s that depends on %s' % (expr, s)) # The variable may have been created with different attributes, # say when using sympify('Heaviside(t)') since this will # default to assuming that t is complex. So if the symbol has the # same representation, convert to the desired one. var = sym.Symbol(str(t)) if isinstance(expr, Expr): expr = expr.expr else: expr = sympify(expr) # SymPy laplace barfs on Piecewise but unilateral LT ignores expr # for t < 0 so remove Piecewise. expr = expr.replace(var, t) if expr.is_Piecewise and expr.args[0].args[1].has(t >= 0): expr = expr.args[0].args[0] expr = sym.expand(expr) terms = expr.as_ordered_terms() result = 0 try: for term in terms: result += laplace_term(term, t, s) except ValueError: raise result = result.simplify() laplace_cache[key] = result return const * result
def P1(f): fx, fy = sy.sympify(f) s = sy.Symbol('s') lx, ly = x1 - x0, y1 - y0 subst = ((x, x0 * (1 - s) + x1 * s), (y, y0 * (1 - s) + y1 * s)) integrand = (fx.subs(subst) * lx + fy.subs(subst) * ly) iexpr = sy.Integral(integrand, (s, 0, 1)) return process(iexpr)
def print_Constant(self, rule): with self.new_step(): self.append("The integral of a constant is the constant " "times the variable of integration:") self.append( self.format_math_display( sympy.Eq(sympy.Integral(rule.constant, rule.symbol), _manualintegrate(rule))))
def testIntegrate(self): self.compare( mathics.Expression( 'Integrate', mathics.Symbol('Global`x'), mathics.Symbol('Global`y')), sympy.Integral( sympy.Symbol('_Mathics_User_Global`x'), sympy.Symbol('_Mathics_User_Global`y')))
def cosh_integral(f, var): """Integrates a function f that has exactly one cosh term, from -oo to oo, by substituting a new helper variable for the cosh argument""" cosh_term = list(f.atoms(sp.cosh)) assert len(cosh_term) == 1 integral = sp.Integral(f, var) transformed_int = integral.transform(cosh_term[0].args[0], sp.Symbol("u", real=True)) return sp.integrate(transformed_int.args[0], (transformed_int.args[1][0], -sp.oo, sp.oo))
def testIntegrate(self): self.compare( mathics.Expression( "Integrate", mathics.Symbol("Global`x"), mathics.Symbol("Global`y") ), sympy.Integral( sympy.Symbol("_Mathics_User_Global`x"), sympy.Symbol("_Mathics_User_Global`y"), ), )
def print_Exp(self, rule): with self.new_step(): if rule.base == sympy.E: self.append("The integral of the exponential function is itself.") else: self.append("The integral of an exponential function is itself" " divided by the natural logarithm of the base.") self.append(self.format_math_display( sympy.Eq(sympy.Integral(rule.context, rule.symbol), _manualintegrate(rule))))
def get_coef(expr, vari, trun=30, period=1.0): """ Calculate Fourier coefficients based on symbolic expression of functions :param expr: Symbolic expression of a function on which Fourier expansion is performed :param vari: variable of the symbolic expression :param trun: Truncation terms :param period: Period :return: Fourier coefficients from 0 to trun """ an = ([ 2 / period * sympy.Integral(expr * sympy.cos(2 * i * sympy.pi * vari / period), (vari, 0, period)).evalf() for i in range(trun + 1) ]) bn = ([ 2 / period * sympy.Integral(expr * sympy.sin(2 * i * sympy.pi * vari / period), (vari, 0, period)).evalf() for i in range(trun + 1) ]) return np.asarray(an, dtype=float), np.asarray(bn, dtype=float)
def print_ConstantTimes(self, rule): with self.new_step(): self.append( "The integral of <strong>a</strong> constant times a function " "is <strong>the</strong> constant times the integral of the function:" ) self.append( self.format_math_display( sympy.Eq( sympy.Integral(rule.context, rule.symbol), rule.constant * sympy.Integral(rule.other, rule.symbol)))) with self.new_level(): self.print_rule(rule.substep) self.append( '<div class="collapsible"><h2>open answer</h2><ol class="content">So, the result is: ' ) self.append( self.format_math(_manualintegrate(rule)) + '</ol></div>')
def gaussqf(M, p, a, b, lf): l = len(M) # count of moments k = l // 2 # count of equations M_ = [] # Making system for a1..an for i in range(k - 1, 2 * k - 1): S = [] for j in range(0, k): S.append(M[i - j]) M_.append(S) m = M[k:l] m = [-1 * x for x in m] m = np.array(m, dtype='float') M_ = np.array(M_, dtype='float') x = sp.symbols('x') A = solve(M_, m) n = len(A) # polynomial degree A = list(A) A = list(reversed(A)) A.append(1) x = sp.symbols("x") eq = 0 # Make equation for i in range(n, -1, -1): eq += A[i] * x ** i # Find nodes. # Nodes must be different and must be in [a,b] X = list(sp.solve(eq)) X = [sp.re(x) for x in X] # omega and derivative of omega w = 1 for i in range(len(X)): w = w * (x - X[i]) dw = sp.diff(w, x) dw = sp.lambdify(x, dw) A = [] print(w) # find coef of the quadrature formula for i in range(len(X)): A.append(sp.Integral(p * w / ((x - X[i]) * (dw(X[i]))), (x, a, b)).as_sum(20, method="midpoint").n()) X = np.array(X, dtype=np.float) A = np.array(A, dtype=np.float) integ_sum = 0 for i in range(len(A)): integ_sum = integ_sum + lf(X[i]) * A[i] print(integ_sum)
def handle_integral(func): if func.additive(): integrand = convert_add(func.additive()) elif func.frac(): integrand = convert_frac(func.frac()) else: integrand = 1 int_var = None if func.DIFFERENTIAL(): int_var = get_differential_var(func.DIFFERENTIAL()) else: for sym in integrand.atoms(sympy.Symbol): s = str(sym) if len(s) > 1 and s[0] == 'd': if s[1] == '\\': int_var = sympy.Symbol(s[2:], real=True) else: int_var = sympy.Symbol(s[1:], real=True) int_sym = sym if int_var: if integrand.func == Div: integrand = sympy.Mul(*integrand.args, evaluate=False) integrand = integrand.subs(int_sym, 1) else: # Assume dx by default int_var = sympy.Symbol('x', real=True) if func.subexpr(): if func.subexpr().atom(): lower = convert_atom(func.subexpr().atom()) else: lower = convert_expr(func.subexpr().expr()) if func.supexpr().atom(): upper = convert_atom(func.supexpr().atom()) else: upper = convert_expr(func.supexpr().expr()) return sympy.Integral(integrand, (int_var, lower, upper)) else: return sympy.Integral(integrand, int_var)
def handle_integral(func): if func.additive(): integrand = convert_add(func.additive()) elif func.frac(): integrand = convert_frac(func.frac()) else: integrand = 1 if func.DIFFERENTIAL(): text = func.DIFFERENTIAL().getText()[1:] if text[0] == "\\": int_var = sympy.Symbol(text[1:]) else: int_var = sympy.Symbol(text) else: for sym in integrand.atoms(sympy.Symbol): s = str(sym) if len(s) > 1 and s[0] == 'd': if s[1] == '\\': int_var = sympy.Symbol(s[2:]) else: int_var = sympy.Symbol(s[1:]) int_sym = sym if int_var: integrand = integrand.subs(int_sym, 1) else: # Assume dx by default int_var = sympy.Symbol('x') if func.subexpr(): if func.subexpr().atom(): lower = convert_atom(func.subexpr().atom()) else: lower = convert_expr(func.subexpr().expr()) if func.supexpr().atom(): upper = convert_atom(func.supexpr().atom()) else: upper = convert_expr(func.supexpr().expr()) return sympy.Integral(integrand, (int_var, lower, upper)) else: return sympy.Integral(integrand, int_var)