def laplace_transform_ode(expr, subs=True): """ Apply the Laplace Transform to an expression and rewrite it in an algebraic form. Parameters ---------- expr : Expr The Sympy expression to transform. subs : boolean Default value to True. If True, substitute L[x(t)](s) with X. Returns ------- t : Symbols Symbol representing the original function domain. t : Symbols Symbol representing the s-domain. transf_expr : Expr The Laplace-transformed expression. """ s = Symbol("s") # perform the laplace transform of a derivative an unknown function def laplace_transform_derivative(lap): der = lap.args[0] f, (t, n) = der.args return s**n * laplace_transform(f, t, s) - sum([ s**(n - i) * f.diff(t, i - 1).subs(t, 0) for i in range(1, n + 1) ]) # extract the original function domain derivs = expr.atoms(Derivative) funcs = set().union(*[d.atoms(AppliedUndef) for d in derivs]) func = funcs.pop() t = func.args[0] # apply the Laplace transform to the expression if isinstance(expr, Eq): expr = expr.func( *[laplace_transform(a, t, s, noconds=True) for a in expr.args]) else: expr = laplace_transform(expr, t, s) # select the unevaluated LaplaceTransform objects laps = expr.atoms(LaplaceTransform) for lap in laps: # if the unevaluated LaplaceTransform contains a derivative if lap.atoms(Derivative): # perform the transformation according to the rule transform = laplace_transform_derivative(lap) expr = expr.subs(lap, transform) # substitute unevaluated LaplaceTransform with a symbol if subs: laps = expr.atoms(LaplaceTransform) for lap in laps: name = lap.args[0].func.name.capitalize() expr = expr.subs(lap, Symbol(name)) return t, s, expr
def test_messy(): from sympy import (laplace_transform, Si, Shi, Chi, atan, Piecewise, acoth, E1, besselj, acosh, asin, And, re, fourier_transform, sqrt) assert laplace_transform(Si(x), x, s) == ((-atan(s) + pi/2)/s, 0, True) assert laplace_transform(Shi(x), x, s) == (acoth(s)/s, 1, True) # where should the logs be simplified? assert laplace_transform(Chi(x), x, s) == \ ((log(s**(-2)) - log((s**2 - 1)/s**2))/(2*s), 1, True) # TODO maybe simplify the inequalities? assert laplace_transform(besselj(a, x), x, s)[1:] == \ (0, And(S(0) < re(a/2) + S(1)/2, S(0) < re(a/2) + 1)) # NOTE s < 0 can be done, but argument reduction is not good enough yet assert fourier_transform(besselj(1, x)/x, x, s, noconds=False) == \ (Piecewise((0, 4*abs(pi**2*s**2) > 1), (2*sqrt(-4*pi**2*s**2 + 1), True)), s > 0) # TODO FT(besselj(0,x)) - conditions are messy (but for acceptable reasons) # - folding could be better assert integrate(E1(x)*besselj(0, x), (x, 0, oo), meijerg=True) == \ log(1 + sqrt(2)) assert integrate(E1(x)*besselj(1, x), (x, 0, oo), meijerg=True) == \ log(S(1)/2 + sqrt(2)/2) assert integrate(1/x/sqrt(1 - x**2), x, meijerg=True) == \ Piecewise((-acosh(1/x), 1 < abs(x**(-2))), (I*asin(1/x), True))
def basic(): ft = (exp((2 * t) * (-1)) - 1)**2 ft2 = sin(2 * t) * cos(2 * t) F = laplace_transform(ft, t, s) F2 = laplace_transform(ft2, t, s) print(F) print(F2)
def test_messy(): from sympy import (laplace_transform, Si, Shi, Chi, atan, Piecewise, acoth, E1, besselj, acosh, asin, And, re, fourier_transform, sqrt) assert laplace_transform(Si(x), x, s) == ((-atan(s) + pi / 2) / s, 0, True) assert laplace_transform(Shi(x), x, s) == (acoth(s) / s, 1, True) # where should the logs be simplified? assert laplace_transform(Chi(x), x, s) == \ ((log(s**(-2)) - log((s**2 - 1)/s**2))/(2*s), 1, True) # TODO maybe simplify the inequalities? assert laplace_transform(besselj(a, x), x, s)[1:] == \ (0, And(S(0) < re(a/2) + S(1)/2, S(0) < re(a/2) + 1)) # NOTE s < 0 can be done, but argument reduction is not good enough yet assert fourier_transform(besselj(1, x)/x, x, s, noconds=False) == \ (Piecewise((0, 4*abs(pi**2*s**2) > 1), (2*sqrt(-4*pi**2*s**2 + 1), True)), s > 0) # TODO FT(besselj(0,x)) - conditions are messy (but for acceptable reasons) # - folding could be better assert integrate(E1(x)*besselj(0, x), (x, 0, oo), meijerg=True) == \ log(1 + sqrt(2)) assert integrate(E1(x)*besselj(1, x), (x, 0, oo), meijerg=True) == \ log(S(1)/2 + sqrt(2)/2) assert integrate(1/x/sqrt(1 - x**2), x, meijerg=True) == \ Piecewise((-acosh(1/x), 1 < abs(x**(-2))), (I*asin(1/x), True))
def laplace_transform_f(fmap: Dict[Function, Function], timevar, svar, expr: Expr, czero=True) -> Expr: """ Transforms a function expression in time space to laplace space with support for derivatives, can be composed with traverse_linop to apply the transform to inner expressions """ L = lambda expr: laplace_transform(expr, timevar, svar) if expr.func == Derivative: f_expr, (var, order) = expr.args # for now only match univariate functions f, (f_var, ) = f_expr.func, f_expr.args if var == timevar == f_var and f in fmap: return laplace_transform_diff(f, fmap[f], timevar, svar, order, czero=czero) if expr.func in fmap: return fmap[expr.func] return L(expr)
def laplace_transform(x=smp.Symbol('x'), s=smp.Symbol('s')): global func, f, result, calculus_screen f = func.get() try: laplace = smp.laplace_transform(f, x, s, noconds=True) smp.pprint(laplace) print(smp.latex(laplace)) ltx.latex(str(smp.latex(laplace))) except: result.configure(text="Don't write like 2x, but 2*x")
def get_values(): """ Get the special values as a dict where the keys are the Symi expressions ans the values are the corresponding SymPy values. Returns ------- values : tuple of dict Correspondences between Symi and Sympy. Values[0] gives the basic function replacements, values[1] gives the operator replacements, values[2] gives the constants replacements values[3] gives the advances function replacements """ fcts = { "arccos": "acos", "arcsin": "asin", "arctan": "atan", "conj": "conjugate", "abs": "Abs", "int": "integrate", "des": "apart" } operators = {} constants = {"i": "I", "j": "J", "inf": "oo", "ipi": "I*pi", "e": "E"} advanced = { "Laplace": lambda __wild_sym__: laplace_transform(parse_expr(str(__wild_sym__)), parse_expr("t"), parse_expr("s"), noconds=True), "Linv": lambda __wild_sym__: inverse_laplace_transform(parse_expr( str(__wild_sym__)), parse_expr("s"), parse_expr("t"), noconds=True), "step": lambda __wild_sym__: Heaviside(__wild_sym__), "dirac": lambda __wild_sym__: DiracDelta(__wild_sym__), "sym": lambda __wild_sym__: Symbol(str(__wild_sym__)), } advanced["L"] = advanced["Laplace"] return fcts, operators, constants, advanced
def _calculate_laplace_transform(self): t, s = sympy.symbols('t, s') try: f = sympy.parsing.sympy_parser.parse_expr( self.line_exp_time.text()) F = sympy.laplace_transform(f, t, s, noconds=True) except (ValueError, TypeError, SyntaxError): error_msg = f'ValueError: invalid expression' # print(error_msg) QtWidgets.QMessageBox.about(self, 'Error message', error_msg) return -1 self.line_exp_state.setText(str(F))
def laplace(self): """Attempt Laplace transform""" var = self.var if var == tsym: # Hack since sympy gives up on Laplace transform if t real! var = sym.symbols('t') try: F, a, cond = sym.laplace_transform(self, var, ssym) except TypeError as e: expr = self.expr if not isinstance(expr, sym.function.AppliedUndef): raise TypeError(e) if (expr.nargs != 1) or (expr.args[0] != tsym): raise TypeError(e) # Convert v(t) to V(s), etc. name = expr.func.__name__.capitalize() + '(s)' return sExpr(name) if hasattr(self, '_laplace_conjugate_class'): F = self._laplace_conjugate_class(F) return F
def L(f): return sympy.laplace_transform(f, t, s, noconds=True)
# upperbound = (np.inf,0,np.inf,+np.inf,np.inf,np.inf) # print(p0) # print(lowerbound) # print(upperbound) popt, pcov = curve_fit(model2_func, t, y, p0) #,bounds=(lowerbound,upperbound)) return popt, pcov s = sy.symbols("s") t = sy.symbols("t", positive=True) A = sy.symbols("A") sig, mu = sy.symbols("sigma,mu", positive=True) gauss = 1 / (sqrt(2 * sy.pi) * sig) * exp(-(1 / 2) * ((s - mu) / sig)**2) * Heaviside(s) f = sy.laplace_transform(gauss, s, t) gaussian_decay = np.vectorize( sy.lambdify((t, A, sig, mu), A * f[0], modules=['numpy'])) #logN = 1/(sqrt(2*sy.pi)*sig*s)*exp(-(1/2)*(log(s-mu)/sig)**2) #f = sy.laplace_transform(logN,s,t) #lognormal_decay=np.vectorize(sy.lambdify((t,A,sig,mu),A*f[0],modules=['numpy'])) def gaussian_fit(t, y, p0, baseline): popt, pcov = curve_fit(gaussian_decay, t, y, p0) return popt, pcov def DLT(t, A, gamma, t0): """Discrete Laplace Transform"""
I0p = 0 V0 = 0 # component values L = 0.1 C = 0.001 R = 100 #%% import sympy as sp s, t = sp.symbols('s, t') w = sp.symbols('w', real=True) Vt = sp.S("155*sin(377*t)") Vs, _, _ = sp.laplace_transform(Vt, t, s) Is = (1 / L) * Vs / (s**2 + (R / L) * s + 1 / (L * C)) It = sp.inverse_laplace_transform(Is, s, t) #%% [markdown] ### Plotting analytic solution #%% # plotting constants time_fine = np.linspace(0.0001, 0.2, 1000) time = np.linspace(0.0001, 0.2, 200) time_coarse = np.linspace(0.0001, 0.2, 100) #%% analytic_soln = [float(sp.re(It.subs({'t': t_}))) for t_ in time]
#! /usr/bin/env python3 import sympy as sp import math s, x = sp.symbols('s, x', positive=True) t = sp.symbols('t') a = sp.symbols('a', real=True) n = sp.symbols('n', naturals=True) exp = sp.exp cos = sp.cos sin = sp.sin sqrt = sp.sqrt expression = cos(x) * sin(x) out = sp.laplace_transform(expression, x, s) print(out)
def laplace_transform(function): return sym.laplace_transform(function, t, s, noconds=True)
def L(f,t,s): return sp.laplace_transform(f, t, s, noconds=True)
import sympy as sym import matplotlib.pyplot as plt from sympy.abc import s, t import numpy as np # Testing Laplace Output y1 = sym.sin(t) Y1 = sym.laplace_transform(y1, t, s) print('Your equation in the frequency domain is: ' + str(Y1[0])) # Inversing and plotting y2 = sym.inverse_laplace_transform(Y1[0], s, t) # Gives a 'Heaviside(t)' at the end; print(y2) char_holder = str(y2) # Removing Heaviside(t) no_heaviside = '' for i in range(len(char_holder)): if char_holder[i + 1] != 'H': no_heaviside += char_holder[i] else: break print('Your equation in the time domain is: ' + no_heaviside) # Plotting time = np.linspace(0, 8, 100) filler_array = np.zeros(len(time)) for y in [y2]:
def laplace_transform_derivative(lap): der = lap.args[0] f, (t, n) = der.args return s**n * laplace_transform(f, t, s) - sum([ s**(n - i) * f.diff(t, i - 1).subs(t, 0) for i in range(1, n + 1) ])
# -*- coding: utf-8 -*- import os import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl mpl.rcParams['text.usetex'] = True import sympy from scipy import integrate t = sympy.symbols("t", positive=True) s, Y = sympy.symbols("s, Y", real=True) y = sympy.Function("y") ode = y(t).diff(t, 2) + 2 * y(t).diff(t) + 10 * y(t) - 2 * sympy.sin(3 * t) print(ode) L_y = sympy.laplace_transform(y(t), t, s) print(L_y) L_ode = sympy.laplace_transform(ode, t, s, noconds=True) print(L_ode) def laplace_transform_derivatives(e): """ Evaluate the unevaluted laplace transforms of derivatives of functions """ if isinstance(e, sympy.LaplaceTransform): if isinstance(e.args[0], sympy.Derivative): d, t, s = e.args n = len(d.args) - 1 return ((s**n) * sympy.LaplaceTransform(d.args[0], t, s) -
# In[119]: s = sympy.symbols("s") # In[120]: a, t = sympy.symbols("a, t", positive=True) # In[121]: f = sympy.sin(a * t) # In[122]: sympy.laplace_transform(f, t, s) # In[123]: F = sympy.laplace_transform(f, t, s, noconds=True) # In[124]: F # In[125]: sympy.inverse_laplace_transform(F, s, t, noconds=True) # In[126]:
mp.dps = 20 series_Length = 1000 # decleare function variables t = time; s = 1/t (frequency) t, s = sym.symbols('t s') # Any function may be used to test the model, however some topologies may cause numerical problems if too many points is # placed on a symptotically converging region. This is due to the ZeroDivisions errors in Aitkens iterations ( currently # this is handeled by applying A= +/- infinity) F = sym.exp(t) # apply the selected complex numbers to test on the transfer function i.e. omega*i omega = np.logspace(-2, 4, num=50) # Since F is given symbolically, then the exact result can be derived by differential calculus L_F = sym.laplace_transform(F, t, s)[0] L_F_approx = sym.lambdify(s, L_F) analytical_solution = L_F_approx( np.array([complex(0, omega[i]) for i in range(len(omega))])) # Here, the numerical approximate begins, by taking creating a time series, of t and f(t) respectively T = np.array(mp.linspace(0, 30, series_Length)) F_approx = sym.lambdify(t, F, 'mpmath') F_t = [0] * len(T) for i in range(len(T)): F_t[i] = F_approx(T[i]) F_t = np.array(F_t) time_calc = time.time()
y = sympy.Function("y") # In[59]: ode = y(t).diff(t, 2) + 2 * y(t).diff(t) + 10 * y(t) - 2 * sympy.sin(3*t) # In[60]: ode # In[61]: L_y = sympy.laplace_transform(y(t), t, s) # In[62]: L_y # In[63]: L_ode = sympy.laplace_transform(ode, t, s, noconds=True) # In[64]: L_ode
x, t, s, D, H = sm.symbols('x t s D H') mu1, mu2 = sm.symbols('mu:2') eta2 = sm.symbols('eta2') nmax = 5 n = sm.symbols('n') # dummy summation variable b = sm.Function('b')(t) b = 1 gamma = (mu1 - mu2) / (mu1 + mu2) #W = 1/sm.pi*(sm.atan((D + 2*n*H)/x) + sm.atan((D - 2*n*H)/x)) W = sm.Function('W')(n) u_elastic = b * (sm.Rational(1, 2) * W.subs(n, 0) + sm.summation(gamma**n * W, (n, 1, nmax))) uhat_elastic = sm.laplace_transform(u_elastic, t, s)[0] mu2hat = s / ((s / mu2) + (1 / eta2)) uhat = uhat_elastic.subs(mu2, mu2hat) uhat = uhat.subs(mu1, mu2) uv_1 = nth_derivative_at_zero(uhat, s, 4).expand() sm.pprint(uv_1) ''' #bhat = sm.laplace_transform(b,t,s)[0] uhat = uhat.subs(mu2,mu1) u_final = (s*uhat).limit(s,0) u_viscous_2 = inverse_laplace_transform_series_expansion(uhat,s,t,nmax)
def expr_to_sys(expr, var, freq_space=False): s = var if freq_space else Dummy('s') tf = expr if freq_space else laplace_transform(expr, var, s, noconds=True) n, d = ratpoly_coeffs(tf * s, s) return signal.TransferFunction([*map(float, n)], [*map(float, d)])
#程序文件Pex8_12.py import sympy as sp import pylab as plt import numpy as np sp.var('t', positive=True) sp.var('s') #定义符号变量 sp.var('X,Y', cls=sp.Function) #定义符号函数 g = 40 * sp.sin(3 * t) Lg = sp.laplace_transform(g, t, s) eq1 = 2 * s**2 * X(s) + 6 * X(s) - 2 * Y(s) eq2 = s**2 * Y(s) - 2 * X(s) + 2 * Y(s) - Lg[0] eq = [eq1, eq2] #定义取拉氏变换后的代数方程组 XYs = sp.solve(eq, (X(s), Y(s))) #求像函数 Xs = XYs[X(s)] Ys = XYs[Y(s)] Xs = sp.factor(Xs) Ys = sp.factor(Ys) xt = sp.inverse_laplace_transform(Xs, s, t) yt = sp.inverse_laplace_transform(Ys, s, t) print("x(t)=", xt) print("y(t)=", yt) fx = sp.lambdify(t, xt, 'numpy') #转换为匿名函数 fy = sp.lambdify(t, yt, 'numpy') t = np.linspace(-5, 5, 100) plt.rc('text', usetex=True) plt.plot(t, fx(t), '*-k', label='$x(t)$') plt.plot(t, fy(t), '.-r', label='$y(t)$') plt.xlabel('$t$') plt.legend() plt.show()
from sympy import Symbol, laplace_transform t = Symbol('t') s = Symbol('s') f_of_t = t**3 #laplace transform of t^n is equal to n!/s^(n+1) print("f_of_t:", f_of_t) laplace_transform_f_of_x = laplace_transform(f_of_t, t, s) print("laplace_transform_f_of_x:", laplace_transform_f_of_x) """ f_of_t: t**3 laplace_transform_f_of_x: (6/s**4, 0, True) """
# (a) $\mathcal{L}\{1 + 2t - \frac{1}{3}t^4\}$ # # (b) $\mathcal{L}\{5e^{2t} - 3e^{-t}\}$ # # # **Solution/Code** # In[2]: t, s, a, b = sp.symbols('t s a b') print('Output:\n') # a eq1 = 1 + 2 * t - (1 / 3) * (t**4) display(a) display(sp.laplace_transform(eq1, t, s)[0]) # b eq2 = 5 * (sp.exp(2 * t)) - 3 * (sp.exp(-t)) display(b) display(sp.laplace_transform(eq2, t, s)[0]) # **Problem 2.** Find the Laplace transform of: # # (a) $6sin3t - 4cos5t$ # # (b) $2cosh2\theta - sinh3\theta$ # **Solution/Code** # In[3]:
display(eq_spring) eq_spring = sym.Eq(k*f_y_t + c*(sym.Derivative(f_y_t, t)) - m * (sym.Derivative(f_y_t, (t,2))), k*f_x_t + c*sym.Derivative(f_x_t, t)) display(eq_spring) # %% eq_spring_s = sym.Eq(k*f_y_i_s + c*s*f_y_i_s - m*s**2*f_y_i_s, k*f_x_i_s + c*s*f_x_i_s) display(eq_spring_s) # %% eq_spring_g = sym.Eq(f_g_i_s, (eq_spring_s.lhs / f_y_i_s).simplify() / (eq_spring_s.rhs / f_x_i_s).simplify()) display(eq_spring_g) # %% eq_spring = sym.Eq(-(x)*k - c*(sym.Derivative(x, t)), m * (sym.Derivative(x, (t,2)))) display(eq_spring) display(sym.laplace_transform(eq_spring.lhs - eq_spring.rhs, t, s)) # %% s = sym.symbols("s") w_n, z_n = sym.symbols("omega_n, zeta_n", positive=True) f_g_i_s = sym.Function("G_i")(s) eq_g_i_s = sym.Eq(f_g_i_s, (2*z_n*w_n*s + w_n**2) / (s**2 + 2*z_n*w_n*s + w_n**2)) display(eq_g_i_s) # %% g = sym.symbols("G") f_a_s = sym.Function("a")(s) f_b_s = sym.Function("b")(s) eq_g = sym.Eq(g, f_b_s / f_a_s) display(eq_g)
def cvtLaplace(timestring, lapstring): s, t = sp.symbols('s, t') expression = timestring.get() ans = sp.laplace_transform(expression, t, s) lapstring.set(ans[0])
import sympy as sp from sympy.abc import t,s from sympy import cos,sin f=2*(sin(t)*sin(3*t)) u=sp.laplace_transform(f,t,s,noconds=True) print("18MEC24006-DENNY JOHNSON P") print("The Laplcae Transform of the Given Function is:",u)
------- series: symbolic expression for the series expansion of the u(x) about x=0 ''' series = 0 # note that n goes up to N for n in range(N + 1): # sum each term in the taylor series expansion series += (nth_derivative_at_zero(uhat, s, n) * t**n) / sp.factorial(n) return series x, s = sp.symbols('x s') u = 3 * x**2 + 2 * x + 1 # test function uhat = sp.laplace_transform(u, x, s)[0] # test function laplace transform u_expansion = inverse_laplace_transform_series_expansion(uhat, s, x, 2) assert sp.simplify(u - u_expansion) == 0 ''' Maxwell viscoelastic 2D two layered earthquake model I am demonstrating here that the surface deformation resulting from viscous relaxation following an earthquake in a layered halfspace is, to first order, a linear function of the viscosities in each layer. Variables used x: distance from fault strike t: time D: locking depth of the fault H: thickness of the top layer mu1,mu2: shear modulus of the first and second layer
Nome do sript: laplace_001 Disponível em: https://github.com/DenisCosta/PYTHON_MATHEMATICAL-MODELING/blob/master/ LAPLACE/laplace_001.py """ # Biblioteca sympy # Variáveis envolvidas: t e s import sympy as sy t = sy.Symbol('t') s = sy.Symbol('s') # Função Definida no Domínio do Tempo f1 = sy.exp(2 * t) # Aplicando a Transformando a Laplace T_L = sy.laplace_transform(f1, t, s) # Dados de Saída print('===========================') print('Função Primitiva -->', f1) print('') sy.pprint('Função Primitiva: ', f1) print('\n f(t) = e**(2t) \n') print('') print('Tranformada de Laplace -->', T_L) print('Tranformada de Laplace:') sy.pprint(T_L)
print() # %% # Example 2 print("Example 2") print() A, s, t = sympy.symbols(['A', 's', 't']) ft = A print("f(t)=\n{}".format(sympy.pretty(ft))) print() Fs = sympy.laplace_transform(ft, t, s) print("F(s)=\n{}".format(sympy.pretty(Fs))) print() # %% # Example 3 print("Example 3") print() A, s, t = sympy.symbols(['A', 's', 't']) ft = A * t print("f(t)=\n{}".format(sympy.pretty(ft)))
#程序文件Pex8_11.py import sympy as sp sp.var('t',positive=True); sp.var('s') #定义符号变量 sp.var('Y',cls=sp.Function) #定义符号函数 g=4*t*sp.exp(t) Lg=sp.laplace_transform(g,t,s) #方程右端项的拉氏变换 d=s**4*Y(s)+2*s**2*Y(s)+Y(s) de=d-Lg[0] #定义取拉氏变换后的代数方程 Ys=sp.solve(de,Y(s))[0] #求像函数 Ys=sp.factor(Ys) yt=sp.inverse_laplace_transform(Ys,s,t) print("y(t)=",yt); yt=yt.rewrite(sp.exp) #这里的变换只是为了把解化成指数函数,并且不出现虚数 yt=yt.as_real_imag(); print("y(t)=",yt) yt=sp.simplify(yt[0]); print("y(t)=",yt)