Example #1
0
 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)))
Example #2
0
 def test_sinh(self):
     self.assertAlmostEqual(qmath.sinh(self.f1), math.sinh(self.f1))
     self.assertAlmostEqual(qmath.sinh(self.c1), cmath.sinh(self.c1))
     self.assertAlmostEqual(qmath.sinh(self.c2), cmath.sinh(self.c2))
     self.assertAlmostEqual(qmath.sinh(Quat(self.f1)), math.sinh(self.f1))
     self.assertAlmostEqual(qmath.sinh(Quat(0, 3)), cmath.sinh(3J))
     self.assertAlmostEqual(qmath.sinh(Quat(4, 5)), cmath.sinh(4 + 5J))
     self.assertAlmostEqual(qmath.sinh(Quat(0, self.f1)), Quat(0, math.sin(self.f1)))
Example #3
0
 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)))
Example #4
0
def sinh(c):
  """Compute Sinh using a Taylor expansion
  """
  if not isinstance(c,pol): return math.sinh(c)
  a0,p=c.separate();
  lst=[math.sinh(a0),math.cosh(a0)]
  for n in range(2,c.order+1):
    lst.append( lst[-2]/n/(n-1))
  return phorner(lst,p)
Example #5
0
 def pieq(self, z, y):
     d = self.line_length
     gamma = cmath.sqrt(z*y)
     Zc = cmath.sqrt(z/y)
     Z_pi = Zc * cmath.sinh(gamma*d) 
     Y_pi = 1.0/Zc * cmath.tanh(gamma*d/2.0) 
     # The real part of Y_pi is different from TLC.for, but
     # the real part isn't important
     return Z_pi, Y_pi
Example #6
0
def sinh(*args, **kw):
    arg0 = args[0]
    if isinstance(arg0, (int, float, long)):
        return _math.sinh(*args,**kw)
    elif isinstance(arg0, complex):
        return _cmath.sinh(*args,**kw)
    elif isinstance(arg0, _sympy.Basic):
        return _sympy.sinh(*args,**kw)
    else:
        return _numpy.sinh(*args,**kw)
 def test_sinh_cc (self):
     src_data = [complex(i,i+1) for i in range(-5, 5, 2)]
     expected_result = tuple(cmath.sinh(i) for i in src_data)
     src = gr.vector_source_c(src_data)
     op = gr.transcendental('sinh', '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 __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()
Example #9
0
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))
Example #10
0
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)
Example #11
0
	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
