def _n_Z(Omega, c10, Dt, loc_q, loc_ym, loc_yp, loc_alcc, loc_alss, loc_bsc, loc_bcs): arg1 = cmath.sqrt(2.0*loc_yp)/2.0/Dt/c10 arg2 = cmath.sqrt(2.0*loc_ym)/2.0/Dt/c10 return ((loc_alcc*cmath.cosh(arg1)*cmath.cosh(arg2) + loc_alss*cmath.sinh(arg1)*cmath.sinh(arg2) + loc_q)/ (loc_bsc*cmath.sinh(arg1)*cmath.cosh(arg2) + loc_bcs*cmath.cosh(arg1)*cmath.sinh(arg2)))
def test_cosh(self): self.assertAlmostEqual(qmath.cosh(self.f1), math.cosh(self.f1)) self.assertAlmostEqual(qmath.cosh(self.c1), cmath.cosh(self.c1)) self.assertAlmostEqual(qmath.cosh(self.c2), cmath.cosh(self.c2)) self.assertAlmostEqual(qmath.cosh(Quat(self.f1)), math.cosh(self.f1)) self.assertAlmostEqual(qmath.cosh(Quat(0, 3)), cmath.cosh(3J)) self.assertAlmostEqual(qmath.cosh(Quat(4, 5)), cmath.cosh(4 + 5J)) self.assertAlmostEqual(qmath.cosh(Quat(0, self.f1)), Quat(math.cos(self.f1)))
def _N11(Omega, c10, j0, Dt, loc_t, loc_ym, loc_yp, loc_gcm, loc_gcp, loc_gsm, loc_gsp): twoDtc10 = 2.0*Dt*c10 return (2.0*cmath.sqrt(2.0*loc_t)*c10*j0*(cmath.sqrt(loc_ym)*cmath.sinh(cmath.sqrt(2.0*loc_ym)/twoDtc10) - cmath.sqrt(loc_yp)*cmath.sinh(cmath.sqrt(2.0*loc_yp)/twoDtc10))/ (loc_gcm*cmath.cosh(cmath.sqrt(2.0*loc_ym)/twoDtc10) + loc_gcp*cmath.cosh(cmath.sqrt(2.0*loc_yp)/twoDtc10) + loc_gsm*cmath.sinh(cmath.sqrt(2.0*loc_ym)/twoDtc10) + loc_gsp*cmath.sinh(cmath.sqrt(2.0*loc_yp)/twoDtc10)))
def cosh(c): """Compute Cosh using a Taylor expansion """ if not isinstance(c,pol): return math.cosh(c) a0,p=c.separate(); lst=[math.cosh(a0),math.sinh(a0)] for n in range(2,c.order+1): lst.append( lst[-2]/n/(n-1)) return phorner(lst,p)
def test_cosh_cc (self): src_data = [complex(i,i+1) for i in range(-5, 5, 2)] expected_result = tuple(cmath.cosh(i) for i in src_data) src = gr.vector_source_c(src_data) op = gr.transcendental('cosh', 'complex_float') snk = gr.vector_sink_c() self.tb.connect(src, op, snk) self.tb.run() result = snk.data() self.assertComplexTuplesAlmostEqual(expected_result, result, places=5)
def cosh(*args, **kw): arg0 = args[0] if isinstance(arg0, (int, float, long)): return _math.cosh(*args,**kw) elif isinstance(arg0, complex): return _cmath.cosh(*args,**kw) elif isinstance(arg0, _sympy.Basic): return _sympy.cosh(*args,**kw) else: return _numpy.cosh(*args,**kw)
def test_complex_functions(): for x in (list(range(10)) + list(range(-10,0))): for y in (list(range(10)) + list(range(-10,0))): z = complex(x, y)/4.3 + 0.01j assert exp(mpc(z)).ae(cmath.exp(z)) assert log(mpc(z)).ae(cmath.log(z)) assert cos(mpc(z)).ae(cmath.cos(z)) assert sin(mpc(z)).ae(cmath.sin(z)) assert tan(mpc(z)).ae(cmath.tan(z)) assert sinh(mpc(z)).ae(cmath.sinh(z)) assert cosh(mpc(z)).ae(cmath.cosh(z)) assert tanh(mpc(z)).ae(cmath.tanh(z))
def oneArgFuncEval(function, value): # Evaluates functions that take a complex number input if function == "sin": return cmath.sin(value) elif function == "cos": return cmath.cos(value) elif function == "tan": return cmath.tan(value) elif function == "asin": return cmath.asin(value) elif function == "acos": return cmath.acos(value) elif function == "atan": return cmath.atan(value) elif function == "csc": return 1.0 / cmath.sin(value) elif function == "sec": return 1.0 / cmath.cos(value) elif function == "cot": return 1.0 / cmath.tan(value) elif function == "ln": return cmath.log(value) elif function == "sqr": return cmath.sqrt(value) elif function == "abs": return cmath.sqrt((value.real ** 2) + (value.imag ** 2)) elif function == "exp": return cmath.exp(value) if function == "sinh": return cmath.sinh(value) elif function == "cosh": return cmath.cosh(value) elif function == "tanh": return cmath.tanh(value) elif function == "asinh": return cmath.asinh(value) elif function == "acosh": return cmath.acosh(value) elif function == "atanh": return cmath.atanh(value) elif function == "ceil": return math.ceil(value.real) + complex(0, 1) * math.ceil(value.imag) elif function == "floor": return math.floor(value.real) + complex(0, 1) * math.floor(value.imag) elif function == "trunc": return math.trunc(value.real) + complex(0, 1) * math.trunc(value.imag) elif function == "fac": if value.imag == 0 and value < 0 and value.real == int(value.real): return "Error: The factorial function is not defined on the negative integers." return gamma(value + 1) elif function == "log": return cmath.log10(value)
def setTransmission(self, gl, Z0): ''' gl = l*gamma l = length gamma = a + j*b a - attenuation constant b - phase constant Z0 - characteristic impedance ''' ch = cmath.cosh(gl) sh = cmath.sinh(gl) self.a = np.array( [ [ch, sh*Z0], [sh/Z0, ch] ]); pass
def cosh(x): """ Return the hyperbolic cosine of x. """ if isinstance(x,ADF): ad_funcs = list(map(to_auto_diff,[x])) x = ad_funcs[0].x ######################################## # Nominal value of the constructed ADF: f = cosh(x) ######################################## variables = ad_funcs[0]._get_variables(ad_funcs) if not variables or isinstance(f, bool): return f ######################################## # Calculation of the derivatives with respect to the arguments # of f (ad_funcs): lc_wrt_args = [sinh(x)] qc_wrt_args = [cosh(x)] cp_wrt_args = 0.0 ######################################## # Calculation of the derivative of f with respect to all the # variables (Variable) involved. lc_wrt_vars,qc_wrt_vars,cp_wrt_vars = _apply_chain_rule( ad_funcs,variables,lc_wrt_args,qc_wrt_args, cp_wrt_args) # The function now returns an ADF object: return ADF(f, lc_wrt_vars, qc_wrt_vars, cp_wrt_vars) else: # try: # pythonic: fails gracefully when x is not an array-like object # return [cosh(xi) for xi in x] # except TypeError: if x.imag: return cmath.cosh(x) else: return math.cosh(x.real)
def __init__(self, Var_txt, count_plot, name): self.Var = dict() for var in Var_txt: if var[0] == "comp": self.Var[var[0]] = [] for i in range(1,len(var)): self.Var[var[0]].append(float(var[i])/100) else: self.Var[var[0]] = float(var[1]) self.file_name = name self.r = self.Var["r"] self.L = self.Var["L"] self.C = self.Var["C"] self.g = self.Var["g"] self.l = self.Var["l"] self.V1 = self.Var["V1"] self.Vb = self.V1 self.Sb = 100e6 self.fp = self.Var["fp"] self.f = self.Var["f"] self.prec = self.Var["prec"] self.w = 2 * cm.pi * self.f self.count_plot = count_plot self.U1 = self.V1 / cm.sqrt(3).real self.Z = (self.r + 1j * self.w * self.L) * self.l self.Y = (self.g + 1j * self.w * self.C) * self.l self.Zc = cm.sqrt(self.Z / self.Y) self.gamal = cm.sqrt(self.Z * self.Y) self.A = cm.cosh(self.gamal) self.B = self.Zc * cm.sinh(self.gamal) self.C = 1 / self.Zc * cm.sinh(self.gamal) self.D = self.A self.result = self.calc_Vr(self.A, self.B) self.result2 = self.compSeM() self.result3 = self.compSeEx() #self.ang_pot = self.calc_ang_pot(self.A,self.B,np.array(self.result[0])/3,np.array(self.result[1])/np.sqrt(3)) self.plot_all_Vr()
def do_transfer_function(length,freq,type=3, measure="m"): ''' Let the transfer function default to type 3; Allows for easy default change later Allows for easy 'case-based' changes ''' ''' Z=impedance/l, Y=admittance/l Z=R+jwL, Y=G+jwC Z0=Characteristic Impedence, gamma=propagation constant Z0=sqrt(Z/Y), gamma=sqrt(Z*Y) Should Use PyGSL, but start off with cmath ''' #Length must be in KM if measure == "m": length /= 1000 elif measure == "km": pass else: raise TypeError('Improper measurement scale used') w = 2 * pi * freq #log.debug("Freq=%f,Len=%d",freq,length) Z = complex(_R(freq),w*_L(freq)) Y = complex(_G(freq),w*_C(freq)) Z0 = cmath.sqrt(Z/Y) gamma = cmath.sqrt(Z*Y) gammad=gamma*length Zs = complex(100,0) Zl = complex(100,0) upper = Z0 * ( 1/cmath.cosh(gammad)) #sech=1/cosh lower = Zs * ( (Z0/Zl) + cmath.tanh(gammad) ) + Z0 * ( 1+ (Z0/Zl)*cmath.tanh(gammad) ) H = upper/lower H*=H return cmath.polar(H)[0] #polar returns (abs(h),real(h))
def exp_mat2_full_scalar(X, t, exp_Xt): s = 0.5 * (X[0,0] + X[1,1]) det_X_minus_sI = (X[0,0]-s) * (X[1,1]-s) - X[0,1] * X[1,0] q = cmath.sqrt(-det_X_minus_sI) # we have to distinguish the case q=0 (the other exceptional case t=0 should not occur) if abs(q) < 1e-15: # q is (numerically) 0 sinh_qt_over_q = t else: sinh_qt_over_q = cmath.sinh(q*t) / q cosh_qt = cmath.cosh(q*t) cosh_q_t_minus_s_sinh_qt_over_qt = cosh_qt - s*sinh_qt_over_q exp_st = cmath.exp(s*t) # abbreviations for the case of exp_Xt referencing the same array as X E_00 = exp_st * (cosh_q_t_minus_s_sinh_qt_over_qt + sinh_qt_over_q * X[0,0]) E_01 = exp_st * (sinh_qt_over_q * X[0,1]) E_10 = exp_st * (sinh_qt_over_q * X[1,0]) E_11 = exp_st * (cosh_q_t_minus_s_sinh_qt_over_qt + sinh_qt_over_q * X[1,1]) exp_Xt[0,0] = E_00 exp_Xt[0,1] = E_01 exp_Xt[1,0] = E_10 exp_Xt[1,1] = E_11
print('arc sine =', cmath.asin(c)) print('arc cosine =', cmath.acos(c)) print('arc tangent =', cmath.atan(c)) print('sine =', cmath.sin(c)) print('cosine =', cmath.cos(c)) print('tangent =', cmath.tan(c)) # hyperbolic functions c = 2 + 2j print('inverse hyperbolic sine =', cmath.asinh(c)) print('inverse hyperbolic cosine =', cmath.acosh(c)) print('inverse hyperbolic tangent =', cmath.atanh(c)) print('hyperbolic sine =', cmath.sinh(c)) print('hyperbolic cosine =', cmath.cosh(c)) print('hyperbolic tangent =', cmath.tanh(c)) # classification functions print(cmath.isfinite(2 + 2j)) # True print(cmath.isfinite(cmath.inf + 2j)) # False print(cmath.isinf(2 + 2j)) # False print(cmath.isinf(cmath.inf + 2j)) # True print(cmath.isinf(cmath.nan + 2j)) # False print(cmath.isnan(2 + 2j)) # False print(cmath.isnan(cmath.inf + 2j)) # False print(cmath.isnan(cmath.nan + 2j)) # True
def rpn_calc(input, angle_mode = 0): global stack single_arg_funcs = ['exp','sqrt','sin','asin','cos','acos','tan','atan', 'sinh','asinh','cosh','acosh','tanh', 'atanh','!', 'polar'] num, arg, option = parse(input) #print(num, arg, option) #print('\n') if arg == None and (num != None or num != 'Error'): config.stack.append(num) history.append('Entered number: ' + str(num) ) return config.stack # Simple arithmatic----------------------------------------------------------------------- if option == None and num != None: if arg not in single_arg_funcs: last = config.stack.pop() if arg == '+': try: result = Decimal(last) + Decimal(num) hist = str(last) + '+' + str(num) + '=' + str(result) except TypeError: result = last + num hist = str(last) + '+' + str(num) + '=' + str(result) if arg == '-': try: result = Decimal(last) - Decimal(num) hist = str(last) + '-' + str(num) + '=' + str(result) except TypeError: result = last - num hist = str(last) + '-' + str(num) + '=' + str(result) if arg == '*': try: result = Decimal(last) * Decimal(num) hist = str(last) + '*' + str(num) + '=' + str(result) except TypeError: result = last * num hist = str(last) + '*' + str(num) + '=' + str(result) if arg == '/': try: result = Decimal(last) / Decimal(num) hist = str(last) + '/' + str(num) + '=' + str(result) except TypeError: result = last / num hist = str(last) + '/' + str(num) + '=' + str(result) if arg == '**': try: result = pow(Decimal(last), Decimal(num) ) hist = str(last) + '**' + str(num) + '=' + str(result) except TypeError: result = last ** num hist = str(last) + '**' + str(num) + '=' + str(result) if arg == 'rt': try: result = root(Decimal(last), Decimal(num) ) hist = str(last) + 'raised to 1 over ' + str(num) + '=' + str(result) except TypeError: result = root(last + num) hist = str(last) + 'raised to 1 over ' + str(num) + '=' + str(result) if arg == '%': try: result = Decimal(last) % Decimal(num) hist = str(last) + '%' + str(num) + '=' + str(result) except TypeError: result = last % num hist = str(last) + '%' + str(num) + '=' + str(result) if arg == '!': try: result = Decimal(math.factorial(num)) hist = str(num) + '!' + '=' + str(result) except TypeError: result = math.factorial(num) hist = str(num) + '!' + '=' + str(result) if arg == 'exp': try: result = math.exp(Decimal(num)) hist = str(num) + 'exp' + '=' + str(result) except ValueError: result = cmath.exp(Decimal(num)) hist = str(num) + 'exp' + '=' + str(result) except TypeError: result = cmath.exp(num) hist = str(num) + 'exp' + '=' + str(result) if arg == 'sqrt': try: result = math.sqrt(Decimal(num)) hist = str(num) + 'sqrt' + '=' + str(result) except ValueError: result = cmath.sqrt(Decimal(num)) hist = str(num) + 'sqrt' + '=' + str(result) except TypeError: result = cmath.sqrt(num) hist = str(num) + 'sqrt' + '=' + str(result) if arg == 'log': try: result = math.log10(Decimal(num)) hist = str(num) + 'log10' + '=' + str(result) except ValueError: result = cmath.log10(Decimal(num)) hist = str(num) + 'log10' + '=' + str(result) except TypeError: result = cmath.log10(num) hist = str(num) + 'log10' + '=' + str(result) #================================= if arg == 'ln': try: result = math.log(Decimal(num)) hist = str(num) + 'ln' + '=' + str(result) except ValueError: result = cmath.log(Decimal(num)) hist = str(num) + 'ln' + '=' + str(result) except TypeError: result = cmath.log(num) hist = str(num) + 'ln' + '=' + str(result) #--------TRIG-------------------------------- if arg == 'sin': if angle_mode == 1: try: result = math.sin(Decimal(num)) hist = 'sin' + str(num) + '=' + str(result) except TypeError: result = cmath.sin(num) hist = 'sin' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.sin(math.radians(Decimal(num))) hist = 'sin' + str(num) + '=' + str(result) except TypeError: result = cmath.sin(num) hist = 'sin' + str(num) + '=' + str(result) if arg == 'cos': if angle_mode == 1: try: result = math.cos(Decimal(num)) hist = 'cos' + str(num) + '=' + str(result) except TypeError: result = cmath.cos(num) hist = 'cos' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.cos(math.radians(Decimal(num))) hist = 'cos' + str(num) + '=' + str(result) except TypeError: result = cmath.cos(num) hist = 'cos' + str(num) + '=' + str(result) if arg == 'tan': if angle_mode == 1: try: result = math.tan(Decimal(num)) hist = 'tan' + str(num) + '=' + str(result) except TypeError: result = cmath.tan(num) hist = 'tan' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.tan(math.radians(Decimal(num))) hist = 'tan' + str(num) + '=' + str(result) except TypeError: result = cmath.tan(num) hist = 'tan' + str(num) + '=' + str(result) if arg == 'asin': if angle_mode == 1: try: result = math.asin(Decimal(num)) hist = 'asin' + str(num) + '=' + str(result) except TypeError: result = cmath.asin(num) hist = 'asin' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.asin(math.radians(Decimal(num))) hist = 'asin' + str(num) + '=' + str(result) except TypeError: result = cmath.asin(num) hist = 'asin' + str(num) + '=' + str(result) if arg == 'acos': if angle_mode == 1: try: result = math.acos(Decimal(num)) hist = 'acos' + str(num) + '=' + str(result) except TypeError: result = cmath.acos(num) hist = 'acos' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.acos(math.radians(Decimal(num))) hist = 'acos' + str(num) + '=' + str(result) except TypeError: result = cmath.acos(num) hist = 'acos' + str(num) + '=' + str(result) if arg == 'atan': if angle_mode == 1: try: result = math.atan(Decimal(num)) hist = 'atan' + str(num) + '=' + str(result) except TypeError: result = cmath.atan(num) hist = 'atan' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.atan(math.radians(Decimal(num))) hist = 'atan' + str(num) + '=' + str(result) except TypeError: result = cmath.atan(num) hist = 'atan' + str(num) + '=' + str(result) if arg == 'sinh': try: result = math.sinh(Decimal(num)) hist = 'sinh' + str(num) + '=' + str(result) except TypeError: result = cmath.sinh(num) hist = 'sinh' + str(num) + '=' + str(result) if arg == 'cosh': try: result = math.cosh(Decimal(num)) hist = 'cosh' + str(num) + '=' + str(result) except TypeError: result = cmath.cosh(num) hist = 'cosh' + str(num) + '=' + str(result) if arg == 'tanh': try: result = math.tanh(Decimal(num)) hist = 'tanh' + str(num) + '=' + str(result) except TypeError: result = cmath.tanh(num) hist = 'tanh' + str(num) + '=' + str(result) if arg == 'asinh': try: result = math.asinh(Decimal(num)) hist = 'asinh' + str(num) + '=' + str(result) except TypeError: result = cmath.asinh(num) hist = 'asinh' + str(num) + '=' + str(result) if arg == 'acosh': try: result = math.acosh(Decimal(num)) hist = 'acosh' + str(num) + '=' + str(result) except TypeError: result = cmath.acosh(num) hist = 'acosh' + str(num) + '=' + str(result) if arg == 'atanh': try: result = math.atanh(Decimal(num)) hist = 'atanh' + str(num) + '=' + str(result) except TypeError: result = cmath.atanh(num) hist = 'atanh' + str(num) + '=' + str(result) if arg == 'rect': #continue here.... try: result = rect(last, num) hist = 'Convert ' + str(last) + ',' + str(num) + ' to rectangular coords.' except TypeError: result = 'Error' hist = 'Error in attempted conversion to rectangular coords. No result.' if arg == 'polar': try: result = polar(num) hist = 'Convert ' + str(num) + ' to polar coords.' except TypeError: result = 'Error' hist = 'Error in attempted conversion to polar coords. No result.' config.stack.append(result) history.append(hist) return config.stack #======================================================================================================================= #----Only argument passed----------------------------------------------------------------------------------------------- #======================================================================================================================= elif option == None and num == None: last = config.stack.pop() if arg not in single_arg_funcs: try: n_minus1 = config.stack.pop() except IndexError: try: config.stack.append(Decimal(last)) except TypeError: config.stack.append(last) except TypeError: config.stack.append(last) except Exception as e: return 'Error' if arg == '+': try: result = Decimal(n_minus1) + Decimal(last) hist = str(n_minus1) + '+' + str(last) + '=' + str(result) except TypeError: result = n_minus1 + last hist = str(n_minus1) + '+' + str(last) + '=' + str(result) if arg == '-': try: result = Decimal(n_minus1) - Decimal(last) hist = str(n_minus1) + '-' + str(last) + '=' + str(result) except TypeError: result = n_minus1 - last hist = str(n_minus1) + '-' + str(last) + '=' + str(result) if arg == '*': try: result = Decimal(n_minus1) * Decimal(last) hist = str(n_minus1) + '*' + str(last) + '=' + str(result) except TypeError: result = n_minus1 * last hist = str(n_minus1) + '*' + str(last) + '=' + str(result) if arg == '/': try: result = Decimal(n_minus1) / Decimal(last) hist = str(n_minus1) + '/' + str(last) + '=' + str(result) except TypeError: result = n_minus1 / last hist = str(n_minus1) + '/' + str(last) + '=' + str(result) if arg == '!': try: result = Decimal(math.factorial(last)) hist = str(last) + '!' '=' + str(result) except TypeError: result = math.factorial(last) hist = str(last) + '!' '=' + str(result) except OverflowError: config.stack.append(last) hist = str('Factorial overflow error, no result.') return 'Error' if arg == '**': try: result = pow(Decimal(last), Decimal(last)) hist = str(n_minus1) + '**' + str(last) + '=' + str(result) except TypeError: result = last ** last hist = str(n_minus1) + '**' + str(last) + '=' + str(result) if arg == 'log': try: result = math.log10(Decimal(last)) hist = str(last) +'log10' + '=' + str(result) except ValueError: result = cmath.log10(Decimal(last)) hist = str(last) +'log10' + '=' + str(result) except TypeError: result = cmath.log10(last) hist = str(last) +'log10' + '=' + str(result) if arg == 'ln': try: result = math.log(Decimal(last)) hist = str(last) +'ln' + '=' + str(result) except ValueError: result = cmath.log(Decimal(last)) hist = str(last) +'ln' + '=' + str(result) except TypeError: result = cmath.log(last) hist = str(last) +'ln' + '=' + str(result) if arg == 'rt': try: result = root(Decimal(last), Decimal(n_minus1)) hist = str(n_minus1) + 'root' + str(last) + '=' + str(result) except TypeError: result = root(last), (n_minus1) hist = str(n_minus1) + 'root' + str(last) + '=' + str(result) if arg == 'exp': try: result = math.exp(Decimal(last)) hist = str(last) +'exp' + '=' + str(result) except TypeError: result = cmath.exp(last) hist = str(last) +'exp' + '=' + str(result) if arg == 'sqrt': try: result = math.sqrt(Decimal(last)) hist = 'Square root of ' + str(last) + '=' + str(result) except ValueError: result = cmath.sqrt(Decimal(last)) hist = 'Square root of ' + str(last) + '=' + str(result) except TypeError: result = cmath.sqrt(last) hist = 'Square root of ' + str(last) + '=' + str(result) #----------Trig---------------------------------------- #--------TRIG-------------------------------- if arg == 'sin': if angle_mode == 1: try: result = math.sin(Decimal(last)) hist = 'sin' + str(last) + '=' + str(result) except TypeError: result = cmath.sin(last) hist = 'sin' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.sin(math.radians(Decimal(last))) hist = 'sin' + str(last) + '=' + str(result) except TypeError: result = cmath.sin(last) hist = 'sin' + str(last) + '=' + str(result) if arg == 'cos': if angle_mode == 1: try: result = math.cos(Decimal(last)) hist = 'cos' + str(last) + '=' + str(result) except TypeError: result = cmath.cos(last) hist = 'cos' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.cos(math.radians(Decimal(last))) hist = 'cos' + str(last) + '=' + str(result) except TypeError: result = cmath.cos(last) hist = 'cos' + str(last) + '=' + str(result) if arg == 'tan': if angle_mode == 1: try: result = math.tan(Decimal(last)) hist = 'tan' + str(last) + '=' + str(result) except TypeError: result = cmath.tan(last) hist = 'tan' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.tan(math.radians(Decimal(last))) hist = 'tan' + str(last) + '=' + str(result) except TypeError: result = cmath.tan(last) hist = 'tan' + str(last) + '=' + str(result) if arg == 'asin': if angle_mode == 1: try: result = math.asin(Decimal(last)) hist = 'asin' + str(last) + '=' + str(result) except TypeError: result = cmath.asin(last) hist = 'asin' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.asin(math.radians(Decimal(last))) hist = 'asin' + str(last) + '=' + str(result) except TypeError: result = cmath.asin(last) hist = 'asin' + str(last) + '=' + str(result) if arg == 'acos': if angle_mode == 1: try: result = math.acos(Decimal(last)) hist = 'acos' + str(last) + '=' + str(result) except TypeError: result = cmath.acos(last) hist = 'acos' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.acos(math.radians(Decimal(last))) hist = 'acos' + str(last) + '=' + str(result) except TypeError: result = cmath.acos(last) hist = 'acos' + str(last) + '=' + str(result) if arg == 'atan': if angle_mode == 1: try: result = math.atan(Decimal(last)) hist = 'atan' + str(last) + '=' + str(result) except TypeError: result = cmath.atan(last) hist = 'atan' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.atan(math.radians(Decimal(last))) hist = 'atan' + str(last) + '=' + str(result) except TypeError: result = cmath.atan(last) hist = 'atan' + str(last) + '=' + str(result) if arg == 'sinh': try: result = math.sinh(Decimal(last)) hist = 'sinh' + str(last) + '=' + str(result) except TypeError: result = math.sinh(last) hist = 'sinh' + str(last) + '=' + str(result) if arg == 'cosh': try: result = math.cosh(Decimal(last)) hist = 'cosh' + str(last) + '=' + str(result) except TypeError: result = math.cosh(last) hist = 'cosh' + str(last) + '=' + str(result) if arg == 'tanh': try: result = math.tanh(Decimal(last)) hist = 'tanh' + str(last) + '=' + str(result) except TypeError: result = math.tanh(last) hist = 'tanh' + str(last) + '=' + str(result) if arg == 'asinh': try: result = math.asinh(Decimal(last)) hist = 'asinh' + str(last) + '=' + str(result) except TypeError: result = math.asinh(last) hist = 'asinh' + str(last) + '=' + str(result) if arg == 'acosh': try: result = math.acosh(Decimal(last)) hist = 'acosh' + str(last) + '=' + str(result) except TypeError: result = math.acosh(last) hist = 'acosh' + str(last) + '=' + str(result) if arg == 'atanh': try: result = math.atanh(Decimal(last)) hist = 'atanh' + str(last) + '=' + str(result) except TypeError: result = math.atanh(last) hist = 'atanh' + str(last) + '=' + str(result) if arg == 'rect': #continue here.... try: result = rect(n_minus1, last) hist = 'Convert ' + str(n_minus1) + ',' + str(last) + ' to rectangular coords.' except TypeError: result = 'Error' hist = 'Error in attempted conversion to rectangular coords. No result.' if arg == 'polar': try: result = polar(last) hist = 'Convert complex value ' + str(last) + ' to rectangular coords.' except TypeError: result = 'Error' hist = 'Error in attempted conversion to polar coords. No result.' config.stack.append(result) history.append(hist) return config.stack
complexHyp_real = int( input( 'Enter the real part of the complex number that you want to find the sinh, cosh, or tanh of:' )) complexHyp_imaginary = int( input( 'Enter the imaginary part of the complex number that you want to find the sinh, cosh, or tanh of: ' )) complexHyp = complex(complexHyp_real, complexHyp_imaginary) print('The sinh of ' + str(complexHyp) + ' is ' + str(cmath.sinh(complexHyp)) + ".") print("The cosh of " + str(complexHyp) + " is " + str(cmath.cosh(complexHyp)) + ".") print("The tanh of " + str(complexHyp) + " is " + str(cmath.tanh(complexHyp)) + ".") elif (complexTriginput.lower()).strip() in acceptedComplexArcHyp: complexArcHype_real = int( input( "Enter the real part of the complex number that you want to find the arcsinh, arccosh, or arctanh of: " )) complexArcHype_imaginary = int( input( "Enter the imaginary part of the complex number that you want to find the arcsinh, arcosh, or arctanh of: " )) complexArcHype = complex(complexArcHype_real,
def Cheb(m, x): if (abs(x) <= 1): return math.cos(m * math.acos(x)) else: return (cmath.cosh(m * cmath.acosh(x))).real
def test_cosh(self): self.assertAlmostEqual(complex(-6.58066, -7.58155), cmath.cosh(complex(3, 4)))
def calculate_deflection(system): # get global variables [length_left] = length_left_glob.data["length_left"] [length_right] = length_right_glob.data["length_right"] [lam] = lam_glob.data["lam"] A1,A2,A3,A4,B1,B2,B3,B4 = create_matrix_and_calculate_coefficients(system) y_beam = np.zeros(n_beam, dtype=complex) if (length_left != 0 and length_right != 0) or (length_left != 0 and system=="Fixed-Free Beam"): # otherwise the beam is not deformed i = 0 while i < n_beam: if x_beam[i] <= length_left: # for the subsystem on the left y_beam[i] = -1*(A1*cm.sin(lam/L*x_beam[i])+A2*cm.cos(lam/L*x_beam[i])+A3*cm.sinh(lam/L*x_beam[i])+A4*cm.cosh(lam/L*x_beam[i])) else: # for the subsystem on the right y_beam[i] = -1*(B1*cm.sin(lam/L*(x_beam[i]-length_left))+B2*cm.cos(lam/L*(x_beam[i]-length_left))+B3*cm.sinh(lam/L*(x_beam[i]-length_left))+B4*cm.cosh(lam/L*(x_beam[i]-length_left))) i+=1 # scales the deflection to a maximum amplitude of 3 max_value = np.amax(np.absolute(y_beam)) y_beam = y_beam * (3/max_value) beam_coordinates_source.data = dict(x=x_beam,y=y_beam.real)
'cos': lambda x: cmath.cos(x), 'tan': lambda x: cmath.tan(x), 'csc': lambda x: 1/cmath.sin(x), 'sec': lambda x: 1/cmath.cos(x), 'cot': lambda x: 1/cmath.tan(x), 'ln': lambda x: cmath.log(x), 'log': lambda x: cmath.log(x)/cmath.log(10), 'fact': lambda x: factorial(int(x)), 'asin': lambda x: cmath.asin(x), 'acos': lambda x: cmath.acos(x), 'atan': lambda x: cmath.atan(x), 'acsc': lambda x: cmath.asin(1/x), 'asec': lambda x: cmath.acos(1/x), 'acot': lambda x: cmath.atan(1/x), 'sinh': lambda x: cmath.sinh(x), 'cosh': lambda x: cmath.cosh(x), 'tanh': lambda x: cmath.tanh(x), 'csch': lambda x: 1/cmath.sinh(x), 'sech': lambda x: 1/cmath.cosh(x), 'coth': lambda x: 1/cmath.tanh(x), 'asinh': lambda x: cmath.asinh(x), 'acosh': lambda x: cmath.acosh(x), 'atanh': lambda x: cmath.atanh(x), 'acsch': lambda x: cmath.asinh(1/x), 'asech': lambda x: cmath.acosh(1/x), 'acoth': lambda x: cmath.atanh(1/x) } def replace_variables(phrase, replacement, var = 'x'): """Replaces all instances of a named variable in a phrase with a replacement, 'x' by default."""
#------------------------------------------------------------------------------ # Hyperbolic functions - real version x = 0.5 assert abs(cosh(x) - math.cosh(x)) < 1e-14 assert abs(sinh(x) - math.sinh(x)) < 1e-14 assert abs(tanh(x) - math.tanh(x)) < 1e-14 #------------------------------------------------------------------------------ # Hyperbolic functions - complex version x = 0.5j assert abs(cosh(x) - cmath.cosh(x)) < 1e-14 assert abs(sinh(x) - cmath.sinh(x)) < 1e-14 assert abs(tanh(x) - cmath.tanh(x)) < 1e-14 assert abs(acosh(x) - cmath.acosh(x)) < 1e-14 assert abs(asinh(x) - cmath.asinh(x)) < 1e-14 assert abs(atanh(x) - cmath.atanh(x)) < 1e-14 #------------------------------------------------------------------------------ # Rounding operations. assert type(round(0.5)) is mpf assert type(round(mpq(1, 2))) is mpf assert type(floor(0.5)) is mpf assert type(ceil(0.5)) is mpf
def UndeformedFBG(self,FBGOriginalWavel,PhotoElasticParam,InitialRefractiveIndex,MeanChangeRefractiveIndex,FringeVisibility,MinBandWidth,MaxBandWidth,SimulationResolution): """ Function to Simulate the Undeformed FBG signal Input: FBGOriginalWavel: List(Mandatory) List with the FBG array original wavelength PhotoElasticParam: float (Mandatory) Photo-Elastic parameter InitialRefractiveIndex: float (Mandatory) Initial effective refractive index (neff) MeanChangeRefractiveIndex: float (Mandatory) Mean induced change in the refractive index (dneff) FringeVisibility: float (Mandatory) Fringe Visibility (Fv) MinBandWidth: float (Mandatory) Light Min. Bandwidth MaxBandWidth: float (Mandatory) SimulationResolution: float (Mandatory) Simulation resolution- Wavelength increment """ self.FBGOriginalWavel=FBGOriginalWavel self.PhotoElasticParam=PhotoElasticParam self.InitialRefractiveIndex=InitialRefractiveIndex self.MeanChangeRefractiveIndex=MeanChangeRefractiveIndex self.FringeVisibility=FringeVisibility self.MinBandWidth=MinBandWidth self.MaxBandWidth=MaxBandWidth self.SimulationResolution=SimulationResolution #Array with the Original FBG period self.APFBG=[] for i in np.arange(0,self.NumberFBG): self.APFBG.append(self.FBGOriginalWavel[i]*(1-self.MeanChangeRefractiveIndex/self.InitialRefractiveIndex)/(2.0*self.InitialRefractiveIndex)) #Empty Original Reflec spectrum self.OReflect={} self.OReflect['wavelength']=[] self.OReflect['reflec']=[] #Cycle all the FBG sensors for i in np.arange(0,self.NumberFBG): # Wavelength cycle (Here the simulation resolution is used) for l in np.arange(self.MinBandWidth,self.MaxBandWidth,self.SimulationResolution): f1 = np.matrix('1 0; 0 1') #empty transfer matrix M=20.0 #Sections the gratting is divided-- Transfer Matrix #FBG increment size (nm) deltz=(self.FBGLength*(10.0**6))/M for z in np.arange(0,M): #Sigma Function sig=2.0*math.pi*self.InitialRefractiveIndex*((1.0/l)-(1.0/(2.0*self.InitialRefractiveIndex*self.APFBG[i])))+(2*math.pi*self.MeanChangeRefractiveIndex/l) #Kaa Function kaa=math.pi*self.FringeVisibility*self.MeanChangeRefractiveIndex/l #Gamma Function gammab=cmath.sqrt(kaa**2.0-sig**2.0) #Transfer Matrix Calculation f11=complex(cmath.cosh(gammab*deltz),-(sig/gammab)*cmath.sinh(gammab*deltz)) f22=complex(cmath.cosh(gammab*deltz),(sig/gammab)*cmath.sinh(gammab*deltz)) f12=complex(0,-(kaa/gammab)*cmath.sinh(gammab*deltz)) f21=complex(0,+(kaa/gammab)*cmath.sinh(gammab*deltz)) #Assemble Transfer Matrix f1=np.dot(f1,np.matrix([[f11, f12],[ f21, f22]])) PO=f1[0,0] NO=f1[1,0] REF=abs(NO/PO)**2 self.OReflect['wavelength'].append(l) self.OReflect['reflec'].append(REF)
def p_expression_cosh(t): 'expression : COSH expression' t[0] = cmath.cosh(t[2])
def p_expression_sech(t): 'expression : SECH expression' t[0] = 1/cmath.cosh(t[2])
def Heston_cf(self,u): """ Define a function that computes the characteristic function for variance gamma """ sigma = self.sigma eta0 = self.eta0 kappa = self.kappa rho = self.rho theta = self.theta S0 = self.S0 r = self.r T = self.T ii = complex(0,1) l = cmath.sqrt(sigma**2*(u**2+ii*u)+(kappa-ii*rho*sigma*u)**2) w = np.exp(ii*u*np.log(S0)+ii*u*(r-0)*T+kappa*theta*T*(kappa-ii*rho*sigma*u)/sigma**2)/(cmath.cosh(l*T/2)+(kappa-ii*rho*sigma*u)/l*cmath.sinh(l*T/2))**(2*kappa*theta/sigma**2) y = w*np.exp(-(u**2+ii*u)*eta0/(l/cmath.tanh(l*T/2)+kappa-ii*rho*sigma*u)) return y
def mycotanh(z): return cmath.cosh(z)/cmath.sinh(z)
def cosh(self): comp_value = cmath.cosh(self.comp_value) dxr = cmath.sinh(self.comp_value) comp_unc = self.comp_unc * dxr # if y = coshx than U(y) = U(x)sinhx return Ucom(comp_value, comp_unc, self.name, self.dep)
def activation(self, x, derive=False): if derive == True: i = 1 / (cmath.cosh(x))**2 return i.real return cmath.tanh(x).real
def NonUniformStrain(self,FBGOriginalWavel,PhotoElasticParam,InitialRefractiveIndex,MeanChangeRefractiveIndex,FringeVisibility,MinBandWidth,MaxBandWidth,SimulationResolution,FBGDirection): """ Function to Simulate the FGB Spectrum Considering Non-Uniform Strain effects Input: FBGOriginalWavel: List(Mandatory) List with the FBG array original wavelength PhotoElasticParam: float (Mandatory) Photo-Elastic parameter InitialRefractiveIndex: float (Mandatory) Initial effective refractive index (neff) MeanChangeRefractiveIndex: float (Mandatory) Mean induced change in the refractive index (dneff) FringeVisibility: float (Mandatory) Fringe Visibility (Fv) MinBandWidth: float (Mandatory) Light Min. Bandwidth MaxBandWidth: float (Mandatory) SimulationResolution: float (Mandatory) Simulation resolution- Wavelength increment FBGDirection: int (mandatory) 0-xx 1-yy 2-zz """ self.FBGOriginalWavel=FBGOriginalWavel self.PhotoElasticParam=PhotoElasticParam self.InitialRefractiveIndex=InitialRefractiveIndex self.MeanChangeRefractiveIndex=MeanChangeRefractiveIndex self.FringeVisibility=FringeVisibility self.MinBandWidth=MinBandWidth self.MaxBandWidth=MaxBandWidth self.SimulationResolution=SimulationResolution self.FBGDirection=FBGDirection #Array with the original FBG period self.APFBG=[] for i in np.arange(0,self.NumberFBG): self.APFBG.append(self.FBGOriginalWavel[i]/(2.0*self.InitialRefractiveIndex)) #Empty Reflec spectrum -Uniform Strain self.NUSReflect={} self.NUSReflect['wavelength']=[] self.NUSReflect['reflec']=[] #Cycle all the FBG sensors for i in np.arange(0,self.NumberFBG): #Sections the gratting is divided-- Transfer Matrix M=len(self.FBGArray['FBG'+str(i+1)]['x']) #FBG increment size (nm) deltz=(self.FBGLength*(10.0**6))/M #----Built the grating period chenged by the Non-uniform strain--- FBGperiod=[] for j in np.arange(0,M): if self.FBGDirection==0: #FBG longitudinal direction (xx) FBGperiod.append(self.APFBG[i]*(1+(1-self.PhotoElasticParam)*self.FBGArray['FBG'+str(i+1)]['LE11'][j])) if self.FBGDirection==1: #FBG longitudinal direction (yy) FBGperiod.append(self.APFBG[i]*(1+(1-self.PhotoElasticParam)*self.FBGArray['FBG'+str(i+1)]['LE22'][j])) if self.FBGDirection==2: #FBG longitudinal direction (zz) FBGperiod.append(self.APFBG[i]*(1+(1-self.PhotoElasticParam)*self.FBGArray['FBG'+str(i+1)]['LE33'][j])) # Wavelength cycle (Here the simulation resolution is used) for l in np.arange(self.MinBandWidth,self.MaxBandWidth,self.SimulationResolution): f1 = np.matrix('1 0; 0 1') #empty transfer matrix #Cycle-Each FBG increment for z in np.arange(0,M): #Sigma Function sig=2.0*math.pi*self.InitialRefractiveIndex*((1.0/l)-(1.0/(2.0*self.InitialRefractiveIndex*FBGperiod[z])))+(2*math.pi*self.MeanChangeRefractiveIndex/l) #Kaa Function kaa=math.pi*self.FringeVisibility*self.MeanChangeRefractiveIndex/l #Gamma Function gammab=cmath.sqrt(kaa**2.0-sig**2.0) #Transfer Matrix Calculation f11=complex(cmath.cosh(gammab*deltz),-(sig/gammab)*cmath.sinh(gammab*deltz)) f22=complex(cmath.cosh(gammab*deltz),(sig/gammab)*cmath.sinh(gammab*deltz)) f12=complex(0,-(kaa/gammab)*cmath.sinh(gammab*deltz)) f21=complex(0,+(kaa/gammab)*cmath.sinh(gammab*deltz)) #Assemble Transfer Matrix f1=np.dot(f1,np.matrix([[f11, f12],[ f21, f22]])) #Add to the Reflection file PO=f1[0,0] NO=f1[1,0] REF=abs(NO/PO)**2 self.NUSReflect['wavelength'].append(l) self.NUSReflect['reflec'].append(REF)
def calculate_amp_and_phase(): # get global variables [length_left] = length_left_glob.data["length_left"] [length_right] = length_right_glob.data["length_right"] [lam] = lam_glob.data["lam"] [EI] = EI_glob.data["EI"] y_amp = np.zeros(n_r, dtype=complex) if (length_left != 0 and length_right != 0 and float(lfa_coordinates_source.data['x'][0]) != 0 and float(lfa_coordinates_source.data['x'][0]) != L) or (system_select.value=="Fixed-Free Beam" and float(lfa_coordinates_source.data['x'][0]) != 0 and length_left != 0): # otherwise the amplitude is zero for every excitation frequency j = 0.04 i = 0 while j < max_r: lam_temp = calculate_lambda(system_select.value, j, EI) # calculates lambda for every frequency ratio lam_glob.data = dict(lam=[lam_temp]) A1,A2,A3,A4,B1,B2,B3,B4 = create_matrix_and_calculate_coefficients(system_select.value) if lfa_coordinates_source.data['x'][0] <= length_left: # for the subsystem on the left y_amp[i] = -1*EI/(F*(L**3))*(A1*cm.sin(lam_temp/L*lfa_coordinates_source.data['x'][0])+A2*cm.cos(lam_temp/L*lfa_coordinates_source.data['x'][0]) +A3*cm.sinh(lam_temp/L*lfa_coordinates_source.data['x'][0])+A4*cm.cosh(lam_temp/L*lfa_coordinates_source.data['x'][0])) else: # for the subsystem on the right y_amp[i] = -1*EI/(F*(L**3))*(B1*cm.sin(lam_temp/L*(lfa_coordinates_source.data['x'][0]-length_left))+B2*cm.cos(lam_temp/L*(lfa_coordinates_source.data['x'][0]-length_left)) +B3*cm.sinh(lam_temp/L*(lfa_coordinates_source.data['x'][0]-length_left))+B4*cm.cosh(lam_temp/L*(lfa_coordinates_source.data['x'][0]-length_left))) j+=0.02 i+=1 for i in range(0,n_r): if slider_damping.value == 0: y_phase[i] = cm.phase(y_amp[i]) # calculate the phase angle for every exitation frequency ratio else: y_phase[i] = -cm.phase(y_amp[i]) y_amp[i] = abs(y_amp[i]) # calculate the absolute value # update plotting variables amp_coordinates_source.data['y'] = y_amp.real phase_coordinates_source.data['y'] = y_phase lam_glob.data = dict(lam=[lam])
def mycotanh(z): return cmath.cosh(z) / cmath.sinh(z)
def dA1dsigm(theta, u, t): return (u**2 * 1j * u) * t / 2 * dddsigm(theta, u) * cm.cosh( de(theta, u) * t / 2)
def TransverseStrain(self,FBGOriginalWavel,PhotoElasticParam,InitialRefractiveIndex,MeanChangeRefractiveIndex,FringeVisibility,MinBandWidth,MaxBandWidth,SimulationResolution,FBGDirection,DirectionalRefractiveP11,DirectionalRefractiveP12,YoungsModule,PoissionsCoefficient): """ Function to Simulate the FGB Spectrum Considering Uniform longitudinal strain and transverse Stress Input: FBGOriginalWavel: List(Mandatory) List with the FBG array original wavelength PhotoElasticParam: float (Mandatory) Photo-Elastic parameter InitialRefractiveIndex: float (Mandatory) Initial effective refractive index (neff) MeanChangeRefractiveIndex: float (Mandatory) Mean induced change in the refractive index (dneff) FringeVisibility: float (Mandatory) Fringe Visibility (Fv) MinBandWidth: float (Mandatory) Light Min. Bandwidth MaxBandWidth: float (Mandatory) SimulationResolution: float (Mandatory) Simulation resolution- Wavelength increment FBGDirection: int (mandatory) 0-xx 1-yy 2-zz DirectionalRefractiveP11: float (Mandatory) Directional Photo-elastic coeffic DirectionalRefractiveP12: float (Mandatory) Directional Photo-elastic coefficient YoungsModule: float (Mandatory) Optical Fibre Young's Module PoissionsCoefficient: float (Mandatory) Optical Fibre Poisson Ration """ self.FBGOriginalWavel=FBGOriginalWavel self.PhotoElasticParam=PhotoElasticParam self.InitialRefractiveIndex=InitialRefractiveIndex self.MeanChangeRefractiveIndex=MeanChangeRefractiveIndex self.FringeVisibility=FringeVisibility self.MinBandWidth=MinBandWidth self.MaxBandWidth=MaxBandWidth self.SimulationResolution=SimulationResolution self.FBGDirection=FBGDirection self.DirectionalRefractiveP11=DirectionalRefractiveP11 self.DirectionalRefractiveP12=DirectionalRefractiveP12 self.YoungsModule=YoungsModule/10**6 #Change to MPA self.PoissionsCoefficient=PoissionsCoefficient #Array with the FBG period- Longitudinal Strain self.APFBG=[] for i in np.arange(0,self.NumberFBG): if self.FBGDirection==0: #FBG longitudinal direction (xx) TempMeanFBG=np.mean(self.FBGArray['FBG'+str(i+1)]['LE11'] )#Strain average TempnewWavelength=self.FBGOriginalWavel[i]*(1+(1-self.PhotoElasticParam)*TempMeanFBG) #weavelength at uniform strain self.APFBG.append(TempnewWavelength/(2.0*self.InitialRefractiveIndex)) # Grating period at strain state if self.FBGDirection==1: #FBG longitudinal direction (yy) TempMeanFBG=np.mean(self.FBGArray['FBG'+str(i+1)]['LE22'] )#Strain average TempnewWavelength=self.FBGOriginalWavel[i]*(1+(1-self.PhotoElasticParam)*TempMeanFBG) #weavelength at uniform strain self.APFBG.append(TempnewWavelength/(2.0*self.InitialRefractiveIndex)) # Grating period at strain state if self.FBGDirection==2: #FBG longitudinal direction (zz) TempMeanFBG=np.mean(self.FBGArray['FBG'+str(i+1)]['LE33'] )#Strain average TempnewWavelength=self.FBGOriginalWavel[i]*(1+(1-self.PhotoElasticParam)*TempMeanFBG) #weavelength at uniform strain self.APFBG.append(TempnewWavelength/(2.0*self.InitialRefractiveIndex)) # Grating period at strain state #Empty Reflec spectrum- Two waves self.TSYReflect={}#Y wave self.TSYReflect['wavelength']=[] self.TSYReflect['reflec']=[] self.TSZReflect={}#Z wave self.TSZReflect['wavelength']=[] self.TSZReflect['reflec']=[] #Cycle all the FBG sensors for i in np.arange(0,self.NumberFBG): #Sections the gratting is divided-- Transfer Matrix M=len(self.FBGArray['FBG'+str(i+1)]['x']) #FBG increment size (nm) deltz=(self.FBGLength*(10.0**6))/M #Build a List with the change in the refractive index DeltaNEffY self.Dneffy=[] self.Dneffz=[] for j in np.arange(0,M): if self.FBGDirection==0: #FBG longitudinal direction (xx) DirecX='S11' DirecY='S22' DirecZ='S33' self.Dneffy.append(-(self.InitialRefractiveIndex**3.0)/(2*self.YoungsModule) *((self.DirectionalRefractiveP11-2*self.PoissionsCoefficient*self.DirectionalRefractiveP12)*self.FBGArray['FBG'+str(i+1)][DirecY][j] +((1-self.PoissionsCoefficient)*self.DirectionalRefractiveP12-self.PoissionsCoefficient*self.DirectionalRefractiveP11) *(self.FBGArray['FBG'+str(i+1)][DirecZ][j]+self.FBGArray['FBG'+str(i+1)][DirecX][j]))) self.Dneffz.append(-(self.InitialRefractiveIndex**3.0)/(2*self.YoungsModule) *((self.DirectionalRefractiveP11-2*self.PoissionsCoefficient*self.DirectionalRefractiveP12)*self.FBGArray['FBG'+str(i+1)][DirecZ][j] +((1-self.PoissionsCoefficient)*self.DirectionalRefractiveP12-self.PoissionsCoefficient*self.DirectionalRefractiveP11) *(self.FBGArray['FBG'+str(i+1)][DirecY][j]+self.FBGArray['FBG'+str(i+1)][DirecX][j]))) if self.FBGDirection==1: #FBG longitudinal direction (yy) DirecX='S22' DirecY='S11' #need to be negative DirecZ='S33' self.Dneffy.append(-(self.InitialRefractiveIndex**3.0)/(2*self.YoungsModule) *((self.DirectionalRefractiveP11-2*self.PoissionsCoefficient*self.DirectionalRefractiveP12)*(-self.FBGArray['FBG'+str(i+1)][DirecY][j]) +((1-self.PoissionsCoefficient)*self.DirectionalRefractiveP12-self.PoissionsCoefficient*self.DirectionalRefractiveP11) *(self.FBGArray['FBG'+str(i+1)][DirecZ][j]+self.FBGArray['FBG'+str(i+1)][DirecX][j]))) self.Dneffz.append(-(self.InitialRefractiveIndex**3.0)/(2*self.YoungsModule) *((self.DirectionalRefractiveP11-2*self.PoissionsCoefficient*self.DirectionalRefractiveP12)*self.FBGArray['FBG'+str(i+1)][DirecZ][j] +((1-self.PoissionsCoefficient)*self.DirectionalRefractiveP12-self.PoissionsCoefficient*self.DirectionalRefractiveP11) *(-self.FBGArray['FBG'+str(i+1)][DirecY][j]+self.FBGArray['FBG'+str(i+1)][DirecX][j]))) if self.FBGDirection==2: #FBG longitudinal direction (zz) DirecX='S33' DirecY='S22' DirecZ='S11'#Negative self.Dneffy.append(-(self.InitialRefractiveIndex**3.0)/(2*self.YoungsModule) *((self.DirectionalRefractiveP11-2*self.PoissionsCoefficient*self.DirectionalRefractiveP12)*self.FBGArray['FBG'+str(i+1)][DirecY][j] +((1-self.PoissionsCoefficient)*self.DirectionalRefractiveP12-self.PoissionsCoefficient*self.DirectionalRefractiveP11) *(-self.FBGArray['FBG'+str(i+1)][DirecZ][j]+self.FBGArray['FBG'+str(i+1)][DirecX][j]))) self.Dneffz.append(-(self.InitialRefractiveIndex**3.0)/(2*self.YoungsModule) *((self.DirectionalRefractiveP11-2*self.PoissionsCoefficient*self.DirectionalRefractiveP12)*(-self.FBGArray['FBG'+str(i+1)][DirecZ][j]) +((1-self.PoissionsCoefficient)*self.DirectionalRefractiveP12-self.PoissionsCoefficient*self.DirectionalRefractiveP11) *(self.FBGArray['FBG'+str(i+1)][DirecY][j]+self.FBGArray['FBG'+str(i+1)][DirecX][j]))) # Wavelength cycle (Here the simulation resolution is used) #YWave for l in np.arange(self.MinBandWidth,self.MaxBandWidth,self.SimulationResolution): f1 = np.matrix('1 0; 0 1') #empty transfer matrix #Cycle-Each FBG increment for z in np.arange(0,M): #Sigma Function sig=2.0*math.pi*(self.InitialRefractiveIndex+self.Dneffy[z])*((1.0/l)-(1.0/(2.0*(self.InitialRefractiveIndex+self.Dneffy[z])*self.APFBG[i])))+(2*math.pi*self.MeanChangeRefractiveIndex/l) #Kaa Function kaa=math.pi*self.FringeVisibility*self.MeanChangeRefractiveIndex/l #Gamma Function gammab=cmath.sqrt(kaa**2.0-sig**2.0) #Transfer Matrix Calculation f11=complex(cmath.cosh(gammab*deltz),-(sig/gammab)*cmath.sinh(gammab*deltz)) f22=complex(cmath.cosh(gammab*deltz),(sig/gammab)*cmath.sinh(gammab*deltz)) f12=complex(0,-(kaa/gammab)*cmath.sinh(gammab*deltz)) f21=complex(0,+(kaa/gammab)*cmath.sinh(gammab*deltz)) #Assemble Transfer Matrix f1=np.dot(f1,np.matrix([[f11, f12],[ f21, f22]])) #Add to the Reflection file- YWave PO=f1[0,0] NO=f1[1,0] REF=abs(NO/PO)**2 self.TSYReflect['wavelength'].append(l) #Output File self.TSYReflect['reflec'].append(REF) #Output File #ZWave for l in np.arange(self.MinBandWidth,self.MaxBandWidth,self.SimulationResolution): f1 = np.matrix('1 0; 0 1') #empty transfer matrix #Cycle-Each FBG increment for z in np.arange(0,M): #Sigma Function sig=2.0*math.pi*(self.InitialRefractiveIndex+self.Dneffz[z])*((1.0/l)-(1.0/(2.0*(self.InitialRefractiveIndex+self.Dneffz[z])*self.APFBG[i])))+(2*math.pi*self.MeanChangeRefractiveIndex/l) #Kaa Function kaa=math.pi*self.FringeVisibility*self.MeanChangeRefractiveIndex/l #Gamma Function gammab=cmath.sqrt(kaa**2.0-sig**2.0) #Transfer Matrix Calculation f11=complex(cmath.cosh(gammab*deltz),-(sig/gammab)*cmath.sinh(gammab*deltz)) f22=complex(cmath.cosh(gammab*deltz),(sig/gammab)*cmath.sinh(gammab*deltz)) f12=complex(0,-(kaa/gammab)*cmath.sinh(gammab*deltz)) f21=complex(0,+(kaa/gammab)*cmath.sinh(gammab*deltz)) #Assemble Transfer Matrix f1=np.dot(f1,np.matrix([[f11, f12],[ f21, f22]])) #Add to the Reflection file- YWave PO=f1[0,0] NO=f1[1,0] REF=abs(NO/PO)**2 self.TSZReflect['wavelength'].append(l) #Output File self.TSZReflect['reflec'].append(REF) #Output File
Power and Log Functions The cmath() module provides some useful functions for logarithmic and power operations. """ c = 1+2j print('e^c = ', cmath.exp(c)) print('log2(c) = ', cmath.log(c,2)) print('log10(c) = ', cmath.log10(c)) print('sqrt(c) = ', cmath.sqrt(c)) """ Trigonometric Functions """ c = 2+4j print('arc sine value:\n ', cmath.asin(c)) print('arc cosine value:\n ', cmath.acos(c)) print('arc tangent value:\n ', cmath.atan(c)) print('sine value:\n ', cmath.sin(c)) print('cosine value:\n ', cmath.cos(c)) print('tangent value:\n ', cmath.tan(c)) """ Hyperbolic Functions """ c = 2+4j print('Inverse hyperbolic sine value: \n', cmath.asinh(c)) print('Inverse hyperbolic cosine value: \n', cmath.acosh(c)) print('Inverse hyperbolic tangent value: \n', cmath.atanh(c)) print('Inverse sine value: \n', cmath.sinh(c)) print('Inverse cosine value: \n', cmath.cosh(c)) print('Inverse tangent value: \n', cmath.tanh(c))
def dA1drho(theta, u, t): return -1j * u * (u**2 + 1j * u) * t * xi(theta, u) * theta[4] / ( 2 * de(theta, u)) * cm.cosh(de(theta, u) * t / 2)
def COSH(df, price='Close'): """ Hyperbolic Cosine Returns: list of floats = jhta.COSH(df, price='Close') """ return [cmath.cosh(df[price][i]).real for i in range(len(df[price]))]
def dA2drho(theta, u, t): return -theta[4] * 1j * u * (2 + t * xi(theta, u)) / ( 2 * de(theta, u)) * (xi(theta, u) * cm.cosh(de(theta, u) * t / 2) + de(theta, u) * cm.sinh(de(theta, u) * t / 2))
def compute_zx_polar(Z0, L, q, x): '''computes the polar represntation of Zx (equation 2.8 in Gals thesis) ''' ZX = Z0 * cmath.cosh(q * (L - x)) / cmath.cosh(q * L) ZX = cmath.polar(ZX) return ZX
def cosh(a, b): result = a**2 + b**2 return cmath.cosh(result) + 1.6j
def Intergration (self,u): sigma = self.sigma eta = self.eta kappa = self.kappa rho = self.rho theta = self.theta S0 = self.S0 r = self.r T = self.T ii = complex(0,1) l = cmath.sqrt( sigma ** 2 * ( u ** 2 + ii * u ) + ( kappa - ii * rho * sigma * u) ** 2) w = np.exp(ii * u * np.log(S0) + ii * u * (r - 0) * T + kappa * theta * T * (kappa - ii * rho * sigma * u)/ sigma ** 2)/(cmath.cosh(l * T/2) + (kappa - ii * rho * sigma * u) / l * cmath.sinh(l * T/2)) ** (2 * kappa * theta/sigma**2) E = w * np.exp(-(u ** 2 + ii * u) * eta/( l / cmath.tanh( l * T/2) + kappa - ii * rho * sigma * u)) return E
def cosh(a): return (cmath.cosh(a) if (a.__class__ == mpc) else math.cosh(a))
print('arc sine =', cmath.asin(c)) print('arc cosine =', cmath.acos(c)) print('arc tangent =', cmath.atan(c)) print('sine =', cmath.sin(c)) print('cosine =', cmath.cos(c)) print('tangent =', cmath.tan(c)) # hyperbolic functions c = 2 + 2j print('inverse hyperbolic sine =', cmath.asinh(c)) print('inverse hyperbolic cosine =', cmath.acosh(c)) print('inverse hyperbolic tangent =', cmath.atanh(c)) print('hyperbolic sine =', cmath.sinh(c)) print('hyperbolic cosine =', cmath.cosh(c)) print('hyperbolic tangent =', cmath.tanh(c)) # classification functions print(cmath.isfinite(2 + 2j)) # True print(cmath.isfinite(cmath.inf + 2j)) # False print(cmath.isinf(2 + 2j)) # False print(cmath.isinf(cmath.inf + 2j)) # True print(cmath.isinf(cmath.nan + 2j)) # False print(cmath.isnan(2 + 2j)) # False print(cmath.isnan(cmath.inf + 2j)) # False print(cmath.isnan(cmath.nan + 2j)) # True print(cmath.isclose(2 + 2j, 2.01 + 1.9j, rel_tol=0.05)) # True
def cos_impl(z): """cmath.cos(z) = cmath.cosh(z j)""" return cmath.cosh(complex(-z.imag, z.real))
def calculations(parameters): #Receving the input parameters from the user_input function system = parameters["system"] phase_spacing_sym = parameters['phase_spacing_sym'] a1 = parameters["a1"] b1 = parameters["b1"] c1 = parameters["c1"] no_sub_conductors = parameters["no_subconductors"] sub_cond_spacing = parameters["sub_cond_spacing"] no_strands = parameters["no_strands"] d = parameters["diameter"] length = parameters["length_of_line"] model = parameters["model"] resistance = parameters["resistance"] freq = parameters["freq"] nom_volt = parameters["nom_volt"] power_rec = parameters["load"] pf = parameters["pf"] #Receiving End Voltage VR = nom_volt / math.sqrt(3) #Calculating radius---r a = 3 b = -3 c = 1 - no_strands # calculate the discriminant di = (b**2) - (4 * a * c) # find two solutions sol1 = (-b - cmath.sqrt(di)) / (2 * a) sol2 = (-b + cmath.sqrt(di)) / (2 * a) if (sol1.real >= sol2.real): n = sol1.real else: n = sol2.real D = (2 * n - 1) * d r = D / 2 # Inductance---L if (system == 1): if (no_sub_conductors == 2): h = math.pow(no_sub_conductors, 2) i = math.pow(phase_spacing_sym, 6) / (math.pow(r, 1) * math.exp( -1 / 4) * math.pow(sub_cond_spacing, 1)) q = math.pow(i, 1 / h) print(q) elif (no_sub_conductors == 3): h = math.pow(no_sub_conductors, 2) i = math.pow(phase_spacing_sym, 6) / math.pow( r * math.pow(sub_cond_spacing, 2) * math.exp(-1 / 4), 3) q = math.pow(i, 1 / h) print(q) elif (no_sub_conductors == 4): h = math.pow(no_sub_conductors, 2) i = math.pow(phase_spacing_sym, 6) / math.pow( r * math.pow(sub_cond_spacing, 3) * math.exp(-1 / 4) * math.sqrt(2), 4) q = math.pow(i, 1 / h) else: h = math.pow(no_sub_conductors, 2) i = math.pow(phase_spacing_sym, 6) / math.pow( r * math.exp(-1 / 4) * math.pow(sub_cond_spacing, 5) * 6, 6) q = math.pow(i, 1 / h) else: if (no_sub_conductors == 2): h = math.pow(a1 * b1 * c1, 1 / 3) i = math.exp(-1 / (4 * no_sub_conductors)) * math.pow( r, 1 / no_sub_conductors) * math.pow(sub_cond_spacing, 1 / no_sub_conductors) q = h / i elif (no_sub_conductors == 3): h = math.pow(a1 * b1 * c1, 1 / 3) i = math.pow(r * math.pow(sub_cond_spacing, 2) * math.exp(-1 / 4), 1 / no_sub_conductors) q = h / i elif (no_sub_conductors == 4): h = math.pow(a1 * b1 * c1, 1 / 3) i = math.pow( math.sqrt(2) * r * math.pow(sub_cond_spacing, 3) * math.exp(-1 / 4), 1 / no_sub_conductors) q = h / i else: h = math.pow(a1 * b1 * c1, 1 / 3) i = math.pow( 6 * r * math.pow(sub_cond_spacing, 5) * math.exp(-1 / 4), 1 / no_sub_conductors) q = h / i L = 2 * math.pow(10, -4) * math.log(q) #Capacitance---Cap if (model == 1): Cap = 0 else: if (system == 1): if (no_sub_conductors == 2): h = math.pow(no_sub_conductors, 2) i = math.pow(phase_spacing_sym, 6) / ( math.pow(r, 1) * math.pow(sub_cond_spacing, 1)) q = math.pow(i, 1 / h) print(q) elif (no_sub_conductors == 3): h = math.pow(no_sub_conductors, 2) i = math.pow(phase_spacing_sym, 6) / math.pow( r * math.pow(sub_cond_spacing, 2), 3) q = math.pow(i, 1 / h) print(q) elif (no_sub_conductors == 4): h = math.pow(no_sub_conductors, 2) i = math.pow(phase_spacing_sym, 6) / math.pow( r * math.pow(sub_cond_spacing, 3) * math.sqrt(2), 4) q = math.pow(i, 1 / h) else: h = math.pow(no_sub_conductors, 2) i = math.pow(phase_spacing_sym, 6) / math.pow( r * math.pow(sub_cond_spacing, 5) * 6, 6) q = math.pow(i, 1 / h) else: if (no_sub_conductors == 2): h = math.pow(a1 * b1 * c1, 1 / 3) i = math.pow(r, 1 / no_sub_conductors) * math.pow( sub_cond_spacing, 1 / no_sub_conductors) q = h / i elif (no_sub_conductors == 3): h = math.pow(a1 * b1 * c1, 1 / 3) i = math.pow(r * math.pow(sub_cond_spacing, 2), 1 / no_sub_conductors) q = h / i elif (no_sub_conductors == 4): h = math.pow(a1 * b1 * c1, 1 / 3) i = math.pow( math.sqrt(2) * r * math.pow(sub_cond_spacing, 3), 1 / no_sub_conductors) q = h / i else: h = math.pow(a1 * b1 * c1, 1 / 3) i = math.pow(6 * r * math.pow(sub_cond_spacing, 5), 1 / no_sub_conductors) q = h / i Cap = 2 * math.pi * 8.84 * math.pow(10, -9) / math.log(q) # Inductive Reactance---XL XL = 2 * math.pi * freq * L * length #Capacitive Reactance---XC if (model == 1): XC = "infinite" else: XC = 1 / (2 * math.pi * freq * Cap * length) # ABCD paramters if (model == 1): Y = 0 else: Y = complex(0, 1 / XC) Z = complex(resistance * length, XL) if (model == 1): A = 1 B = Z C = Y D = 1 elif (model == 2): A = 1 + Y * Z / 2 B = Z C = Y * (1 + Y * Z / 4) D = 1 + Y * Z / 2 else: A = cmath.cosh(cmath.sqrt(Y * Z)) B = cmath.sqrt(Z / Y) * cmath.sinh(cmath.sqrt(Y * Z)) C = cmath.sqrt(Y / Z) * cmath.sinh(cmath.sqrt(Y * Z)) D = cmath.cosh(cmath.sqrt(Y * Z)) # Sending end line voltage---VS # Receving end current---IR IR = power_rec * math.pow(10, 6) / (pf * VR * 3) VS = (A * VR + IR * B) #charging current---IC if (model == 1): IC = 0 elif (model == 2): IC1 = VS * Y / 2 IC2 = VR * Y / 2 IC = IC1 + IC2 else: IC = C * VR # Sending end line Current----IS IS = C * VR + D * IR #Voltage Regulation---volt_reg if (model == 1): volt_reg = (abs(VS) - abs(VR)) * 100 / abs(VR) else: volt_reg = (abs(VS / A) - abs(VR)) * 100 / abs(VR) #Power loss---power_loss power_loss = 3 * IR.real * IR.real * resistance * length #Transmission Efficiency---eff eff = power_rec * 100 / (power_rec + power_loss * math.pow(10, -6)) #Angles angle_1 = cmath.phase(A) #alpha angle_2 = cmath.phase(B) #beta # Sending end circle x = -abs(A) * abs(VS / 1000) * abs( VS / 1000) * math.cos(angle_2 - angle_1) / abs(B) y = abs(A) * abs(VS / 1000) * abs( VS / 1000) * math.sin(angle_2 - angle_1) / abs(B) rad_1 = abs(VS / 1000) * abs(VR / 1000) / abs(B) centre_1 = complex(x, y) fig, ax = plt.subplots() ax.set(xlim=(-5 * rad_1, 5 * rad_1), ylim=(-5 * rad_1, 5 * rad_1)) a_circle = plt.Circle((x, y), rad_1) ax.add_artist(a_circle) plt.title('Sending End Circle', fontsize=12) plt.ylabel("Apparent Power") plt.xlabel("Real Power") plt.text( 100, 200, 'Centre= %s\n Radius = %s\n' % ("{:g}".format(centre_1), "{:.3f}".format(rad_1))) #Receving end circle x1 = -abs(A) * abs(VR / 1000) * abs( VR / 1000) * math.cos(angle_2 - angle_1) / abs(B) y1 = -abs(A) * abs(VR / 1000) * abs( VR / 1000) * math.sin(angle_2 - angle_1) / abs(B) rad_2 = abs(VS / 1000) * abs(VR / 1000) / abs(B) centre_2 = complex(x1, y1) fig, ax_1 = plt.subplots() ax_1.set(xlim=(-5 * rad_2, 5 * rad_2), ylim=(-5 * rad_2, 5 * rad_2)) b_circle = plt.Circle((x1, y1), rad_2, color='r') ax_1.add_artist(b_circle) plt.title('Receving End Circle', fontsize=12) plt.ylabel("Apparent Power") plt.xlabel("Real Power") plt.text( 100, 200, 'Centre= %s\n Radius = %s\n' % ("{:g}".format(centre_2), "{:.3f}".format(rad_2))) plt.show() #Dictionary to pass values to output function features = { "Inductance": L, "Capacitance": Cap, "XL": XL, "XC": XC, "IC": IC, "A": A, "B": B, "C": C, "D": D, "VS": VS, "IS": IS, "volt_reg": volt_reg, "power_loss": power_loss, "eff": eff, "centre_1": centre_1, "rad_1": rad_1, "centre_2": centre_2, "rad_2": rad_2, "model": model } return features
def profileCalc(EkmanDepth_array, EkmanDepth_back, delta_array, frVelCpx_array, frVelCpx_back, stratPar_array, stratPar_back, SBLHeight_array, roughLength_m_array, roughLength_m_back, roughLength_h, roughLength_h_back, tempSurf, tempTop, temp_array, tempSurf_back, tempScale_array, tempScale_back, windCpx_back_array, geostrWindCpx, dpar, alpha_array, corPar, angle, epsilon, M, MODB): CHARNOCKCONST = 0.018 GRAVITYACC = 9.8 OMEGA = 7.29e-5 VONKARMANCONST = 0.41 BETA = GRAVITYACC / 300 N = 50 zmax = max(max([x * 2 for x in EkmanDepth_array]), EkmanDepth_back) hmax = zmax hmin = 1 dlnz = math.log(hmax / hmin) / (N - 1) J = 0 wind_prof = [[] for x in xrange(0, len(delta_array), 2)] temp_prof = [[] for x in xrange(0, len(delta_array), 2)] z_array = [[] for x in xrange(0, len(delta_array), 2)] for i in xrange(0, len(delta_array), 2): d = dpar[i] - epsilon frVel = abs(frVelCpx_array[i]) lambInv = VONKARMANCONST * frVel / (EkmanDepth_array[i] * corPar) profileFunc_m = profileFunc_momentum_Calc(lambInv, epsilon, stratPar_array[i]) u_h = frVelCpx_array[i] / VONKARMANCONST * (math.log(SBLHeight_array[i] / roughLength_m_array[i]) - profileFunc_m) wind_prof_back = [] temp_prof_back = [] z = [] for indx in xrange(N): z.append(hmin * math.exp(dlnz * indx)) if z[indx] <= epsilon * EkmanDepth_back: stratPar = stratPar_back * z[indx] / (epsilon * EkmanDepth_back) tmpLambInv = VONKARMANCONST * abs(frVelCpx_back) / (EkmanDepth_back * corPar) profileFunc_m = profileFunc_momentum_Calc(tmpLambInv, epsilon, stratPar) profileFunc_h = profileFunc_heat_Calc(tmpLambInv, epsilon, stratPar) wind_prof_back.append(frVelCpx_back / VONKARMANCONST * (math.log(z[indx] / roughLength_m_back) - profileFunc_m)) temp_prof_back.append(tempSurf_back + tempScale_back / VONKARMANCONST * (math.log(z[indx] / roughLength_h_back) - profileFunc_h)) else: dmax = M - epsilon ksi = (z[indx] - epsilon * EkmanDepth_back) / (EkmanDepth_back * dmax) tmpKsi = ksi ksi = min(1, ksi) coeff = (1 - 1j) * cmath.sinh((1 + 1j) * dmax * (1 - ksi)) / cmath.cosh((1 + 1j) * dmax) wind_prof_back.append(geostrWindCpx - 1. / lambdaCalc(epsilon, stratPar_back) * frVelCpx_back / VONKARMANCONST * coeff) temp_prof_back.append(tempTop - 2. / lambdaCalc(epsilon, stratPar_back) * tempScale_back / VONKARMANCONST * dmax * (1 - tmpKsi)) if z[indx] <= delta_array[i]: if z[indx] <= SBLHeight_array[i]: stratPar = stratPar_array[i] * z[indx] / SBLHeight_array[i] profileFunc_m = profileFunc_momentum_Calc(lambInv, epsilon, stratPar) profileFunc_h = profileFunc_heat_Calc(lambInv, epsilon, stratPar) wind_prof[J].append(frVelCpx_array[i] / VONKARMANCONST * (math.log(z[indx] / roughLength_m_array[i]) - profileFunc_m)) temp_prof[J].append(tempSurf + tempScale_array[i] / VONKARMANCONST * (math.log(z[indx] / roughLength_h) - profileFunc_h)) else: ksi = (z[indx] - SBLHeight_array[i]) / (delta_array[i] - SBLHeight_array[i]) tmpKsi = ksi tmpKsi = ksi ksi = min(1, ksi) heatFlux = - frVel * tempScale_array[i] alpha = alpha_array[i] coeff1 = (1 - 1j) * cmath.sinh((1 + 1j) * d * (1 - ksi)) / cmath.cosh((1 + 1j) * d) coeff2 = heatFlux * (1 - ksi) tmpCoeff2 = 0 coeff3 = heatFlux * (1 - ksi) coeff4 = BETA * d ** 2 / (corPar * abs(geostrWindCpx) * math.cos(angle) * (alpha + 1j * d ** 2)) coeff4 *= (coeff2 - tmpCoeff2) coeff4 *= MODB coeff5 = (windCpx_back_array[i] - geostrWindCpx) * \ cmath.cosh((1 + 1j) * d * ksi) / cmath.cosh((1 + 1j) * d) wind_prof[J].append(geostrWindCpx - lambInv * frVelCpx_array[i] / VONKARMANCONST * coeff1\ + coeff4 +coeff5) temp_prof[J].append(temp_array[i] + 2. * lambInv * d * coeff3 / (frVel * VONKARMANCONST)) else: wind_prof[J].append(wind_prof_back[indx]) temp_prof[J].append(temp_prof_back[indx]) z_array[J].append(z[indx]) J += 1 return wind_prof, temp_prof, z_array, wind_prof_back, temp_prof_back
def UndeformedFBG(self, SimulationResolution, MinBandWidth, MaxBandWidth, InitialRefractiveIndex, MeanChangeRefractiveIndex, FringeVisibility, DirectionalRefractiveP11, DirectionalRefractiveP12, PoissonsCoefficient, FBGOriginalWavel): """ Parameters ---------- SimulationResolution: float (Mandatory) Simulation resolution- Wavelength increment MinBandWidth: float (Mandatory) Light Min. Bandwidth MaxBandWidth: float (Mandatory) Light Max. Bandwidth InitialRefractiveIndex: float (Mandatory) Initial effective refractive index (neff) MeanChangeRefractiveIndex: float (Mandatory) Mean induced change in the refractive index (dneff) FringeVisibility: float (Mandatory) Fringe Visibility (FV) DirectionalRefractiveP11 : float (Mandatory) Pockel’s normal photoelastic constant DirectionalRefractiveP12 : float (Mandatory) Pockel’s shear photoelastic constant PoissonsCoefficient : float (Mandatory) Poisson's Coefficient of fiber FBGOriginalWavel: array (Mandatory) Original wavelengths of FBG regions Returns ------- None. """ self.SimulationResolution = SimulationResolution self.MinBandWidth = MinBandWidth self.MaxBandWidth = MaxBandWidth self.InitialRefractiveIndex = InitialRefractiveIndex self.MeanChangeRefractiveIndex = MeanChangeRefractiveIndex self.FringeVisibility = FringeVisibility self.DirectionalRefractiveP11 = DirectionalRefractiveP11 self.DirectionalRefractiveP12 = DirectionalRefractiveP12 self.PoissonsCoefficient = PoissonsCoefficient self.FBGOriginalWavel = FBGOriginalWavel #Array with the Original FBG period self.APFBG = [] for i in np.arange(0, self.NumberFBG): self.APFBG.append(self.FBGOriginalWavel[i] / (2.0 * self.InitialRefractiveIndex)) #Empty Original Reflec spectrum self.OReflect = {} self.OReflect['wavelength'] = [] self.OReflect['reflec'] = [] #Cycle all the FBG sensors for i in np.arange(0, self.NumberFBG): # Wavelength cycle (Here the simulation resolution is used) for l in np.arange(self.MinBandWidth, self.MaxBandWidth, self.SimulationResolution): #print("---------- WAVELENGTH: "+str(l)) f1 = np.matrix('1 0; 0 1') #empty transfer matrix M = 20.0 #Sections the gratting is divided-- Transfer Matrix #FBG increment size (nm) deltz = (self.FBGLength * (10.0**6)) / M for z in np.arange(0, M): #Sigma Function sig = 2.0 * math.pi * self.InitialRefractiveIndex * ( (1.0 / l) - (1.0 / (2.0 * self.InitialRefractiveIndex * self.APFBG[i])) ) + (2 * math.pi * self.MeanChangeRefractiveIndex / l) #print("Sigma: "+str(sig)) #print("Lamb: "+str((2.0*self.InitialRefractiveIndex*self.APFBG[i]))) #Kaa Function kaa = math.pi * self.FringeVisibility * self.MeanChangeRefractiveIndex / l #print("Kaa: "+str(kaa)) #Gamma Function gammab = cmath.sqrt(kaa**2.0 - sig**2.0) #print("Gammab: "+str(gammab)) #Transfer Matrix Calculation f11 = complex(cmath.cosh(gammab * deltz), -(sig / gammab) * cmath.sinh(gammab * deltz)) f22 = complex(cmath.cosh(gammab * deltz), (sig / gammab) * cmath.sinh(gammab * deltz)) f12 = complex(0, -(kaa / gammab) * cmath.sinh(gammab * deltz)) f21 = complex(0, +(kaa / gammab) * cmath.sinh(gammab * deltz)) #print("TM: "+str(gammab)) #Assemble Transfer Matrix f1 = np.dot(f1, np.matrix([[f11, f12], [f21, f22]])) #print("Transfer Matrix "+str(z)+": "+str(f1)) PO = f1[0, 0] NO = f1[1, 0] REF = abs(NO / PO)**2 #print("Reflectivity "+str(REF)) self.OReflect['wavelength'].append(l) self.OReflect['reflec'].append(REF) print(self.OReflect['wavelength'][0:15]) print(self.OReflect['reflec'][0:15])
def DeformedFBG(self, SimulationResolution, MinBandWidth, MaxBandWidth, AmbientTemperature, InitialRefractiveIndex, MeanChangeRefractiveIndex, FringeVisibility, DirectionalRefractiveP11, DirectionalRefractiveP12, YoungsModule, PoissonsCoefficient, ThermoOptic, StrainType, StressType, EmulateTemperature, FiberThermalExpansionCoefficient, HostThermalExpansionCoefficient, FBGOriginalWavel): """ Parameters ---------- SimulationResolution: float (Mandatory) Simulation resolution- Wavelength increment MinBandWidth: float (Mandatory) Light Min. Bandwidth MaxBandWidth: float (Mandatory) Light Max. Bandwidth AmbientTemperature : float (Mandatory) Base in which our reference temperature is set. InitialRefractiveIndex: float (Mandatory) Initial effective refractive index (neff) MeanChangeRefractiveIndex: float (Mandatory) Mean induced change in the refractive index (dneff) FringeVisibility: float (Mandatory) Fringe Visibility (FV) DirectionalRefractiveP11 : float (Mandatory) Pockel’s normal photoelastic constant DirectionalRefractiveP12 : float (Mandatory) Pockel’s shear photoelastic constant YoungsModule : float (Mandatory) Young's modulus of fiber PoissonsCoefficient : float (Mandatory) Poisson's Coefficient of fiber ThermoOptic : float (Mandatory) Thermo optic coefficient of fiber StrainType : int (Mandatory) 0 for none, 1 for uniform, 2 for non-uniform StressType : int (Mandatory) 0 for none, 1 for included EmulateTemperature : float (Mandatory) Theoretical emulated temperature of fiber FiberThermalExpansionCoefficient : float (Mandatory) Thermal expansion coefficient of fiber material HostThermalExpansionCoefficient : float (Mandatory) Thermal expansion coefficient of host material FBGOriginalWavel: array (Mandatory) Original wavelengths of FBG regions Returns ------- None. """ self.SimulationResolution = SimulationResolution self.MinBandWidth = MinBandWidth self.MaxBandWidth = MaxBandWidth self.AmbientTemperature = AmbientTemperature self.InitialRefractiveIndex = InitialRefractiveIndex self.MeanChangeRefractiveIndex = MeanChangeRefractiveIndex self.FringeVisibility = FringeVisibility self.DirectionalRefractiveP11 = DirectionalRefractiveP11 self.DirectionalRefractiveP12 = DirectionalRefractiveP12 self.YoungsModule = YoungsModule self.PoissonsCoefficient = PoissonsCoefficient self.ThermoOptic = ThermoOptic self.EmulateTemperature = EmulateTemperature self.FiberThermalExpansionCoefficient = FiberThermalExpansionCoefficient self.HostThermalExpansionCoefficient = HostThermalExpansionCoefficient self.FBGOriginalWavel = FBGOriginalWavel #Calculate photoelastic coef from directional coefs. self.PhotoElasticParam = (self.InitialRefractiveIndex**2 / 2) * ( self.DirectionalRefractiveP12 - self.PoissonsCoefficient * (self.DirectionalRefractiveP11 - self.DirectionalRefractiveP12)) #Determine if we need to emulate a theoretical temperature value if self.EmulateTemperature != -1.0: for i in np.arange(0, self.NumberFBG): for j in range(len(self.FBGArray['FBG' + str(i + 1)]['T'])): self.FBGArray['FBG' + str(i + 1)]['T'][j] = self.EmulateTemperature print(self.FBGArray['FBG' + str(i + 1)]['T'][0:5]) #Array with the original FBG periods self.APFBG = [] for i in np.arange(0, self.NumberFBG): self.APFBG.append(self.FBGOriginalWavel[i] / (2.0 * self.InitialRefractiveIndex)) #Empty Reflec spectrum- Two waves (individual contributions to account for any transverse stress) self.YReflect = {} #Y wave self.YReflect['wavelength'] = [] self.YReflect['reflec'] = [] self.ZReflect = {} #Z wave self.ZReflect['wavelength'] = [] self.ZReflect['reflec'] = [] #Empty Reflec spectrum- Composite wave of Y and Z contributions self.DReflect = {} #Composite wave self.DReflect['wavelength'] = [] self.DReflect['reflec'] = [] #Cycle all the FBG sensors for i in np.arange(0, self.NumberFBG): #Sections the gratting is divided-- Transfer Matrix M = len(self.FBGArray['FBG' + str(i + 1)]['x']) #FBG increment size (nm) deltz = (self.FBGLength * (10.0**6)) / M #--- STRAIN --- FBGperiod = [] if StrainType == 0: #--- Case of "no longitudinal strain" --- for j in np.arange(0, M): FBGperiod.append(self.APFBG[i]) elif StrainType == 1: #--- Case of "uniform longitudinal strain" --- StrainMeanFBG = np.mean( self.FBGArray['FBG' + str(i + 1)] ['LE11']) #Strain average over FBG region TempMeanFBG = np.mean( self.FBGArray['FBG' + str(i + 1)] ['T']) #Temperature average over FBG region TempnewWavelength = self.FBGOriginalWavel[i] * ( 1 + (1 - self.PhotoElasticParam) * StrainMeanFBG + (self.FiberThermalExpansionCoefficient + (1 - self.PhotoElasticParam) * (self.HostThermalExpansionCoefficient - self. FiberThermalExpansionCoefficient) + self.ThermoOptic) * (TempMeanFBG - self.AmbientTemperature) ) #weavelength at uniform strain and temperature for j in np.arange(0, M): FBGperiod.append( TempnewWavelength / (2.0 * self.InitialRefractiveIndex)) # Grating period else: #--- Case of "non-uniform longitudinal strain" build the grating period changed --- for j in np.arange(0, M): TempnewWavelength = self.FBGOriginalWavel[i] * ( 1 + (1 - self.PhotoElasticParam) * self.FBGArray['FBG' + str(i + 1)]['LE11'][j] + (self.FiberThermalExpansionCoefficient + (1 - self.PhotoElasticParam) * (self.HostThermalExpansionCoefficient - self.FiberThermalExpansionCoefficient) + self.ThermoOptic) * (self.FBGArray['FBG' + str(i + 1)]['T'][j] - self.AmbientTemperature) ) #weavelength at nonuniform strain and temperature #print(self.FBGArray['FBG'+str(i+1)]['T'][0]-self.AmbientTemperature) FBGperiod.append( TempnewWavelength / (2.0 * self.InitialRefractiveIndex)) # Grating period #--- STRESS --- #Build a List with the change in the refractive index DeltaNEffY self.Dneffy = [] self.Dneffz = [] if StressType == 0: #--- Case of "no transverse stress" --- for j in np.arange(0, M): self.Dneffy.append(0) self.Dneffz.append(0) else: #--- Case of "included transverse stress" --- for j in np.arange(0, M): DirecX = 'S11' DirecY = 'S22' DirecZ = 'S33' self.Dneffy.append( -(self.InitialRefractiveIndex**3.0) / (2 * self.YoungsModule) * ((self.DirectionalRefractiveP11 - 2 * self.PoissonsCoefficient * self.DirectionalRefractiveP12) * self.FBGArray['FBG' + str(i + 1)][DirecY][j] + ((1 - self.PoissonsCoefficient) * self. DirectionalRefractiveP12 - self.PoissonsCoefficient * self.DirectionalRefractiveP11) * (self.FBGArray['FBG' + str(i + 1)][DirecZ][j] + self.FBGArray['FBG' + str(i + 1)][DirecX][j]))) self.Dneffz.append( -(self.InitialRefractiveIndex**3.0) / (2 * self.YoungsModule) * ((self.DirectionalRefractiveP11 - 2 * self.PoissonsCoefficient * self.DirectionalRefractiveP12) * self.FBGArray['FBG' + str(i + 1)][DirecZ][j] + ((1 - self.PoissonsCoefficient) * self. DirectionalRefractiveP12 - self.PoissonsCoefficient * self.DirectionalRefractiveP11) * (self.FBGArray['FBG' + str(i + 1)][DirecY][j] + self.FBGArray['FBG' + str(i + 1)][DirecX][j]))) #--- SIMULATION --- #YWave for l in np.arange( self.MinBandWidth, self.MaxBandWidth, self.SimulationResolution ): # Wavelength cycle (Here the simulation resolution is used) f1 = np.matrix('1 0; 0 1') #empty transfer matrix #Cycle-Each FBG increment for z in np.arange(0, M): #Sigma Function sig = 2.0 * math.pi * ( self.InitialRefractiveIndex + self.Dneffy[z]) * ( (1.0 / l) - (1.0 / (2.0 * (self.InitialRefractiveIndex + self.Dneffy[z]) * FBGperiod[z]))) + ( 2 * math.pi * self.MeanChangeRefractiveIndex / l) #Kaa Function kaa = math.pi * self.FringeVisibility * self.MeanChangeRefractiveIndex / l #Gamma Function gammab = cmath.sqrt(kaa**2.0 - sig**2.0) #Transfer Matrix Calculation f11 = complex(cmath.cosh(gammab * deltz), -(sig / gammab) * cmath.sinh(gammab * deltz)) f22 = complex(cmath.cosh(gammab * deltz), (sig / gammab) * cmath.sinh(gammab * deltz)) f12 = complex(0, -(kaa / gammab) * cmath.sinh(gammab * deltz)) f21 = complex(0, +(kaa / gammab) * cmath.sinh(gammab * deltz)) #Assemble Transfer Matrix f1 = np.dot(f1, np.matrix([[f11, f12], [f21, f22]])) #Add to the Reflection file- YWave PO = f1[0, 0] NO = f1[1, 0] REF = abs(NO / PO)**2 self.YReflect['wavelength'].append(l) #Output File self.YReflect['reflec'].append(REF) #Output File #ZWave for l in np.arange(self.MinBandWidth, self.MaxBandWidth, self.SimulationResolution): f1 = np.matrix('1 0; 0 1') #empty transfer matrix #Cycle-Each FBG increment for z in np.arange(0, M): #Sigma Function sig = 2.0 * math.pi * ( self.InitialRefractiveIndex + self.Dneffz[z]) * ( (1.0 / l) - (1.0 / (2.0 * (self.InitialRefractiveIndex + self.Dneffz[z]) * FBGperiod[z]))) + ( 2 * math.pi * self.MeanChangeRefractiveIndex / l) #Kaa Function kaa = math.pi * self.FringeVisibility * self.MeanChangeRefractiveIndex / l #Gamma Function gammab = cmath.sqrt(kaa**2.0 - sig**2.0) #Transfer Matrix Calculation f11 = complex(cmath.cosh(gammab * deltz), -(sig / gammab) * cmath.sinh(gammab * deltz)) f22 = complex(cmath.cosh(gammab * deltz), (sig / gammab) * cmath.sinh(gammab * deltz)) f12 = complex(0, -(kaa / gammab) * cmath.sinh(gammab * deltz)) f21 = complex(0, +(kaa / gammab) * cmath.sinh(gammab * deltz)) #Assemble Transfer Matrix f1 = np.dot(f1, np.matrix([[f11, f12], [f21, f22]])) #Add to the Reflection file- YWave PO = f1[0, 0] NO = f1[1, 0] REF = abs(NO / PO)**2 self.ZReflect['wavelength'].append(l) #Output File self.ZReflect['reflec'].append(REF) #Output File #Halve the amplitude of each of the y and z waves, then sum to find composite wave. self.DReflect['wavelength'] = self.YReflect['wavelength'] self.YReflect['reflec'] = np.divide(self.YReflect['reflec'], 2.0) self.ZReflect['reflec'] = np.divide(self.ZReflect['reflec'], 2.0) self.DReflect['reflec'] = np.add(self.YReflect['reflec'], self.ZReflect['reflec'])
def Coth(x): return cmath.cosh(x)/cmath.sinh(x)
def __new__(cls, argument): if isinstance(argument, (RealValue, Zero)): return FloatValue(math.cosh(float(argument))) if isinstance(argument, (ComplexValue)): return ComplexValue(cmath.cosh(complex(argument))) return MathFunction.__new__(cls)
def fit(lines_seriestab, file_prefix, sparky_peaklist, OS): import os, math, cmath ## ## (tau,R2eff)-fit and kex,R2-determ. ## lines_fit_o = ['#atom Ra Rb ka kb dw\n'] fd = open('%s.gnudata' %(file_prefix),'r') gnudata = fd.readlines() fd.close() ## set a list of sums of squares SS = [] for i in range(len(lines_seriestab)): if not sparky_peaklist: ass = assignments_Sparky[peakindexes_NMRPipe[i]] else: ass = lines_seriestab[i][58:68].strip() print 'nonlinear fit for %s' %(ass) lines_gnuplot_script = ([ '#freqCP = x\n' 'tauCP(x) = 1/(4.*x)\n', ## 'psi(x) = (Ra-Rb-ka+kb)**2-deltaomega**2+4.*ka*kb\n', ## tc 'psi(x) = kex**2-deltaomega**2\n', ## kt ## 'epsilon(x) = 2*deltaomega*(Ra-Rb-ka+kb)\n', ## tc 'epsilon(x) = -2*deltaomega*kex*(2*pA-1)\n', ## kt ## 'Dpos(x) = (1./2.)*( 1+(psi(x)+2*deltaomega**2)/sqrt(psi(x)**2+epsilon(x)**2))\n', ## 'Dneg(x) = (1./2.)*(-1+(psi(x)+2*deltaomega**2)/sqrt(psi(x)**2+epsilon(x)**2))\n', 'Dpos(x) = (1./2.)*( 1+(psi(x)+2*deltaomega**2)/sqrt(psi(x)**2+epsilon(x)**2))\n', 'Dneg(x) = (1./2.)*(-1+(psi(x)+2*deltaomega**2)/sqrt(psi(x)**2+epsilon(x)**2))\n', 'etapos(x) = (tauCP(x)/sqrt(2))*sqrt( psi(x)+sqrt(psi(x)**2+epsilon(x)**2))\n', 'etaneg(x) = (tauCP(x)/sqrt(2))*sqrt(-psi(x)+sqrt(psi(x)**2+epsilon(x)**2))\n', ## 'f(x) = (1./2.)*( Ra+Rb+ka+kb-(1/tauCP(x))*( acosh( Dpos(x)*cosh(etapos(x)) - Dneg(x)*cos(etaneg(x)) ) ) )\n', 'f(x) = R+(1./2.)*( kex-(1/tauCP(x))*( acosh( Dpos(x)*cosh(etapos(x)) - Dneg(x)*cos(etaneg(x)) ) ) )\n', ## 'Ra = 17\n', ## tc ## 'Rb = 23\n', ## tc ## 'ka = 29\n', ## tc ## 'kb = 19\n', ## tc 'kex = 2000\n', ## kt 'pA = 0.9\n', ## kt 'R = 7\n', ## kt 'deltaomega = 1000\n', ## 'fit f(x) "%s.gnudata" using 1:%s via Ra,Rb,ka,kb,deltaomega\n' %(file_prefix, i+2), 'fit f(x) "%s.gnudata" using 1:%s via kex,pA,R,deltaomega\n' %(file_prefix, i+2), 'set terminal png\n', 'set output "%s%s.png"\n' %(file_prefix, i), 'plot [][0:]"%s.gnudata" using 1:%s title "%s", f(x)\n' %(file_prefix, i+2, ass) ]) ## write gnuplot script file fd = open('%s.gnuscript%s' %(file_prefix, i), 'w') fd.writelines(lines_gnuplot_script) fd.close() ## execute gnuplot script file and write gnuplot fit log if OS == 'linux': os.system('/usr/bin/gnuplot %s.gnuscript%s' %(file_prefix, i)) elif OS == 'windows': os.system('gnuplot %s.gnuscript%s' %(file_prefix, i)) ## remove gnuplot script file os.remove('%s.gnuscript%s' %(file_prefix, i)) ## parse gnuplot fit log if OS == 'linux': lines_fit_i = os.popen('tail -n18 fit.log').readlines() elif OS == 'windows': fd = open('fit.log','r') lines_fit_i = fd.readlines()[-18:] fd.close() ## Ra = float(lines_fit_i[3].split()[2]) ## Rb = float(lines_fit_i[4].split()[2]) ## ka = float(lines_fit_i[5].split()[2]) ## kb = float(lines_fit_i[6].split()[2]) ## dw = float(lines_fit_i[7].split()[2]) kex = float(lines_fit_i[5].split()[2]) pA = float(lines_fit_i[6].split()[2]) R = float(lines_fit_i[7].split()[2]) dw = float(lines_fit_i[8].split()[2]) ## write parsed fit data to other fit log ## lines_fit_o += ['%10s %6.3f %6.3f %6.3f %6.3f %8.3f\n' %(ass, Ra, Rb, ka, kb, dw)] lines_fit_o += ['%10s %6.3f %6.3f %6.3f %8.3f\n' %(ass, kex, pA, R, dw)] ## ## SS calculation for use in F-test comparing nonlinear and linear fits ## n = len(gnudata[1:]) deltaomega = dw sumdiffsq = 0 sumdiff = 0 for line in gnudata[1:]: x = float(line.split()[0]) y = float(line.split()[i+1]) tauCP = 1/(4.*x) ## psi = (Ra-Rb-ka+kb)**2-deltaomega**2+4.*ka*kb psi = kex**2-deltaomega**2 ## epsilon = 2*deltaomega*(Ra-Rb-ka+kb) epsilon = -2*deltaomega*kex*(2*pA-1) Dpos = (1./2.)*( 1+(psi+2*deltaomega**2)/math.sqrt(psi**2+epsilon**2)) Dneg = (1./2.)*(-1+(psi+2*deltaomega**2)/math.sqrt(psi**2+epsilon**2)) etapos = (tauCP/math.sqrt(2))*math.sqrt( psi+math.sqrt(psi**2+epsilon**2)) etaneg = (tauCP/math.sqrt(2))*math.sqrt(-psi+math.sqrt(psi**2+epsilon**2)) ## yhat = (1./2.)*( Ra+Rb+ka+kb-(1/tauCP)*( cmath.acosh( Dpos*cmath.cosh(etapos) - Dneg*math.cos(etaneg) ) ) ) yhat = R+(1./2.)*( kex-(1/tauCP)*( cmath.acosh( Dpos*cmath.cosh(etapos) - Dneg*math.cos(etaneg) ) ) ) diff = yhat-y sumdiff += diff ## abs?? sumdiffsq += diff**2 ss = abs(sumdiffsq-(sumdiff**2)/n) stop ## append ss calculated for 1 chemical group to list of sums of squares SS += [ss] os.remove('fit.log') fd = open('%s.fit' %(file_prefix), 'w') fd.writelines(lines_fit_o) fd.close() return SS
#------------------------------------------------------------------------------ # Hyperbolic functions - real version x = 0.5 assert abs(cosh(x) - math.cosh(x)) < 1e-14 assert abs(sinh(x) - math.sinh(x)) < 1e-14 assert abs(tanh(x) - math.tanh(x)) < 1e-14 #------------------------------------------------------------------------------ # Hyperbolic functions - complex version x = 0.5j assert abs(cosh(x) - cmath.cosh(x)) < 1e-14 assert abs(sinh(x) - cmath.sinh(x)) < 1e-14 assert abs(tanh(x) - cmath.tanh(x)) < 1e-14 assert abs(acosh(x) - cmath.acosh(x)) < 1e-14 assert abs(asinh(x) - cmath.asinh(x)) < 1e-14 assert abs(atanh(x) - cmath.atanh(x)) < 1e-14 #------------------------------------------------------------------------------ # Rounding operations. assert type(round(0.5)) is mpf assert type(round(mpq(1,2))) is mpf assert type(floor(0.5)) is mpf assert type(ceil(0.5)) is mpf
def cosh_usecase(x): return cmath.cosh(x)
def calculate_3d_plot_coordinates(system): # get global variables [length_left] = length_left_glob.data["length_left"] [length_right] = length_right_glob.data["length_right"] [lam] = lam_glob.data["lam"] [EI] = EI_glob.data["EI"] xx = xx_all[0] value_unraveled_all = np.zeros((250,26), dtype=complex) if (length_left != 0 and length_right != 0) or (length_left != 0 and system=="Fixed-Free Beam"): # otherwise the beam is not deformed j = 0.04 k = 0 while j <= 10.0: lam_temp = calculate_lambda(system,j,EI) # calculates lambda for every frequency lam_glob.data = dict(lam=[lam_temp]) A1,A2,A3,A4,B1,B2,B3,B4 = create_matrix_and_calculate_coefficients(system) i = 0 while i < 26: if xx[i] <= length_left: # for the subsystem on the left value_unraveled_all[k][i] = -1*EI*j*j/(F*(L**3))*(A1*cm.sin(lam_temp/L*xx[i])+A2*cm.cos(lam_temp/L*xx[i])+A3*cm.sinh(lam_temp/L*xx[i])+A4*cm.cosh(lam_temp/L*xx[i])) else: # for the subsystem on the right value_unraveled_all[k][i] = -1*EI*j*j/(F*(L**3))*(B1*cm.sin(lam_temp/L*(xx[i]-length_left))+B2*cm.cos(lam_temp/L*(xx[i]-length_left))+B3*cm.sinh(lam_temp/L*(xx[i]-length_left))+B4*cm.cosh(lam_temp/L*(xx[i]-length_left))) i+=1 k+=1 j = round(j+0.04,2) zmax = complex(max(value_unraveled_all.ravel().real), 0) # get maximum z value zmin = complex(min(value_unraveled_all.ravel().real), 0) # get minimum z value if (zmax.real == 0.0 and zmin.real == 0.0): zmax = complex(0.05, 0) zmin = complex(-0.05, 0) lam_glob.data = dict(lam=[lam]) zmax_glob.data = dict(zmax=[zmax]) zmin_glob.data = dict(zmin=[zmin]) value_unraveled_all_glob.data = dict(value_unraveled_all=value_unraveled_all)
def birefringence_rot(s, chi, lambda_0, n_o, n_e, jones, rng_states, thread_idx, B, U, U_epar, rand_nums, seed): if n_o != n_e or chi != 0: if B[0] == 2.0 and B[1] == 2.0 and B[2] == 2.0: # rand_num = xoroshiro128p_uniform_float32(rng_states, thread_idx) rand_num = rand_nums[seed] theta = cmath.pi * rand_num # rand_num = xoroshiro128p_uniform_float32(rng_states, thread_idx + 1) rand_num = rand_nums[seed + 1] beta0 = cmath.pi * 2 * rand_num B[0] = cmath.sin(theta).real * cmath.cos(beta0).real B[1] = cmath.sin(theta).real * cmath.sin(beta0).real B[2] = cmath.cos(theta).real theta1 = cuda.local.array(1, float32) get_theta(B, U, theta1) Bp = cuda.local.array(3, float32) temp = B[0] * U[0] + B[1] * U[1] + B[2] * U[2] Bp[0] = B[0] - U[0] * temp Bp[1] = B[1] - U[1] * temp Bp[2] = B[2] - U[2] * temp temp = cmath.sqrt(Bp[0] * Bp[0] + Bp[1] * Bp[1] + Bp[2] * Bp[2]).real if temp != 0: Bp[0] /= temp Bp[1] /= temp Bp[2] /= temp beta = cuda.local.array(1, float32) get_beta(U_epar, Bp, U, beta) # temp = n_e * cmath.cos(theta1[0]).real * n_e * cmath.cos(theta1[0]).real delta_n = n_o * n_e / cmath.sqrt( n_e * cmath.cos(theta1[0]).real * n_e * cmath.cos(theta1[0]).real + n_o * cmath.sin(theta1[0]).real * n_o * cmath.sin(theta1[0]).real).real - n_o g_o = cmath.pi * delta_n / (lambda_0 * 1e4) # n_mat = np.array([g_o.j, -g_o.j, -chi, chi]) n_mat = cuda.local.array(4, nb.complex64) n_mat[0] = g_o * 1j n_mat[1] = -g_o * 1j n_mat[2] = -chi n_mat[3] = chi Q_n = cmath.sqrt(n_mat[0] * n_mat[0] - n_mat[3] * n_mat[3]) m = cuda.local.array(4, nb.complex64) m_new = cuda.local.array(4, nb.complex64) if Q_n != 0: # todo check which to keep # m[0] = (n_mat[0] - n_mat[1]) * cmath.sinh(Q_n * s) / (2 * Q_n) + cmath.cosh(Q_n * s) # m[1] = (n_mat[0] - n_mat[1]) * cmath.sinh(Q_n * s) / (2 * Q_n) + cmath.cosh(Q_n * s) # m[2] = (n_mat[2]) * cmath.sinh(Q_n * s) / (Q_n) # m[3] = -m[2] m[0] = cmath.exp((n_mat[0] + n_mat[1]) / 2 * s) * ( (n_mat[0] - n_mat[1]) * cmath.sinh(Q_n * s) / (2 * Q_n) + cmath.cosh(Q_n * s)) m[1] = cmath.exp((n_mat[0] + n_mat[1]) / 2 * s) * ( (n_mat[0] - n_mat[1]) * cmath.sinh(Q_n * s) / (2 * Q_n) + cmath.cosh(Q_n * s)) m[2] = cmath.exp((n_mat[0] + n_mat[1]) / 2 * s) * ( (n_mat[2]) * cmath.sinh(Q_n * s) / (Q_n)) m[3] = cmath.exp((n_mat[0] + n_mat[1]) / 2 * s) * (-m[2]) m_new[0] = m[0] * cmath.cos(beta[0]) + m[2] * cmath.sin(beta[0]) m_new[1] = m[1] * cmath.cos(beta[0]) + m[3] * cmath.sin(beta[0]) m_new[2] = -m[0] * cmath.sin(beta[0]) + m[2] * cmath.cos(beta[0]) m_new[3] = -m[1] * cmath.sin(beta[0]) + m[3] * cmath.cos(beta[0]) jones[thread_idx, 0] = jones[thread_idx, 0] * m_new[0] + jones[thread_idx, 2] * m_new[3] jones[thread_idx, 1] = jones[thread_idx, 1] * m_new[0] + jones[thread_idx, 3] * m_new[3] jones[thread_idx, 2] = jones[thread_idx, 0] * m_new[2] + jones[thread_idx, 2] * m_new[1] jones[thread_idx, 3] = jones[thread_idx, 1] * m_new[2] + jones[thread_idx, 3] * m_new[1]
def coth(x): return cosh(x)/sinh(x)