def ctrl_ilt(expr): ilt = 0 expanded = sym.apart(expr).as_ordered_terms() print('Expanded this is ', expanded) for term in expanded: print('Terms are ', term) print(sym.inverse_laplace_transform(term, s, t)) ilt += sym.inverse_laplace_transform(term, s, t) return ilt
def il(): F = (2 * s**2 + 3 * s - 1) / ((s**2 - 2 * s + 2) * (s - 1)) t1 = time.time() ft2 = inverse_laplace_transform(F, s, t) t2 = time.time() print(t2 - t1) print(ft2)
def message(): posted_data = request.get_json() name = posted_data['equation'] fff1=eval(name) #fff=sp.parsing.sympy_parser.parse_expr(name) ttt=sp.inverse_laplace_transform(fff1,s,t).evalf().simplify() return jsonify(str(ttt))
def response(steps, waveforms, gain=14.0, shape_time=1.0, **kwds): print shape_time if len(waveforms) == 0: return list() A0 = gain #mV/fC tP = shape_time #us CT = 1 / 1.996 den = tP * CT CA = 2.7433 / den**4 p0 = 1.477 / den pi1, pi2 = 0.598 / den, 1.299 / den pr1, pr2 = 1.417 / den, 1.204 / den # find step width wvf = waveforms[0].data step = wvf[1][0] - wvf[0][0] s, t = sp.symbols('s, t') expr = (A0 * CA) / ((p0 + s) * (pi1**2 + (pr1 + s)**2) * (pi2**2 + (pr2 + s)**2)) sol = sp.inverse_laplace_transform(expr, s, t) ts = [n for n in np.arange(step, 5 * tP, step)] ys = [sp.functions.re(sol.subs(t, tick)) for tick in ts] steps = [s for s in steps if s.name != 'vtxs'] assert len(steps) == len(waveforms) start = [None for s in steps] end, arrays = list(start), list(start) count = 0 for step, wvf in zip(steps, waveforms): if step.name == 'vtxs': continue print 'Calculating response for', step.name wvf = wvf.data[:, 1] # we don't want to normalize bipolar pulses # normalize to 1 fC so current is in nA #if do_norm(wvf): # wvf *= chg / abs(np.sum(wvf)*step) #wvf = list(wvf) # ## convolve #conv = sp.convolution(wvf, ys, dps=2) #conv = np.asarray([sp.functions.re(x) for x in conv]) start[count] = step.data[0, 0:3] end[count] = step.data[-1, 0:3] arrays[count] = wvf #conv count += 1 return [ Array(name='start_points', typename='tuples', data=np.asarray(start)), Array(name='end_points', typename='tuples', data=np.asarray(end)), Array(name='responses', typename='tuples', data=np.asarray(arrays)) ]
def zoh_discretization(t, k, s, z, T, P): pfe = sp.apart(P / s) terms = pfe.args if isinstance(pfe, sp.Add) else [pfe] terms = [ sp.inverse_laplace_transform(term, s, t).subs(t, k * T) for term in terms ] terms = [term.subs(sp.Heaviside(T * k), 1) for term in terms] return (z - 1) / z * z_transform(k, z, sum(terms))
def inverse(): F = 280 / (s**2 + 14 * s + 245) F2 = (-s**2 + 52 * s + 445) / (s**3 + 10 * s**2 + 89) print("begin") t1 = time.time() #ft = inverse_laplace_transform(F,s,t) ft2 = inverse_laplace_transform(F2, s, t) #print(ft) t2 = time.time() print(t2 - t1) print(ft2)
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_inverse_laplace_transform(self): t, s = sympy.symbols('t, s') try: F = sympy.parsing.sympy_parser.parse_expr( self.line_exp_state.text()) f = sympy.inverse_laplace_transform(F, s, t, 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_time.setText(str(f))
def callback(q, f = '', a = 0, b = 0, L = [], kind = 1): ans = '' if kind == 1: ans = str(sp.fft(L)) # Discrete Fourier Transform elif kind == 2: ans = str(sp.ifft(L)) # Inverse Discrete Fourier Transform elif kind == 3: ans = str(sp.ntt(L, prime=3 * 2 ** 8 + 1)) # Performs the Number Theoretic Transform (NTT) elif kind == 4: ans = str(sp.intt(L, prime=3 * 2 ** 8 + 1)) # Performs the Inverse Number Theoretic Transform (NTT) elif kind == 5: ans = str(sp.fwht( L)) # Performs the Walsh Hadamard Transform (WHT), and uses Hadamard ordering for the sequence. elif kind == 6: ans = str(sp.ifwht( L)) # Performs the Inverse Walsh Hadamard Transform (WHT), and uses Hadamard ordering for the sequence. elif kind == 7: ans = functions.math_display(str(sp.mellin_transform(f, x, s))) # Mellin Transform elif kind == 8: ans = functions.math_display( str(sp.inverse_mellin_transform(f, s, x, (a, b)))) # Inverse Mellin Transform elif kind == 9: from sympy import sin, cos, tan, exp, gamma, sinh, cosh, tanh ans = functions.math_display(str(functions.Laplace_Transform(f))) # Laplace Transform elif kind == 10: ans = functions.math_display(str(sp.inverse_laplace_transform(f, s, t))) # Inverse Laplace Transform elif kind == 11: ans = functions.math_display(str(functions.Fourier_Transform(f, a, b))) # Fourier Transform elif kind == 12: ans = functions.math_display(str(sp.inverse_fourier_transform(f, w, x))) # Invese Fourier Transform elif kind == 13: ans = functions.math_display(str(sp.sine_transform(f, x, w))) # Fourier Sine Transform elif kind == 14: ans = functions.math_display(str(sp.inverse_sine_transform(f, w, x))) # Inverse Fourier Sine Transform elif kind == 15: ans = functions.math_display(str(sp.cosine_transform(f, x, w))) # Fourier Cosine Transform elif kind == 16: ans = functions.math_display( str(sp.inverse_cosine_transform(f, w, x))) # Inverse Fourier Cosine Transform elif kind == 17: ans = functions.math_display(str(sp.hankel_transform(f, r, w, 0))) # Hankel Transform elif kind == 18: ans = functions.math_display(str(sp.inverse_hankel_transform(f, w, r, 0))) # Inverse Hankel Transform q.put(ans)
#! /usr/bin/env python3 import sympy as sp 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 pi = sp.pi expression = 1 / (s**2*(s**2 + 1)) out = sp.inverse_laplace_transform(expression, s, x) print(out)
def invL(F): return sympy.inverse_laplace_transform(F, s, t)
plt.ylabel('Angle (rad)') plt.grid() plt.show() # DETERMINE THE IMPULSE RESPONSE OF THE SYSTEM (kick) # F(s) = 1, X1(s) = G_x, x1(t) = inv_lap(x1) x1_t = sym.inverse_laplace_transform(G_x, s, t) print(sym.latex(x1_t)) sym.pprint(G_x) # unfortunately I seem to be getting a bad result here as it cannot be computed in the # c.impulse_response() # DETERMINE THE STEP RESPONSE OF THE SYSTEM (push) x3_step_t = sym.inverse_laplace_transform(G_x/s, s, t) sym.pprint(x3_step_t) print(sym.latex(x3_step_t)) ''' # DETERMINE THE FREQUENCY RESPONSE OF THE SYSTEM (shake) w = sym.symbols('w', real=True, positive=True) x3_freq_t = sym.inverse_laplace_transform(G_x * w**2 / (s**2 + w**2), s, t) sym.pprint(x3_freq_t.simplify()) print(sym.latex(x3_freq_t)) ''' t_imp, x3_imp = C.impulse_response(G_x) plt.plot(t_imp, x3_imp) plt.xlabel('Time (s)') plt.ylabel('Angle (rad)') plt.grid() plt.show() '''
b2 = psi_deriv_x3_at_equlibrium b3 = psi_deriv_V_at_equlibrium s, t = sym.symbols('s, t') a1, a2, a3, b1, b2, b3 = sym.symbols('a1, a2, a3, b1, b2, b3', real=True, positive=True) # Define G_theta G_theta = 1 / b1 * (((-b1 * x1) - (b3 * V)) / V) F_s_impulse = 1 F_s_step = 1 / s X1_s_impulse_G_theta = G_theta * F_s_impulse x1_t_impulse_G_theta = sym.inverse_laplace_transform(X1_s_impulse_G_theta, s, t) X1_s_step_G_theta = G_theta * F_s_step x1_t_step_G_theta = sym.inverse_laplace_transform(X1_s_step_G_theta, s, t) n_points = 500 t_final = 50 t_span = np.linspace(0, t_final, n_points) # Print the symbolic expressions sym.pprint(x1_t_impulse_G_theta.simplify()) sym.pprint(x1_t_step_G_theta.simplify()) plt.plot(x1_t_impulse_G_theta, t_span) plt.plot(x1_t_step_G_theta, t_span) plt.show()
import sympy as sp sp.init_printing() s = sp.Symbol('s') T = sp.Symbol('T', real=True) P = 1 / ((1 + T * s) * s) aparted_P = sp.apart(P, s) print(aparted_P) t = sp.Symbol('t', positive=True) inv_lap_transformed = sp.inverse_laplace_transform((1 / s) - 1 / (s + 1 / T), s, t) print(inv_lap_transformed)
def cvtTime(timestring, lapstring): s, t = sp.symbols('s, t') expression = lapstring.get() ans = sp.inverse_laplace_transform(expression, s, t) timestring.set(str(ans))
Y_sol = sympy.solve(L_ode_4, Y) # In[75]: Y_sol # In[76]: sympy.apart(Y_sol[0]) # In[77]: y_sol = sympy.inverse_laplace_transform(Y_sol[0], s, t) # In[78]: sympy.simplify(y_sol) # In[79]: y_t = sympy.lambdify(t, y_sol, 'numpy') # In[80]: fig, ax = plt.subplots(figsize=(8, 4))
import sympy as sp sp.init_printing() s = sp.Symbol('s') t = sp.Symbol('t', positive=True) w = sp.Symbol('w', real=True) p1 = sp.Symbol('p1', real=True) p2 = sp.Symbol('p2', real=True) P = sp.apart(w**2 / (s * (s - p1) * (s - p2)), s) print(sp.inverse_laplace_transform(P, s, t))
return f.subs([(F, 0), (x3, 0), (x4, 0)]) dphi_F_eq = evaluate_at_eq(dphi_F) dphi_x3_eq = evaluate_at_eq(dphi_x3) dphi_x4_eq = evaluate_at_eq(dphi_x4) dz_F_eq = evaluate_at_eq(dz_F) dz_x3_eq = evaluate_at_eq(dz_x3) dz_x4_eq = evaluate_at_eq(dz_x4) a, b, c, d, w = sym.symbols('a:d, w', real=True, positive=True) s, t = sym.symbols('s, t') transfer_function_F_to_x3 = -c / (s**2 - d) F_impulse = 1 F_step = 1 / s F_freq = w / (w**2 + s**2) x3_t_impulse = sym.inverse_laplace_transform( transfer_function_F_to_x3 * F_impulse, s, t) x3_t_step = sym.inverse_laplace_transform(transfer_function_F_to_x3 * F_step, s, t) x3_t_freq = sym.inverse_laplace_transform(transfer_function_F_to_x3 * F_freq, s, t) sym.pprint(x3_t_impulse) sym.pprint(x3_t_step) sym.pprint(x3_t_freq)
# inverse of (sI - M) step by step print("*" * 180) print('Calculating inverse matrix...') s = sp.symbols('s') Ms = s * sp.eye(3) - M # sI - M Ms_det = sp.factor(Ms.det()).subs({w**2: ww**2}) Ms_com = Ms.cofactor_matrix() Ms_inv = Ms_com.transpose() / Ms_det print('(sI-M)^-1 =') # inverse laplace transform print("*" * 180) print('Calculating inverse laplace transform...') t, t0 = sp.symbols('t t_0', positive=True) exp_Mt = sp.inverse_laplace_transform(Ms_inv, s, t) print('exp(Mt) = L-1((sI-1)^-1)(t) =') sp.pprint(exp_Mt) # initial conditions X0 = sp.Matrix([0, 0, 1]) X1 = sp.Matrix([0, 1 / sp.sqrt(2), 1 / sp.sqrt(2)]) print("*" * 180) print('X = exp(Mt) * X0 =') sp.pprint(exp_Mt * X0) # define trajectory functions def numpify_x(x0, a_val=1, b_val=0, u_val=1): # substitute parameters with values w_val = np.sqrt(a_val**2 + b_val**2 + u_val**2)
#程序文件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()
omega = sym.symbols("w", real=True) inputs = [(1), (1 / s), (omega / (s ** 2 + omega ** 2))] lap_responses = [] responses = [] for G in transfers: lap_outputs = [] outputs = [] for F_lap_val in inputs: # Laplace Outputs lap_output = G * F_lap lap_output = lap_output.subs(F_lap, F_lap_val) lap_outputs.append(lap_output) # Time Domain Outputs output = (sym.inverse_laplace_transform(lap_output, s, t)).simplify() outputs.append(output) print(f"Transfer Function: {G} \nLaplace Input: {F_lap_val}" f"\nLaplace Output: {lap_output} \nTime Domain: {output}\n") lap_responses.append(lap_outputs) responses.append(outputs) print("LaTex Time Domain Outputs:") for r in responses: for o in r: print(f"\[{sym.latex(o)}\]\n") # Post Q3 # Constants substitutions = [(M, 0.3), (m, 0.1), (ell, 0.35), (g, 9.81)] a_val = evaluate_linearised_constants(answers_diff[0][0], substitutions)
s, t = sym.symbols('s, t', real=True, positive=True) a, b, c, d, = sym.symbols('a, b, c, d', real=True, positive=True) G_theta = -c / ( s**2 - d) # G_theta uses X3 as output variable and F(s) as input variable G_x = (-c * b + d * a - s**2) / ( -s**4 + d * s**2 ) # G_x uses X1 as output variable and F(s) as input variable F_s_impulse = 1 #use laplace transform to go from f(t) to f(s) and inverse to go f(s) to f(t) F_s_step = 1 / s # but must manually go from f(t) to f(s) F_s_frequency = w / (s**2 + w**2) # push: F_s = 1 / s X3_s_frequency = G_theta * F_s_frequency X3_s_step = G_theta * F_s_step X3_s_impulse = G_theta * F_s_impulse # shake: F_s = 1 / (s**2 + 1) this is the inverse laplace of sin(t) x3_t_impulse = sym.inverse_laplace_transform(X3_s_impulse, s, t, w) # kick: f_s = 1 x3_t_step = sym.inverse_laplace_transform(X3_s_step, s, t, w) x3_t_frequency = sym.inverse_laplace_transform(X3_s_frequency, s, t, w) X1_s_impulse = G_x * F_s_impulse X1_s_step = G_x * F_s_step X1_s_frequency = G_x * F_s_frequency x1_t_impulse = sym.inverse_laplace_transform(X1_s_impulse, s, t, w) x1_t_step = sym.inverse_laplace_transform(X1_s_step, s, t, w) x1_t_frequency = sym.inverse_laplace_transform(X1_s_frequency, s, t, w) #sym.pprint(x3_t.simplify()) #sym.pprint(x1_t_impulse.simplify()) sym.pprint(X1_s_frequency)
def invL(F,s,t): return sp.re(sp.inverse_laplace_transform(F, s, t, noconds=True))
# 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]: [sympy.laplace_transform(f, t, s, noconds=True) for f in [t, t**2, t**3, t**4]] # In[127]: n = sympy.symbols("n", integer=True, positive=True) # In[128]: sympy.laplace_transform(t**n, t, s, noconds=True) # In[129]:
def inverse_laplace_transform(function): return sym.inverse_laplace_transform(function, s, t)
if isinstance(e, (sympy.Add, sympy.Mul)): t = type(e) return t(*[laplace_transform_derivatives(arg) for arg in e.args]) return e L_ode_2 = laplace_transform_derivatives(L_ode) print(L_ode_2) L_ode_3 = L_ode_2.subs(L_y, Y) print(L_ode_3) ics = {y(0): 1, y(t).diff(t).subs(t, 0): 0} print(ics) L_ode_4 = L_ode_3.subs(ics) print(L_ode_4) Y_sol = sympy.solve(L_ode_4, Y) print(Y_sol) sympy.apart(Y_sol[0]) y_sol = sympy.inverse_laplace_transform(Y_sol[0], s, t) sympy.simplify(y_sol) y_t = sympy.lambdify(t, y_sol, 'numpy') fig, ax = plt.subplots(figsize=(8, 4)) tt = np.linspace(0, 10, 500) ax.plot(tt, y_t(tt).real) ax.set_xlabel(r"$t$", fontsize=18) ax.set_ylabel(r"$y(t)$", fontsize=18) fig.tight_layout() os.system("pause")
(s, sigma - sympy.I * sympy.oo, sigma + sympy.I * sympy.oo)) print("f(t)=\n{}".format(sympy.pretty(f))) print() # %% # Example 1 print("Example 1") s, t = sympy.symbols(['s', 't']) w = sympy.symbols('w', real=True) expr = 2 / ((s + 1) * (s + 2)) i_expr = sympy.inverse_laplace_transform(expr, s, t) i_expr = sympy.simplify(i_expr) i_expr = sympy.expand(i_expr) print(sympy.pretty(i_expr)) print() # %% # Example 2 print("Example 2") s, t = sympy.symbols(['s', 't']) expr = 2 / ((s + 1) * (s + 2)**2)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 28 20:30:41 2019 Todos estos códigos requieren comentarios y una limpieza Limpio=NO Comentarios=NO @author: carlos """ import control as ct import sympy as sym import numpy as np import matplotlib.pyplot as plt from scipy import signal from matplotlib.ticker import (MultipleLocator) s, t = sym.symbols('s, t') t = sym.symbols( 't', positive=True ) ##Si lo quitas aparece la función heaviside, positive implica real. G = 1 / (s * (s + 1) * (s + 5)) G = sym.inverse_laplace_transform(G, s, t) sym.pprint(G)
def TransformSystemsDynamicsMatrix(F): MatrixSize = F.shape[0] temp = s*sympy.eye(MatrixSize)-F #sI-F temp_inv = temp.inv() invLaplace = sympy.inverse_laplace_transform(temp_inv, s, t) return invLaplace
from scipy.signal import lti from scipy.fftpack import fft, fftfreq, fftshift # Commented out IPython magic to ensure Python compatibility. # %matplotlib inline import sympy as sym sym.init_printing() s = sym.symbols('s', complex=True) t, R1, R2, C = sym.symbols('t R1 R2 C', positive=True) X = sym.Function('X')(s) Y = (1 / (R2 * C)) / (s + ((R2 + R1) / (R1 * R2 * C))) * X y = sym.inverse_laplace_transform(Y.subs(X, 1), s, t) Y, y R1 = 1 R2 = 2 C = 0.4 A = 1 / (R2 * C) num = [A] den = [1, ((R2 + R1) / (R1 * R2 * C))] G = lti(num, den) tv, h = G.impulse(N=5000) #se genera la respuesta impulso del sistema plt.plot(tv, h, label='$h(t)$') #se gráfica la respuesta impulso plt.grid(True)
def invL(F): return sympy.inverse_laplace_transform(F, s, t)
s, t = sym.symbols('s, t') w = sym.symbols('w', real=True) # w = omega a, b, c, d = sym.symbols('a, b, c, d', real=True, positive=True) # Define G_theta and G_x symbolically G_theta = - c / (s**2 - d) G_x = ((a * s**2) - (a * d) + (b * c)) / (s**4 - (d * s**2)) # Impulse, Step and Frequency response of G_theta and G_x # Push/Step: F_s = 1 / s Shake/Frequency: F_s = w / (s**2 + w**2) Kick (Dirac pulse)/Impulse: F_s = 1 F_s_impulse = 1 F_s_step = 1 / s F_s_frequency = w / (s**2 + w**2) X3_s_impulse_G_theta = G_theta * F_s_impulse x3_t_impulse_G_theta = sym.inverse_laplace_transform(X3_s_impulse_G_theta, s, t) X3_s_step_G_theta = G_theta * F_s_step x3_t_step_G_theta = sym.inverse_laplace_transform(X3_s_step_G_theta, s, t) X3_s_frequency_G_theta = G_theta * F_s_frequency x3_t_frequency_G_theta = sym.inverse_laplace_transform(X3_s_frequency_G_theta, s, t, w) X1_s_impulse_G_x = G_x * F_s_impulse x1_t_impulse_G_x = sym.inverse_laplace_transform(X1_s_impulse_G_x, s, t) X1_s_step_G_x = G_x * F_s_step x1_t_step_G_x = sym.inverse_laplace_transform(X1_s_step_G_x, s, t) X1_s_frequency_G_x = G_x * F_s_frequency x1_t_frequency_G_x = sym.inverse_laplace_transform(X1_s_frequency_G_x, s, t, w)