Example #12
0
def sinh(x):
    """
    Return the hyperbolic sine 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 = sinh(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 = [cosh(x)]
        qc_wrt_args = [sinh(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 [sinh(xi) for xi in x]
#        except TypeError:
        if x.imag:
            return cmath.sinh(x)
        else:
            return math.sinh(x.real)
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
Example #14
0
    def doPhotons(self, filePar):
        self.initHTML()

        #f = ROOT.TFile('ntuple.root')
        #f.cd('CollectionTree')
        #mytree=ROOT.gDirectory.Get('CollectionTree')

        ##################################
        #os.system('ls photons/*root* > ntuples.txt')
        os.system('ls ntuple.root > ntuples.txt')
        f = open('ntuples.txt', 'r')
        lines = f.readlines()
        f.close()

        chain = ROOT.TChain('CollectionTree')

        for li in lines:
            chain.Add('./' + li.strip())

        mytree = chain
        #################################

        m_drmin = ROOT.TH1F("m_drmin", "drmin", 100, -0.2, 0.2)
        m_h1 = ROOT.TH1F("m_h1", "Energy resolution", 100, -0.25, 0.25)
        m_h1.SetXTitle("(E_{t}(reco)-E_{t}(true))/E_{t}(true)")

        m_h2 = ROOT.TH1F("m_h2", "Phi resolution", 100, -0.01, 0.01)
        m_h2.SetXTitle("#Phi resolution (rad)")

        m_h3 = ROOT.TH1F("m_h3", "Eta resolution in the barrel", 100, -0.01,
                         0.01)
        m_h3.SetXTitle("#eta resolution")

        m_h4 = ROOT.TH1F("m_h4", "Eta resolution in the endcap", 100, -0.01,
                         0.01)
        m_h4.SetXTitle("#eta resolution")

        m_h5 = ROOT.TH1F("m_h5", "Efficiency vs eta", 50, -3, 3)
        m_h5.SetXTitle("#eta")

        m_tmp1 = ROOT.TH1F("m_tmp1", "EtaGen", 50, -3, 3)
        m_tmp2 = ROOT.TH1F("m_tmp2", "cl_eta", 50, -3, 3)

        entries = mytree.GetEntriesFast()

        for jentry in xrange(entries):
            ientry = mytree.LoadTree(jentry)
            if ientry < 0:
                break
            nb = mytree.GetEntry(jentry)
            if nb <= 0:
                continue
            nEvent = int(mytree.IEvent)
            if nEvent < 0:
                continue
            dRmin = 999.
            TheNearestCluster = -1

            #print int(mytree.IEvent),int(mytree.cl_nc),len(mytree.PtGen)
            if mytree.cl_nc == 0 or len(mytree.PtGen) == 0:
                continue
            for i in range(0, int(mytree.cl_nc)):
                #print 'i=',i
                dphi = 1000.
                deta = 1000.

                # resolution in energy
                val = ((mytree.cl_et)[i] -
                       (mytree.PtGen)[0]) / (mytree.PtGen)[0]

                m_h1.Fill(val)
                # resolution in phi
                if (mytree.cl_phi)[i] - (mytree.PhiGen)[0] < 6:
                    dphi = ((mytree.cl_phi)[i] - (mytree.PhiGen)[0])
                    m_h2.Fill(dphi)

                # resolution in eta barrel corrected by the z vertex spread
                deta = 0.
                if math.fabs((mytree.EtaGen)[0]) < 1.475:
                    deta = (mytree.cl_eta)[i] - cmath.asinh(
                        cmath.sinh((mytree.EtaGen)[0]) +
                        (mytree.ZV)[mytree.IVPrimary] / 1600.)
                    m_h3.Fill(deta.real)
                elif math.fabs((mytree.EtaGen)[0]) >= 1.475:
                    deta = (mytree.cl_eta)[i] - cmath.asinh(
                        cmath.sinh((mytree.EtaGen)[0]) /
                        (1 - self.mysign((mytree.EtaGen)[0]) *
                         (mytree.ZV)[mytree.IVPrimary] / 3800.))

                    m_h4.Fill(deta.real)

                if (math.fabs(dphi) > math.pi):
                    dphi = 2.0 * math.pi - math.fabs(dphi)
                dR = math.sqrt(deta.real * deta.real + dphi * dphi)
                if dR < dRmin:
                    dRmin = dR
                    TheNearestCluster = i

            m_tmp2.Fill((mytree.EtaGen)[0])
            if TheNearestCluster >= 0 and dRmin < 0.1:
                m_tmp1.Fill((mytree.EtaGen)[0])

        ROOT.gStyle.SetOptFit(1011)

        m_h1.Fit("gaus")
        m_h2.Fit("gaus")
        m_h3.Fit("gaus")
        m_h4.Fit("gaus")

        res1 = self.saveHisto(m_h1, filePar, '')
        res2 = self.saveHisto(m_h2, filePar, '')
        res3 = self.saveHisto(m_h3, filePar, '')
        res4 = self.saveHisto(m_h4, filePar, '')
        m_h5.Divide(m_tmp1, m_tmp2, 1, 1, "B")

        res5 = self.saveHisto(m_h5, filePar, "E")

        if res1 == -1 or res2 == -1 or res3 == -1 or res4 == -1 or res5 == -1:
            return -1
        else:
            return 0
Example #15
0
    def doElectrons(self, filePar):
        self.initHTML()

        #f = ROOT.TFile('ntuple.root')
        #f.cd('CollectionTree')
        #mytree=ROOT.gDirectory.Get('CollectionTree')

        ##################################
        #os.system('ls data/*root.* > ntuples.txt')
        os.system('ls ntuple.root > ntuples.txt')

        f = open('ntuples.txt', 'r')
        lines = f.readlines()
        f.close()

        chain = ROOT.TChain('CollectionTree')

        for li in lines:
            chain.Add('./' + li.strip())

        mytree = chain
        #################################

        m_drmin = ROOT.TH1F("m_drmin", "drmin", 100, -0.2, 0.2)
        m_h1 = ROOT.TH1F("m_h1", "Energy resolution", 100, -0.25, 0.25)
        m_h1.SetXTitle("(E_{t}(reco)-E_{t}(true))/E_{t}(true)")

        m_h2 = ROOT.TH1F("m_h2", "Phi resolution", 100, -0.01, 0.01)
        m_h2.SetXTitle("#Phi resolution (rad)")

        m_h3 = ROOT.TH1F("m_h3", "Eta resolution in the barrel", 100, -0.01,
                         0.01)
        m_h3.SetXTitle("#eta resolution")

        m_h4 = ROOT.TH1F("m_h4", "Eta resolution in the endcap", 100, -0.01,
                         0.01)
        m_h4.SetXTitle("#eta resolution")

        m_h5 = ROOT.TH1F("m_h5", "Efficiency vs eta", 50, -3, 3)
        m_h5.SetXTitle("#eta")

        m_tmp1 = ROOT.TH1F("m_tmp1", "EtaGen", 50, -3, 3)
        m_tmp2 = ROOT.TH1F("m_tmp2", "cl_eta", 50, -3, 3)

        entries = mytree.GetEntriesFast()

        for jentry in xrange(entries):
            ientry = mytree.LoadTree(jentry)
            if ientry < 0:
                break

            nb = mytree.GetEntry(jentry)
            if nb <= 0:
                continue

            nEvent = int(mytree.IEvent)
            if nEvent < 0:
                continue

            indEle = []
            iele = 0
            for ipart in range(0, mytree.NPar):
                if abs((mytree.Type)[ipart]) == 11 and (
                        mytree.GenStat)[ipart] == 1 and (
                            mytree.KMothNt)[ipart] == -1:
                    indEle.append(ipart)
                    m_tmp2.Fill((mytree.EtaGen)[indEle[iele]])

                    iele += 1

                    if iele > 1:
                        logger.info('two many electrons')
                        return -1

            nele = iele

            # a quel cluster correspond quel electron ?
            # je tourne sur ts les clusters de l ev
            for ic in range(0, mytree.cl_nc):
                etacl = (mytree.cl_eta)[ic]
                phicl = (mytree.cl_phi)[ic]
                etcl = (mytree.cl_et)[ic]

                m_drmin.Fill((mytree.ZV)[0])
                etae = (mytree.EtaGen)[indEle[0]]
                if math.fabs((mytree.cl_eta)[ic]) > 1.475:
                    etaclcor = cmath.asinh(
                        cmath.sinh((mytree.cl_eta)[ic]) *
                        (1 - (mytree.ZV)[mytree.IVPrimary] / (self.mysign(
                            (mytree.cl_eta)[ic]) * 3800.0)))
                    phiclcor = (mytree.cl_phi)[ic] + (
                        0.3 * 3800.0 *
                        (-(mytree.Type)[indEle[0]] / 11.0) * self.mysign(
                            (mytree.cl_eta)[ic])) / (
                                (mytree.cl_et)[ic] * cmath.sinh(
                                    (mytree.cl_eta)[ic]))
                    m_h4.Fill((etaclcor - etae).real)
                else:
                    etaclcor = cmath.asinh(
                        cmath.sinh((mytree.cl_eta)[ic]) -
                        (mytree.ZV)[mytree.IVPrimary] / 1600.0)
                    m_h3.Fill((etaclcor - etae).real)
                    phiclcor = (mytree.cl_phi)[ic] + (
                        0.3 * 1600.0 * (-(mytree.Type)[indEle[0]] / 11.0) /
                        (mytree.cl_et)[ic])

                phie = (mytree.PhiGen)[indEle[0]]
                ete = (mytree.PtGen)[indEle[0]]

                try:
                    m_h2.Fill(phiclcor.real - phie)
                except:
                    m_h2.Fill(phiclcor - phie)
                m_h1.Fill((etcl - ete) / ete)

                m_tmp1.Fill(etae)

        ROOT.gStyle.SetOptFit(1011)

        m_h1.Fit("gaus")
        m_h2.Fit("gaus")
        m_h3.Fit("gaus")
        m_h4.Fit("gaus")

        res1 = self.saveHisto(m_h1, filePar, '')
        res2 = self.saveHisto(m_h2, filePar, '')
        res3 = self.saveHisto(m_h3, filePar, '')
        res4 = self.saveHisto(m_h4, filePar, '')
        m_h5.Divide(m_tmp1, m_tmp2, 1, 1, "B")

        res5 = self.saveHisto(m_h5, filePar, "E")

        if res1 == -1 or res2 == -1 or res3 == -1 or res4 == -1 or res5 == -1:
            return -1
        else:
            return 0
print(cmath.acos(z))

#3.atan()- This function returns the arc tangent of a complex number passed in as a argument.
import cmath
x = 1.0
y = 1.0
z = complex(x, y)
print(cmath.atan(z))

#Hyperbolic functions:
#1.sinh()- This function returns the hyperbolic sine of a complex number passed in as a argument.
import cmath
x = 1.0
y = 1.0
z = complex(x, y)
print(cmath.sinh(z))

#2.cosh()- This function returns the hyperbolic cosine of a complex number passed in as a argumnet.
import cmath
x = 1.0
y = 2.0
z = complex(x, y)
print(cmath.cosh(z))

#3.tanh()- This function returns the hyperbolic tangent of a complex number passed as a argument.
import cmath
x = 1.0
y = 1.0
z = complex(x, y)
print(cmath.tanh(z))
Example #17
0
def birefringence_rot(s, chi, lambda_0, n_o, n_e, jones, 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 = rand_nums[seed]
            theta = cmath.pi * rand_num
            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]
Example #18
0
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
Example #19
0
def sinh(x):
    if isinstance(x, complex):
        return cmath.sinh(x)
    else:
        return math.sinh(x)
Example #20
0
def backgroundCalc(epsilon, M, corPar, MS, MODB, windCpx,
                   tempAtm, tempSurf, roughLength_m,
                   roughLength_h, refLevel):
    '''
    calculate parameters of background atmosphere: friction velocity, temperature scale,
    Ekman depth, geostrophic wind and temperature in free atmosphere
    input:
        epsilon - main fitting parameter of the model,
        M - constant,
        corPar - Coriolis parameter,
        MS - "0" if background is land and "1" if sea,
        MODB - ,
        windCpx - wind at reference level (complex),
        tempAtm - temperature of background atmosphere at reference level,
        tempSurf - background surface temperature,
        roughLength_m - roughness length for momentum for background surface,
        roughLength_h - roughness length for heat for background surface,
        refLevel - reference level, m

    output:
        stratPar - stratification parameter, mu,
        EkmanDepth ,
        frVelCpx - friction velocity for background atmosphere< complex number,
        tempScale - temperature scale for background atmosphere,
        roughLength_m - roughness length for momentum for background surface,
        roughLength_heat - roughness length for heat for background surface,
        tempTop - temperature in free atmosphere,
        gam - ,
        tempSurf - background surface temperature,
        geostrWindCpx - geostrophic wind, complex number
    '''

    CHARNOCKCONST = 0.018
    GRAVITYACC = 9.8
    VONKARMANCONST = 0.41
    BETA = GRAVITYACC / 300.
    VA = 14e-6

    #Iteration for the drag coefficient

    it = 0
    mistake = 1
    DragCoeff = 0.5e-3
    tmpFrVelCpx = math.sqrt(DragCoeff) * windCpx
    stratPar = VONKARMANCONST ** 2. * BETA * (tempAtm - tempSurf) / (corPar * abs(windCpx))
    XX = []
    YY = []
    while mistake > 0.0001:
        it += 1
        tmpFrVel = abs(tmpFrVelCpx)
        roughLength_m = roughLength_m * (1 - MS) + \
                        (CHARNOCKCONST * tmpFrVel ** 2. / GRAVITYACC +
                         0.14 * VA / tmpFrVel) * MS
        lambInv = 1. / lambdaCalc(epsilon, stratPar)
        EkmanDepth = VONKARMANCONST * tmpFrVel / (corPar * lambInv)
        SBLHeight = epsilon * EkmanDepth
        dH = refLevel / EkmanDepth
        dH1 = min(dH, M)
        if dH <= epsilon:
            stratPar1 = dH / epsilon * stratPar
            profileFunc_m = profileFunc_momentum_Calc(lambInv, epsilon, stratPar1)
            profileFunc_h = profileFunc_heat_Calc(lambInv, epsilon, stratPar1)
            frVelCpx = VONKARMANCONST * windCpx /\
                       (math.log(tmpFrVel / (corPar * roughLength_m)) +
                        math.log(VONKARMANCONST * dH / lambInv) - profileFunc_m)
            tempScale = VONKARMANCONST * (tempAtm - tempSurf) /\
                        (math.log(tmpFrVel / (corPar * roughLength_h)) +
                         math.log(VONKARMANCONST * dH / lambInv) - profileFunc_h)
        else:
            profileFunc_m = profileFunc_momentum_Calc(lambInv, epsilon, stratPar)
            profileFunc_h = profileFunc_heat_Calc(lambInv, epsilon, stratPar)
            Coeff = cmath.tanh((1 + 1j) * (M - epsilon))
            Coeff *= (1 - cmath.sinh((1 + 1j) * (M - dH1)) / cmath.sinh((1 + 1j) * (M - epsilon)))
            A = lambInv * Coeff
            B = - A + profileFunc_m  - math.log(VONKARMANCONST * epsilon / lambInv)
            C = -2. * lambInv * (dH - epsilon) + profileFunc_h -\
                math.log(VONKARMANCONST * epsilon / lambInv)
            frVelCpx = VONKARMANCONST * windCpx / \
                       (math.log(tmpFrVel / (corPar * roughLength_m))- B - 1j * A)
            tempScale = VONKARMANCONST * (tempAtm - tempSurf) /\
                                      (math.log(tmpFrVel / (corPar * roughLength_h)) - C)
        mistake = abs(tmpFrVelCpx - frVelCpx) / abs(tmpFrVelCpx)
        tmpFrVelCpx = 0.3 * frVelCpx + 0.7 * tmpFrVelCpx
        tmpFrVel = abs(tmpFrVelCpx)
        stratPar = VONKARMANCONST ** 2 * BETA * tempScale / (corPar * tmpFrVel)
        if it > 100:
            print 'error in backgroundCalc'
            break
    A = lambInv * cmath.tanh((1 + 1j) * (M - epsilon))
    B = - A + profileFunc_momentum_Calc(lambInv, epsilon, stratPar) - math.log(VONKARMANCONST * epsilon / lambInv)
    C = -2 * lambInv * (M - epsilon) + profileFunc_heat_Calc(lambInv, epsilon, stratPar) -\
        math.log(VONKARMANCONST * epsilon / lambInv)
    geostrWindCpx = tmpFrVelCpx / VONKARMANCONST * \
                             (math.log(tmpFrVel / (corPar * roughLength_m))
                              - B - 1j * A)
    tempTop = tempSurf + tempScale / VONKARMANCONST * (math.log(tmpFrVel / (corPar * roughLength_h)) - C)
    gam = 2 * tempScale * abs(frVelCpx) / EkmanDepth ** 2 / corPar
    RES = [stratPar, EkmanDepth, frVelCpx, tempScale, roughLength_m,
           roughLength_h, tempTop, gam, tempSurf, geostrWindCpx]
    return RES
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 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)
Example #23
0
    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
Example #24
0
    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)
Example #25
0
    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)
Example #26
0
def A2_rho(theta, u, t):
    return - theta[4]*1j*u*(2 + t*ksi(theta, u))*(ksi(theta, u)*cmath.cosh(d(theta, u)*t/2) + \
                                                  d(theta, u)*cmath.sinh(d(theta, u)*t/2))/(2*d(theta, u)*theta[0])
Example #27
0
def sinh(x):
    if is_complex(x):
        return cmath.sinh(x)
    return math.sinh(x)
#------------------------------------------------------------------------------
# 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

assert round(0.5) == 1
Example #29
0
c = 2 + 2j
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
Example #30
0
 def sin_impl(z):
     """cmath.sin(z) = -j * cmath.sinh(z j)"""
     r = cmath.sinh(complex(-z.imag, z.real))
     return complex(r.imag, -r.real)
Example #31
0
def coth(x):
    return cosh(x)/sinh(x)
Example #32
0
def A2(theta, u, t):
    return d(theta, u) * cmath.cosh(d(theta, u) * t / 2) / theta[0] + ksi(
        theta, u) * cmath.sinh(d(theta, u) * t / 2) / theta[0]
Example #33
0
 def mycotanh(z):
     return cmath.cosh(z) / cmath.sinh(z)
Example #34
0
 def __new__(cls, argument):
     if isinstance(argument, (RealValue, Zero)):
         return FloatValue(math.sinh(float(argument)))
     if isinstance(argument, (ComplexValue)):
         return ComplexValue(cmath.sinh(complex(argument)))
     return MathFunction.__new__(cls)
Example #35
0
    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))
Example #36
0
def sinh_usecase(x):
    return cmath.sinh(x)
Example #37
0
 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)
Example #38
0
 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
Example #39
0
 def mycotanh(z):
     return cmath.cosh(z)/cmath.sinh(z)
Example #40
0
    def doTop(self, filePar):
        self.initHTML()

        f = ROOT.TFile('ntuple.root')
        #f.cd('CollectionTree')
        mytree = ROOT.gDirectory.Get('CollectionTree')

        m_drmin = ROOT.TH1F("m_drmin", "drmin", 100, -0.2, 0.2)
        m_h1 = ROOT.TH1F("m_h1", "Energy resolution", 100, -0.25, 0.25)
        m_h1.SetXTitle("(E_{t}(reco)-E_{t}(true))/E_{t}(true)")

        m_h2 = ROOT.TH1F("m_h2", "Phi resolution", 100, -0.01, 0.01)
        m_h2.SetXTitle("#Phi resolution (rad)")

        m_h3 = ROOT.TH1F("m_h3", "Eta resolution in the barrel", 100, -0.01,
                         0.01)
        m_h3.SetXTitle("#eta resolution")

        m_h4 = ROOT.TH1F("m_h4", "Eta resolution in the endcap", 100, -0.01,
                         0.01)
        m_h4.SetXTitle("#eta resolution")

        m_h5 = ROOT.TH1F("m_h5", "Efficiency vs eta", 50, -3, 3)
        m_h5.SetXTitle("#eta")

        m_tmp1 = ROOT.TH1F("m_tmp1", "EtaGen", 50, -3, 3)
        m_tmp2 = ROOT.TH1F("m_tmp2", "cl_eta", 50, -3, 3)

        entries = mytree.GetEntriesFast()

        for jentry in xrange(entries):
            ientry = mytree.LoadTree(jentry)
            if ientry < 0:
                break

            nb = mytree.GetEntry(jentry)
            if nb <= 0:
                continue

            nEvent = int(mytree.IEvent)
            if nEvent < 0:
                continue

            indEle = []
            iele = 0
            for ipart in range(0, mytree.NPar):
                if abs((mytree.Type)[ipart]) == 11 and abs(
                    (mytree.Type)[(mytree.KMothNt)[ipart]]) == 24:
                    #indEle[iele]=ipart
                    indEle.append(ipart)
                    m_tmp2.Fill((mytree.EtaGen)[indEle[iele]])
                    iele = +1
                    if iele > 4:
                        logger.info('two many electrons')
                        return -1

            nele = iele

            # a quel cluster correspond quel electron ?
            # je tourne sur ts les clusters de l ev
            for ic in range(0, mytree.cl_nc):
                drmin = 9999.
                im = 0

                # pour un cluster donne je tourne sur tous les electrons primaires trouves precedemment et je minimise dr pour savoir celui qui est le plus pres du cluster
                for iele in range(0, nele):
                    deta = (mytree.EtaGen)[indEle[iele]] - (mytree.cl_eta)[ic]
                    dphi = (mytree.PhiGen)[indEle[iele]] - (mytree.cl_phi)[ic]

                    if dphi > math.pi:
                        dphi = math.fabs(dphi) - 2. * math.pi
                    dr = math.sqrt(dphi * dphi + deta * deta)

                    if dr < drmin:
                        drmin = dr
                        im = iele

                # l'electron matchant le cluster a l'indice im

                m_drmin.Fill(drmin)

                if drmin < 0.1:
                    etacl = (mytree.cl_eta)[ic]
                    phicl = (mytree.cl_phi)[ic]
                    etcl = (mytree.cl_et)[ic]
                    etae = (mytree.EtaGen)[indEle[im]]
                    if math.fabs((mytree.cl_eta)[ic]) > 1.475:
                        etaclcor = cmath.asinh(
                            cmath.sinh((mytree.cl_eta)[ic]) *
                            (1 - (mytree.ZV)[mytree.IVPrimary] / (self.mysign(
                                (mytree.cl_eta)[ic]) * 3800.0)))
                        phiclcor = (mytree.cl_phi)[ic] + (
                            0.3 * 3800 *
                            (-(mytree.Type)[indEle[im]] / 11.0) * self.mysign(
                                (mytree.cl_eta)[ic])) / (
                                    (mytree.cl_et)[ic] * cmath.sinh(
                                        (mytree.cl_eta)[ic]))
                        m_h4.Fill((etaclcor - etae).real)
                    else:
                        etaclcor = cmath.asinh(
                            cmath.sinh((mytree.cl_eta)[ic]) -
                            (mytree.ZV)[mytree.IVPrimary] / 1600.0)
                        phiclcor = (mytree.cl_phi)[ic] + (
                            0.3 * 1600.0 *
                            (-(mytree.Type)[indEle[im]] / 11.0) /
                            (mytree.cl_et)[ic])
                        m_h3.Fill((etaclcor - etae).real)

                    phie = (mytree.PhiGen)[indEle[im]]
                    ete = (mytree.PtGen)[indEle[im]]

                    try:
                        m_h2.Fill(phiclcor.real - phie)
                    except:
                        m_h2.Fill(phiclcor - phie)
                    m_h1.Fill((etcl - ete) / ete)
                    m_tmp1.Fill(etae)

        ROOT.gStyle.SetOptFit(1011)

        m_h1.Fit("gaus")
        m_h2.Fit("gaus")
        m_h3.Fit("gaus")
        m_h4.Fit("gaus")

        res1 = self.saveHisto(m_h1, filePar, '')
        res2 = self.saveHisto(m_h2, filePar, '')
        res3 = self.saveHisto(m_h3, filePar, '')
        res4 = self.saveHisto(m_h4, filePar, '')
        m_h5.Divide(m_tmp1, m_tmp2, 1, 1, "B")

        res5 = self.saveHisto(m_h5, filePar, "E")

        if res1 == -1 or res2 == -1 or res3 == -1 or res4 == -1 or res5 == -1:
            return -1
        else:
            return 0
Example #41
0
 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
Example #42
0
 def sin_impl(z):
     """cmath.sin(z) = -j * cmath.sinh(z j)"""
     r = cmath.sinh(complex(-z.imag, z.real))
     return complex(r.imag, -r.real)
Example #43
0
def p_expression_senh(t):
    'expression : SENH expression'
    t[0] = cmath.sinh(t[2])
Example #44
0
 def __new__(cls, argument):
     if isinstance(argument, (RealValue, Zero)):
         return FloatValue(math.sinh(float(argument)))
     if isinstance(argument, (ComplexValue)):
         return ComplexValue(cmath.sinh(complex(argument)))
     return MathFunction.__new__(cls)
Example #45
0
def IBLLogCalc(epsilon, M, corPar, MS, MODB, stratPar_back, EkmanDepth_back, frVelCpx_back,
            tempScale_back, roughLength_m_back, roughLength_h_back, tempTop, gam, tempSurf_back,
            geostrWindCpx, d, tempSurf, roughLength_h, roughLength_m, stratPar, frVelCpx, tempScale, MOD=None):

    CHARNOCKCONST = 0.018
    GRAVITYACC = 9.8
    VONKARMANCONST = 0.41
    BETA = GRAVITYACC / 300
    VA = 14e-6

    SBLHeight_back = epsilon * EkmanDepth_back
    K_back = EkmanDepth_back ** 2 * corPar / 2
    K = K_back
    geostrWind = abs(geostrWindCpx)
    angle = cmath.phase(geostrWindCpx)

    # iteration for the drag coefficient
    it = 0
    mistake = 1
    tmpFrVelCpx = frVelCpx
    tmpTempScale = tempScale
    K_back = EkmanDepth_back ** 2 * corPar / 2
    gama = max(0, gam)
    lambInv_back = 1 / lambdaCalc(epsilon, stratPar_back)
    while mistake > 0.0001:
        it += 1
        tmpFrVelCpx = 0.3 * frVelCpx + 0.7 * tmpFrVelCpx
        tmpFrVel = abs(tmpFrVelCpx)
        tmpTempScale = 0.3 * tempScale + 0.7 * tmpTempScale
        heatFlux = - tmpFrVel * tempScale
        stratPar = VONKARMANCONST ** 2 * BETA * tmpTempScale / (corPar * tmpFrVel)
        roughLength_m = roughLength_m * MS + \
                        (CHARNOCKCONST * tmpFrVel ** 2 / GRAVITYACC + 0.14 * VA / tmpFrVel) * (1 - MS)
        lambInv = 1 / lambdaCalc(epsilon, stratPar)
        if MOD != 'initial':
            tmpStratPar = stratPar * d / epsilon
        else:
            tmpStratPar = stratPar * d / EkmanDepth_back / epsilon
        profileFunc_m = profileFunc_momentum_Calc(lambInv, epsilon, tmpStratPar)
        profileFunc_h = profileFunc_heat_Calc(lambInv, epsilon, tmpStratPar)
        EkmanDepth = VONKARMANCONST * tmpFrVel / (corPar * lambInv)
        SBLHeight = epsilon * EkmanDepth
        K = EkmanDepth ** 2 * corPar / 2
        if MOD != 'initial':
            delta = EkmanDepth * d
        else:
            delta = d
        if delta <= SBLHeight_back:
            tmpStratPar_back = stratPar_back * delta / SBLHeight_back
            profileFunc_m_back = profileFunc_momentum_Calc(lambInv_back, epsilon, tmpStratPar_back)
            profileFunc_h_back = profileFunc_heat_Calc(lambInv_back, epsilon, tmpStratPar_back)
            windCpx_back = frVelCpx_back / VONKARMANCONST * (math.log(delta / roughLength_m_back) - profileFunc_m_back)
            temp = tempSurf_back + tempScale_back / VONKARMANCONST *\
                   (math.log(delta / roughLength_h_back) - profileFunc_h_back)
        else:
            dm = M - epsilon
            ksi = (delta - SBLHeight_back) / (EkmanDepth_back * dm)
            tmpKsi = ksi
            ksi = min(1, ksi)
            Coeff = (1 -1j) * cmath.sinh((1 + 1j) * dm * (1 - ksi)) / cmath.cosh((1 + 1j) * dm)
            windCpx_back = geostrWindCpx - lambInv_back * frVelCpx_back / VONKARMANCONST * Coeff
            temp = tempTop - 2 * lambInv_back * tempScale_back / VONKARMANCONST * dm * (1 - tmpKsi)
        if gam <= 0:
            alg = 1
            epst = 0
        else:
            alg = (abs(heatFlux) + abs(gama * K_back)) / (abs(heatFlux) + abs(gama * K))
            alg = min(1, alg)
            epst = max(0, 1 / 4 * heatFlux / (K * gama * alg))
        temp -= epst * gama * delta
        frVelCpx = VONKARMANCONST * windCpx_back / (math.log(delta / roughLength_m) - profileFunc_m)
        tempScale = VONKARMANCONST * (temp - tempSurf) / (math.log(delta / roughLength_h) - profileFunc_h)
        mistake = abs(tmpFrVelCpx - frVelCpx) / abs(tmpFrVelCpx)
        if it > 100:
            print 'error in IBLCalc'
            alpha = alg * (1 - (delta / (M * EkmanDepth)) ** 4)
            break
    alpha = alg * (1 - (delta / (M * EkmanDepth)) ** 4)
    RES = [stratPar, EkmanDepth, frVelCpx, tempScale, temp, roughLength_m, windCpx_back, alpha, epst]
    return RES
Example #46
0
def sinh_usecase(x):
    return cmath.sinh(x)
Example #47
0
#------------------------------------------------------------------------------
# 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

assert round(0.5) == 1
Example #48
0
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
Example #49
0
File: fr.py Project: dave2pi/davepy
	def Coth(x):
		return cmath.cosh(x)/cmath.sinh(x)
c = 2 + 2j
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 test_sinh(self):
     self.assertAlmostEqual(complex(-6.54812, -7.61923),
                            cmath.sinh(complex(3, 4)))
Example #52
0
 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) 
Example #53
0
def A1(theta, u, t):
    return (u * u + 1j * u) * cmath.sinh(d(theta, u) * t / 2)
Example #54
0
    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)
Example #55
0
    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
Example #56
0
complex_functions = {'sin': lambda x: cmath.sin(x), 
                    '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 
Example #57
0
def SINH(df, price='Close'):
    """
    Hyperbolic Sine
    Returns: list of floats = jhta.SINH(df, price='Close')
    """
    return [cmath.sinh(df[price][i]).real for i in range(len(df[price]))]
Example #58
0
def p_expression_csch(t):
    'expression : CSCH expression'
    t[0] = 1/cmath.sinh(t[2])
Example #59
0
 def test_sinh(self):
     self.assertAlmostEqual(complex(-6.54812, -7.61923),
                            cmath.sinh(complex(3, 4)))